VNX-826: Premature Release of Resource During Expected Lifetime
Reports a C or C++ file, descriptor, directory, SQLite connection or Windows handle that is closed while the code below still uses it (fclose then fprintf, close then recv, closedir then readdir, sqlite3_close then sqlite3_errmsg, CloseHandle then WriteFile).
| Field | Value |
|---|---|
| Rule ID | VNX-826 |
| Severity | Low |
| SARIF level | note |
| Kind | sast |
| Languages | C, C++ |
| CWE | CWE-826 |
| 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 | premature-release cwe-826 c cpp resource-lifetime |
| Source | internal/sast/rules/vnx-826.rego |
Overview
VNX-826 maps to CWE-826: Premature Release of Resource During Expected Lifetime. It reports the release line when the same handle is used again within 15 lines in the same function:
fclose/pcloseof aFILE*followed by stdio on that stream (fprintf,fputs,fwrite,fread,fgets,fseek,fflush, …);close/closesocketof a descriptor followed byread,write,send,recv,lseek,fstat,ioctl,setsockopt,shutdownand the other descriptor calls on it;closedirfollowed byreaddir;sqlite3_closefollowed bysqlite3_exec,sqlite3_prepare*orsqlite3_errmsgon the same connection;CloseHandlefollowed byReadFile,WriteFileorWaitForSingleObjecton the same handle.
Not reported: a release followed by return, goto, break, continue, exit/abort or throw before the use (error paths), a handle reassigned or reopened in between (fp = fopen(...), fd = -1, fd = accept(...)), a use on another if/else or switch branch, uses in another function (including the next inline method of a class body), method calls (file.close()), array elements (close(pipefd[1])), freed memory (VNX-C-004, VNX-416), double release (VNX-1341), comments and string literals.
Why This Matters
A closed descriptor number is reused by the next open, socket or accept, so a write meant for the closed file lands in an unrelated file or a different client’s connection. A closed FILE* or SQLite connection points at freed memory.
What Gets Flagged
fputs(body, out);
fclose(out); /* FLAGGED */
fprintf(out, "-- end --\n");
close(sock); /* FLAGGED */
n = recv(sock, buf, len - 1, 0);
Remediation
- Release a handle after its last use.
- If the handle must be reopened, assign the new handle before using it, and reset closed handles (
fd = -1;,fp = NULL;).
References
- CWE-826: Premature Release of Resource During Expected Lifetime
- SEI CERT FIO46-C: Do not access a closed file
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-826
// nosec vnx-826
Or record an ignore rule: vulnetix ignore add --rule vnx-826 --reason "...". See Suppressing findings.