Null-terminated byte strings are, by definition, null-terminated. String operations cannot determine the length or end of strings that are not properly null-terminated which can consequently result in buffer overflows and other undefined behavior.
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 programmers 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
If the intent is to copy without truncation, this example will copy the data and guarantee that the resulting null-terminated byte string is null-terminated. If the string cannot be copied it is handled as an error condition.
char *string_data = "0123456789abcdef"; char a[16]; ... if (string_data) { if (strlen(string_data) < sizeof(a)) { strcpy(a, string_data); } else { /* handle string too large condition */ } } else { /* handle null string condition */ }
Compliant Solution 3
The strncpy_s()
function copies not more than a maximum number n
of successive characters (characters that follow a null character are not copied) from the source array to a destination array. If no null character was copied from the source array, then the nth position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.
This compliant solution also guarantees that the string is null-terminated.
#define A_SIZE 16 char *string_data; char a[A_SIZE]; ... if (string_data) { strncpy_s(a, sizeof(a), string_data, 5); } else { /* handle null string condition */ }
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 (high) |
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.4 The strncpy_s function