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 FIO21-C. Do not create temporary files in shared directories.)
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.
Noncompliant Code Example
This noncompliant code example shows a case where a file is removed while it is still open:
Some implementations will not remove the file specified by
file_name because the stream is still open.
Code compiled for Microsoft Windows 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 [IEEE Std 1003.1:2013].
Note that there is a race window between the
fopen() call and the
unlink() call, which could be exploited. This exploitation can be mitigated if the operations occur in a secure directory; see FIO45-C. Avoid TOCTOU race conditions while accessing files for more information.
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 it may result in unintended information disclosure from files not deleted as intended.
|CodeSonar||5.4p0||(customization)||Users can implement a custom check for calls to |
|LDRA tool suite||9.7.1|
|PRQA QA-C||9.7||5014||Partially implemented|
Search for vulnerabilities resulting from the violation of this rule on the CERT website.