You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 14 Next »

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 functions 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, the result may not be null-terminated, as in this example:

char a[16];
strncpy(a, "0123456789abcdef", sizeof(a));

Compliant Solution 1

The correct solution depends on the programmer's intent. If the intent was to truncate a string but ensure that the result was a null-terminated string, this 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 is to convert a null-terminated byte string to a character array.  To be compliant with this standard, this intent must be clearly stated in comments.

Priority: P12 Level: L1

Failure to properly null terminate null-terminated 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

  • No labels