The C Standard, Annex K (normative), "Bounds-Checking Interfaces" [ISO/IEC 9899:2011], defines defines alternative versions of standard string-handling functions designed to be safer replacements for existing functions. For example, it defines the strcpy_s()
, strcat_s()
, strncpy_s()
, and strncat_s()
functions as replacements for strcpy()
, strcat()
, strncpy()
, and strncat()
, respectively.
...
However, the call to copy src2
to dst2
fails because insufficient space is available to copy the entire string, which consists of eight characters, to the destination buffer. As a result, r2
is assigned a nonzero value and dst2[0]
is set to the null character.
Users of the C11 C Standard Annex K functions are less likely to introduce a security flaw because the size of the destination buffer and the maximum number of characters to append must be specified. ISO/IEC TR 24731 Part II [ISO/IEC TR 24731-2:2010] offers another approach, supplying functions that allocate enough memory for their results. ISO/IEC TR 24731 Part II functions also ensure null termination of the destination string.
C11 The C Standard Annex K functions are still capable of overflowing a buffer if the maximum length of the destination buffer and number of characters to copy are incorrectly specified. ISO/IEC TR 24731 Part II functions can make it more difficult to keep track of memory that must be freed, leading to memory leaks. As a result, the C11 C Standard Annex K and the ISO/IEC TR 24731 Part II functions are not particularly secure but may be useful in preventive maintenance to reduce the likelihood of vulnerabilities in an existing legacy code base.
...
Code Block | ||||
---|---|---|---|---|
| ||||
void complain(const char *msg) { errno_t err; static const char prefix[] = "Error: "; static const char suffix[] = "\n"; char buf[BUFSIZ]; /* * Ensure that more than one character * is available for msg */ static_assert(sizeof(buf) > sizeof(prefix) + sizeof(suffix), "Buffer for complain() is too small"); strcpy(buf, prefix); err = strcat_s(buf, sizeof(buf), msg); if (err != 0) { /* Handle error */ } err = strcat_s(buf, sizeof(buf), suffix); if (err != 0) { /* Handle error */ } fputs(buf, stderr); } |
...
String-handling functions defined in the C Standard, subclause 7.24 [ISO/IEC 9899:2011], and elsewhere are susceptible to common programming errors that can lead to serious, exploitable vulnerabilities. Proper use of the C11 Annex K functions can eliminate most of these issues.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR07-C | highHigh | probableProbable | mediumMedium | P12 | L1 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
|
|
| |||||||
PRQA QA-C |
| Warncall -wc strcpy -wc strcat -wc strncpy -wc strncat | Partially implemented |
...