...
These functions truncate strings that exceed the specified limits. Additionally, some functions, such as strncpy()
, do not guarantee that the resulting string is null-terminated. (See STR32-C. Null-terminate byte strings as required.)
...
This solution requires that string_data
is null-terminated; that is, a null byte can be found within the bounds of the referenced character array. Otherwise, strlen()
will stray into other objects before finding a null byte.
Compliant Solution (strcpy_s()
, C11 Annex K)
The strcpy_s()
function defined in C11 Annex K [ISO/IEC 9899:2011] , which provides provides additional safeguards, including accepting the size of the destination buffer as an additional argument. (See STR07-C. Use the bounds-checking interfaces for remediation of existing string manipulation code.) Also, strnlen_s()
accepts a maximum-length argument for strings that may not be null-terminated.
...
If a runtime-constraint error is detected by either the call to either strnlen_s()
or strcpy_s()
, the currently registered runtime-constraint handler is invoked. See ERR03-C. Use runtime-constraint handlers when calling the bounds-checking interfaces for more information on using runtime-constraint handlers with C11 Annex K functions.
...
STR03-EX1: The intent of the programmer is to intentionally purposely truncate the null-terminated byte string.
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
|
| Could detect violations in the following manner: all calls to | |||||||
5.0 |
| Can detect violations of this rule with CERT C Rule Pack | |||||||
| NNTS |
| |||||||
| 115 S | Fully implemented |
...
CERT C++ Secure Coding Standard | STR03-CPP. Do not inadvertently truncate a null-terminated character array | ISO/IEC 9899:2011 | K.3.7.1.3 "The strcpy_s Function" |
ISO/IEC TR 24772:2013 | String Termination [CJM] | ||
MITRE CWE | CWE-170, Improper null termination CWE-464, Addition of data structure sentinel |
Bibliography
[ISO/IEC 9899:2011] | Subclause K.3.7.1.3 "The strcpy_s Function" |
[Seacord 2013] | Chapter 2, "Strings" |
...