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|http://seclists.org/bugtraq/1998/Aug/0071.html]\], a file containing sensitive data is opened for reading. Before closing this file, the registered editor retrieved from the environment and executed using the {{system()}} command. Internally, the {{system()}} command spawns a child process to run the editor. This child process inherits the file descriptors of the parent process. As a result, the editor will be able to access the contents of {{Sensitive.txt}}.

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);
}

Compliant Solution

Risk Assessment

Failing to properly close files may allow unintended access to system resources, or exhaust system resources.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO42-C

2 (medium)

1 (unlikely)

2 (medium)

P4

L3

References

\[[Dowd 06|AA. C References#Dowd 06]\] Chapter 10, "UNIX Processes" (File Descriptor Leaks 582-587)
\[[CWE 403|http://cwe.mitre.org/data/definitions/403.html]\] UNIX file descriptor leaks