Invoking remove() on an open file is implementation-defined. Removing an open file is sometimes recommended to hide the names of temporary files that may be prone to attack (see [[FIO46-C. Temporary files must be dealt with in a secure manner]]).
In cases requiring the removal of an open file, a more strongly defined function, such as the POSIX unlink() function, should be considered. To be strictly conforming and portable, remove() should not be called on an open file.
Non-Compliant Code Example
The following non-compliant code example illustrates a case where a file is removed while it is still open.
FILE *file;
/* ... */
file = fopen(file_name, "w+");
if (fopen == NULL) {
/* Handle error condition */
}
/* ... */
remove(file_name);
/* ... */
Some implementations will not remove "myfile" because the stream is still open.
Implementation Details
Code compiled using Microsoft Visual Studio C++ 2005 and run on Microsoft Windows XP prevents the remove() call from succeeding when the file is open, meaning that the file link will remain after execution completes.
Compliant Solution (POSIX)
This compliant solution uses the POSIX unlink() function to remove the file. The unlink() function is guaranteed to unlink the file from the file system hierarchy but keep the file on disk until all open instances of the file are closed) is used [[Open Group 04]].
#include <unistd.h>
FILE *file;
/* ... */
file = fopen(file_name, "w+");
if (fopen == NULL) {
/* Handle error condition */
}
unlink(file_name);
fclose(file);
Risk Assessment
Calling remove() on an open file has different implications for different implementations and may cause abnormal termination if the removed file is written to or read from, or may result in unintended information disclosure from files not deleted as intended.
Recommendation |
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]] Section 7.19.4.1, "The remove function"
[[Open Group 04]] unlink()![]()
FIO07-A. Prefer fseek() to rewind() 09. Input Output (FIO) FIO09-A. fflush() should be called after writing to an output stream if data integrity is important