Standard FILE objects and their underlying representation (file descriptors on POSIX ® platforms or handles elsewhere) are a finite resource that must be carefully managed. The maximum number of files that an implementation guarantees may be open simultaneously is bounded by the FOPEN_MAX macro defined in <stdio.h>. The value of the macro is guaranteed to be at least 8. Thus, portable programs must either avoid keeping more than FOPEN_MAX files at the same time or be prepared for functions such as fopen() to fail due to resource exhaustion.
...
The behavior of a program is undefined when it uses the value of a pointer to a FILE object after the associated file is closed. (See undefined behavior 148 in Annex J of C11 [ISO/IEC 9899:2011]the C Standard.) Programs that close the standard streams (especially stdout but also stderr and stdin) must be careful not to use the stream objects in subsequent function calls, especially those that implicitly operate on such objects (such as printf(), perror(), and getc()).
...
Several security issues remain in this example. Compliance with recommendations such as STR02-C. Sanitize data passed to complex subsystems and FIO02-C. Canonicalize path names originating from untrusted sources is necessary to prevent exploitation. However, these recommendations do not address the specific issue of file descriptor leakage addressed discussed here.
Compliant Solution (POSIX)
...
Tool | Version | Checker | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Include Page | LDRA_V | LDRA_V | ||||||||||
Compass/ROSE | 49 D | Fully implemented. | ||||||||||
Fortify SCA | V. 5.0 | Can detect violations of this rule with CERT C Rule Pack. | ||||||||||
| RH.LEAK | Compass/ROSE | ||||||||||
| 49 D | Fully implemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
...
| FIO04-J. Release resources when they are no longer needed | |
| ISO/IEC TR 17961 (Draft) | Failing to close files or free dynamic memory when they are no longer needed [fileclose] |
| MITRE CWE |
...
...
...
| UNIX file descriptor leak |
...
...
...
| Allocation of resources without limits or throttling |
...
Bibliography
| [Austin Group 2008] | |
| [Dowd 2006] | Chapter 10, "UNIX Processes" ("File |
...
| Descriptor Leaks," pp. 582–587) | |
| [MSDN] | Inheritance (Windows) |
| [NAI 1998] |
...