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

Compare with Current View Page History

« Previous Version 9 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 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.

#define A_SIZE 16
char *string_data;
char a[A_SIZE];
...
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

Example using strncpy_s()

The strncpy_s function copies not more than n successive characters (characters that
follow a null character are not copied) from the array pointed to by s2 to the array
pointed to by s1. If no null character was copied from s2, then s1n is set to a null
character.

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

  • No labels