Non-Compliant Code Example
These two lines of code assume that gets()
will not read more than BUFSIZ
characters from stdin
. This is an invalid assumption and the resulting operation can result in a buffer overflow.
char buf[BUFSIZ + 1]; gets(buf);
Non-Compliant Code Example
The standard function strncpy()
and strncat()
do not guarantee that the resulting string is null terminated. If there is no null character in the first n characters of the source array pointed the result is not be null-terminated as in the following example:
char a[16]; strncpy(a, "0123456789abcdef", sizeof(a));
Compliant Solution 1
The correct solution depends on the original intent. If your intent was to truncate a string but ensure that the
result was a null-terminated string the following solution can be used.
char a[16]; strncpy(a, "0123456789abcdef", sizeof(a)-1); a[sizeof(a)] = '\0';
Compliant Solution 2
Example using strcpy()
Compliant Solution 3
Example using strncpy_s()
Exception
An exception to this rule applies if the intent of the programmer was to convert a null-terminated byte string to a character array. To be compliant with this standard, this intent must be made clear statement in comments.
Priority: P12 Level: L1
Failure to properly null terminate null-termianted byte strings can result in buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process by an attacker.
Component |
Value |
---|---|
Severity |
3 (medium) |
Likelihood |
2 (probable) |
Remediation cost |
2 (medium) |
References
- ISO/IEC 9899-1999 Section 7.1.1 Definitions of terms, Section 7.21 String handling <string.h>
- Seacord 05 Chapter 2 Strings
- ISO/IEC TR 24731-2006 Section 6.7.1.3 The strcpy_s function