According to its C99 definition, the effect of calling remove() on an open file is defined by the implementation. Therefore, care must be taken when remove() is called on an open file. It is often the case that removing a file that is open can help mitigate file input/output race conditions. In these cases, the intended implementations need to be considered and an alternate, more strongly defined function, such as The Open Group's unlink() should be used. To be strictly conforming and portable, remove() should not be called on an open file.
Non-Compliant Code Example
The following non-compliant code illustrates a case where a file is removed after it is first opened.
FILE *file;
/* ... */
file = fopen("myfile", "w+");
if (fopen == NULL) {
/* Handle error condition */
}
remove("myfile");
/* ... */
Some implementations, such as Visual Studio C++ 2005 compiled code running on Microsoft Windows XP, will not allow the call to remove() to succeed, leaving the file resident on disk after execution has completed.
Compliant Solution
The following compliant solution waits until the process has completed using the file to remove it.
FILE *file;
/* ... */
file = fopen("myfile", "w+");
if (fopen == NULL) {
/* Handle error condition */
}
/* Finish using file */
remove("myfile");
Compliant Solution (POSIX)
In this compliant solution intended for POSIX environments, The Open Group's unlink() function (which is guaranteed by The Open Group Base Specifications Issue 6 to unlink the file from the file system hierarchy but keep the file on disk until all open instances of it are closed) is used.
#include <unistd.h>
FILE *file;
/* ... */
file = fopen("myfile", "w+");
if (fopen == NULL) {
/* Handle error condition */
}
unlink("myfile");
/* ... */
Risk Assessment
Calling remove() on an open file has different implications for different implementations and may cause abnormal termination if the closed file is written to or read from, or may result in unintended information disclosure from not actually deleting a file as intended.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
FIO08-A |
2 (medium) |
1 (unlikely) |
2 (medium) |
P4 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[ISO/IEC 9899-1999:TC2]] Section 7.19.4.1, "The remove function"