 
                            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.
Failing to close files when they are no longer needed may allow attackers to exhaust, and possibly manipulate, system resources. This phenomenon is typically referred to as file descriptor leakage, although file pointers may also be used as an attack vector. In addition, keeping files open longer than necessary increases the risk that data written into in-memory file buffers will not be flushed in the event of abnormal program termination. To prevent file descriptor leaks and to guarantee that any buffered data will be flushed into permanent storage, files must be closed when they are no longer needed.
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 140 in Annex J.2 of C99.) 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()).
Noncompliant Code Example
In this noncompliant code example, derived from a vulnerability in OpenBSD's chpass program [NAI 1998], a file containing sensitive data is opened for reading. The program then retrieves the registered editor from the EDITOR environment variable and executes it using the system() function. If the system() function is implemented in a way that spawns a child process, then the child process inherits the file descriptors opened by its parent. As a result, the child process, which in this example is the program specified by the EDITOR environment variable, will be able to access the contents of the potentially sensitive file called file_name.
FILE *f;
const char *editor;
char *file_name;
/* Initialize file_name */
f = fopen(file_name, "r");
if (f == NULL) {
  /* Handle fopen() error */
}
/* ... */
editor = getenv("EDITOR");
if (editor == NULL) {
  /* Handle getenv() error */
}
if (system(editor) == -1) {
  /* Handle error */
}
On UNIX-based systems, child processes are typically spawned using a form of fork() and exec(), and the child process always inherits from its parent any file descriptors that do not have the close-on-exec flag set. Under Microsoft Windows, the CreateProcess() function is typically used to start a child process. In Windows, file-handle inheritance is determined on a per-file basis. Additionally, the CreateProcess() function itself provides a mechanism to limit file-handle inheritance. As a result, the child process spawned by CreateProcess() may not receive copies of the parent process's open file handles.
Compliant Solution
In this compliant solution, file_name is closed before launching the editor.
FILE* f;
const char *editor;
char *file_name;
/* Initialize file_name */
f = fopen(file_name, "r");
if (f == NULL) {
  /* Handle fopen() error */
}
/* ... */
fclose(f);
f = NULL;
editor = getenv("EDITOR");
if (editor == NULL) {
  /* Handle getenv() error */
}
/* Sanitize environment before calling system()! */
if (system(editor) == -1) {
  /* Handle Error */
}
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 here.
Compliant Solution (POSIX)
Sometimes it is not practical for a program to close all active file descriptors before issuing a system call such as system() or exec(). An alternative on POSIX systems is to use the FD_CLOEXEC flag, or O_CLOEXEC when available, to set the close-on-exec flag for the file descriptor.
int flags;
char *editor;
char *file_name;
/* Initialize file_name */
int fd = open(file_name, O_RDONLY);
if (fd == -1) {
  /* Handle error */
}
flags = fcntl(fd, F_GETFD);
if (flags == -1) {
  /* Handle error */
}
if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
  /* Handle error */
}
/* ... */
editor = getenv("EDITOR");
if (editor == NULL) {
  /* Handle getenv() error */
}
if (system(editor) == -1) {
  /* Handle error */
}
Some systems (such as those with Linux kernel versions greater than or equal to 2.6.23) have an O_CLOEXEC flag that provides the close-on-exec function directly in open(). This flag is required by POSIX.1-2008 [Austin Group 2008]. In multithreaded programs, this flag should be used, if possible, because it prevents a timing hole between open() and fcntl() when using FD_CLOEXEC, during which another thread can create a child process while the file descriptor does not have close-on-exec set.
char *editor;
char *file_name;
/* Initialize file_name */
int fd = open(file_name, O_RDONLY | O_CLOEXEC);
if (fd == -1) {
  /* Handle error */
}
/* ... */
editor = getenv("EDITOR");
if (editor == NULL) {
  /* Handle getenv() error */
}
if (system(editor) == -1) {
  /* Handle error */
}
Risk Assessment
Failing to properly close files may allow unintended access to, or exhaustion of, system resources.
| Rule | Severity | Likelihood | Remediation Cost | Priority | Level | 
|---|---|---|---|---|---|
| FIO42-C | medium | unlikely | medium | P4 | L3 | 
Automated Detection
| Tool | Version | Checker | Description | 
|---|---|---|---|
| 9.7.1 | 
 | 
 | |
| Fortify SCA | V. 5.0 | 
 | can detect violations of this rule with CERT C Rule Pack | 
| 2025.2 | RH.LEAK | 
 | |
| Compass/ROSE | 
 | 
 | 
 | 
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: FIO42-CPP. Ensure files are properly closed when they are no longer needed
The CERT Oracle Secure Coding Standard for Java: FIO04-J. Release resources when they are no longer needed
MITRE CWE: CWE-404, "Improper Resource Shutdown or Release"
MITRE CWE: CWE-403, "UNIX File Descriptor Leak"
MITRE CWE: CWE-770, "Allocation of Resources Without Limits or Throttling"
Bibliography
[Austin Group 2008]
[Dowd 2006] Chapter 10, "UNIX Processes" (File Descriptor Leaks 582-587)
[MSDN] Inheritance (Windows)
 (Windows)
[NAI 1998]
FIO41-C. Do not call getc() or putc() with stream arguments that have side effects 09. Input Output (FIO) FIO43-C. Do not create temporary files in shared directories