VNX-690: Unchecked return value to NULL pointer dereference
Reports the result of malloc, calloc, realloc, strdup, strndup, fopen or getenv dereferenced (p->f, p[i], *p, or passed to strcpy, memset, fprintf, strlen, atoi and similar) before any NULL test, including getenv() passed straight to such a call or used to construct a std::string.
| Field | Value |
|---|---|
| Rule ID | VNX-690 |
| Severity | Low |
| SARIF level | note |
| Kind | sast |
| Languages | C, C++ |
| CWE | CWE-690 |
| CAPEC | CAPEC-66 |
| ATT&CK | T1190 |
| CWSS vector | CWSS:1.0/TI:L/AP:RU/AL:S/IC:N/FC:LT/RP:RU/RL:S/AV:L/AS:N/IN:A/SC:A/BI:L/DI:H/EX:L/EC:N/P:L |
| Tags | unchecked-return-to-null null-dereference cwe-690 |
| Source | internal/sast/rules/vnx-690.rego |
Overview
VNX-690 maps to CWE-690: Unchecked Return Value to NULL Pointer Dereference. Allocation functions, fopen and getenv report failure by returning NULL. When the caller dereferences the result without testing it, the failure becomes a crash (and, on some platforms, a write to a low address).
The rule reports, in C and C++ files:
- the result of
malloc,calloc,realloc,strdup,strndup,fopenorgetenvassigned to a variable that, within the next six code lines and with no NULL test in between, is dereferenced (p->f,p[i],*p) or passed to a libc function that dereferences it (strcpy,memcpy,memset,strlen,strcmp,sprintf,fprintf,fgets,fread,atoiand similar); getenv(...)passed straight to such a function or indexed:strcpy(buf, getenv("HOME")),strlen(getenv("X")),getenv("LANG")[0].
Not reported: an allocation inside an if/while condition or checked on the same line, a test of the variable (== NULL, != NULL, !p, if (p), p &&, a ternary, assert) before the use, wrapper allocators that abort on failure (xmalloc, zmalloc), a getenv result guarded by a ternary, string literals and comments. The value is not followed across functions. The two-line form overlaps VNX-476.
What Gets Flagged
char *buf = malloc(n);
strcpy(buf, name); // FLAGGED: buf may be NULL
FILE *fp = fopen(path, "a");
fprintf(fp, "started\n"); // FLAGGED: fp may be NULL
strcpy(home, getenv("HOME")); // FLAGGED: HOME may be unset
What Is Not Flagged
char *buf = malloc(n);
if (buf == NULL)
return NULL;
strcpy(buf, name);
strcpy(dst, getenv("HOME") ? getenv("HOME") : "/");
Remediation
- Test every pointer returned by an allocator,
fopenorgetenvbefore using it, and handle the failure (return an error, fall back to a default). - Where the project has an aborting allocator (
xmalloc), use it consistently.
References
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-690
// nosec vnx-690
Or record an ignore rule: vulnetix ignore add --rule vnx-690 --reason "...". See Suppressing findings.