 
                            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. To prevent file descriptor leaks, file pointers and file descriptors should be closed when they are no longer needed.
Non-Compliant Code Example
In this non-compliant example inspired by a vulnerability in OpenBSD's chpass program [Openbsd 98 ], a file containing sensitive data is opened for reading. Before closing this file, the program retrieves the registered editor from the environment and executes it using the
], a file containing sensitive data is opened for reading. Before closing this file, the program retrieves the registered editor from the environment and executes it using the system() command.
FILE* f;
char *editor;
f = fopen("Sensitive.txt", "r");
if (fd == NULL) {
  /* Handle fopen() error */
}
/* ... */
editor = getenv("EDITOR");
if (editor == NULL) {
  /* Handle getenv() error */
}
system(editor);
If, the system() command is implemented in a way that spawns a child process to run the editor, then the child process inherits the file descriptors opened by the parent process. As a result, the editor will be able to access the contents of Sensitive.txt.
Implementation Specific Details
On UNIX-based systems child processes are typically spawned using a form of fork() and exec(). The child process always receives copies of its parents file descriptors. Under Microsoft Windows, the CreateProcess() function is typically used. In Windows file handle inheritance is determined on a per-file bases. As a result, the child process spawned by CreateProcess() may not have access to the open file handles of the parent process.
Compliant Solution
To correct this example, Sensitive.txt should be closed before launching the editor.
FILE* f;
char *editor;
f = fopen("Sensitive.txt", "r");
if (fd == NULL) {
  /* Handle fopen() error */
}
/* ... */
fclose(f);
editor = getenv("EDITOR");
if (editor == NULL) {
  /* Handle getenv() error */
}
There are multiple security issues in this example. Complying with recommendations, such as STR02-A and FIO02-A can mitigate attack vectors used to exploit this vulnerability. However, following these recommendations will not correct the underlying issue addressed by this rule, the file descriptor leak.
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 | 2 (medium) | 1 (unlikely) | 2 (medium) | P4 | L3 | 
References
[[Dowd 06]] Chapter 10, "UNIX Processes" (File Descriptor Leaks 582-587)
[CWE 403 ] UNIX file descriptor leaks
] UNIX file descriptor leaks
[MSDN ] Inheritance
] Inheritance
[Openbsd 98 ]
]