VNX-122: Heap-based buffer overflow from an undersized string allocation
Reports C/C++ heap buffers sized by strlen() with no room for the terminator and then filled with strcpy/strcat/sprintf, and fixed-size heap buffers that receive an unbounded strcpy, strcat, gets or sprintf %s copy.
| Field | Value |
|---|---|
| Rule ID | VNX-122 |
| Severity | Medium |
| SARIF level | warning |
| Kind | sast |
| Languages | C, C++ |
| CWE | CWE-122 |
| CAPEC | CAPEC-97 |
| ATT&CK | T1557 |
| CWSS vector | CWSS:1.0/TI:M/AP:RU/AL:S/IC:N/FC:LT/RP:RU/RL:S/AV:L/AS:N/IN:A/SC:A/BI:M/DI:H/EX:M/EC:N/P:C |
| Tags | heap-overflow memory c cwe-122 |
| Source | internal/sast/rules/vnx-122.rego |
Overview
VNX-122 maps to CWE-122: Heap-based Buffer Overflow. It reports two concrete shapes:
- A string buffer allocated with
malloc/xmallocornew char[]sized bystrlen()alone (or a sum ofstrlen()calls, or a variable assigned fromstrlen()just above) with no+ 1, which astrcpy,strcat,sprintforstpcpyinto it then overruns by one byte. The allocation line is reported. - A heap buffer allocated with a fixed size (a number, an upper-case constant or a
sizeof) that then receives an unbounded copy:strcpy/strcatfrom a non-literal source,gets(), orsprintfwith an unbounded%s. The copy line is reported.
What Gets Flagged
char *out = malloc(strlen(name)); // FLAGGED: no room for the NUL
strcpy(out, name);
char *buf = (char *)malloc(64);
strcpy(buf, argv[1]); // FLAGGED: unbounded copy into 64 bytes
char *p = new char[256];
sprintf(p, "%s/%s", dir, file); // FLAGGED
What Is Not Flagged
malloc(strlen(s) + 1),strdup(),snprintf(),strncpy()and%.40sprecision.- Byte buffers filled with
memcpy(no terminator is needed). strcpyof a string literal, and copies preceded by astrlen()/strnlen()check between the allocation and the copy.- Stack buffers, computed sizes and flows across functions (out of scope).
Remediation
Allocate strlen(s) + 1 bytes for a copy of s, and use bounded copies (snprintf, strlcpy) sized by the allocation, or size the allocation from the input.
References
- CWE-122: Heap-based Buffer Overflow
- SEI CERT STR31-C: Guarantee that storage for strings has sufficient space
Suppressing this rule
Put a nosec comment on the line, or on line 1 to cover the whole file. Use the comment marker of the file’s language (#, //, -- or ;):
# nosec vnx-122
// nosec vnx-122
Or record an ignore rule: vulnetix ignore add --rule vnx-122 --reason "...". See Suppressing findings.