Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
Null-terminated byte strings (NTBS) must contain a null-termination character at or before the address of the last element of the array before they can be safely passed as arguments to standard string-handling functions, such as {{strcpy()}} or {{strlen()}}.  This is because these functions, as well as other string-handling functions defined by C99 \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\], depend on the existence of a null-termination character to determine the length of a string.  Similarly, NTBS must be null terminated before iterating on a character array where the termination condition of the loop depends on the existence of a null-termination character within the memory allocated for the string, as in the following example:

...

Wiki Markup
The standard {{strncpy()}} function does not guarantee that the resulting string is null terminated \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\]. If there is no null character in the first {{n}} characters of the {{source}} array, the result maycould not be null terminated.

In the first noncompliant code example, ntbs is null terminated before the call to strncpy(). However, the subsequent execution of strncpy() may can overwrite the null-termination character.

...

The correct solution depends on the programmer's intent. If the intent was to truncate a string but ensure while ensuring that the result remains a null-terminated string, this solution can be used:

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: STR32-CPP. Null-terminate character arrays as required

...

Wiki Markup\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 7.1.1, "Definitions of terms," Section 7.20.3.4 "The realloc function," and Section 7.21, "String handling <string.h>" \[[

ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] TR 24772 "CJM String Termination"

\[[ISO/IEC TR 24731-1:2007|AA. Bibliography#ISO/IEC TR 24731-1-2007]\] Section 6.7.1.4, "The strncpy_s function"

MITRE CWE: CWE-119, "Failure to Constrain Operations within the Bounds of an Allocated Memory Buffer"

MITRE CWE: CWE-170, "Improper Null Termination"

Bibliography

Wiki Markup

\[[MITRE 2007|AA. Bibliography#MITRE 07]\] [CWE ID 119|http://cwe.mitre.org/data/definitions/119.html], "Failure to Constrain Operations within the Bounds of an Allocated Memory Buffer," [CWE ID 170|http://cwe.mitre.org/data/definitions/170.html], "Improper Null Termination"
\[[Schwarz 2005|AA. Bibliography#Schwarz 05]\]
\[[Seacord 2005a|AA. Bibliography#Seacord 05]\] Chapter 2, "Strings"
\[[Viega 2005|AA. Bibliography#Viega 05]\] Section 5.2.14, "Miscalculated NULL termination"

...