...
If the file referenced by dest_file
exists prior to calling rename()
, the behavior is implementation-defined. On POSIX systems, the destination file is removed. On Windows systems, the rename()
fails. This creates Consequently, issues arise when trying to write portable code or when trying to implement alternative behavior.
...
Code Block | ||||
---|---|---|---|---|
| ||||
const char *src_file = /* ... */; const char *dest_file = /* ... */; if (rename(src_file, dest_file) != 0) { /* Handle Errorerror */ } |
Compliant Solution (POSIX)
...
file or directory specified by
newname
already exists or could not be created (invalid path). [MSDN].
Consequently, it is unnecessary to explicitly check for the existence of the destination file before calling rename()
.
...
On Windows systems, it is necessary to explicitly remove the destination file before calling rename()
if you want the programmer wants the file to be overwritten and the rename()
operation to succeed:
...
This code contains unavoidable race conditions between the calls to _access_s()
, remove()
, and rename()
and can consequently be safely executed only within a secure directory. (See FIO15-C. Ensure that file operations are performed in a secure directory.) Another option would be to use the MoveFileEx API , and pass in the MOVEFILE_REPLACE_EXISTING
flag:
Code Block | ||||
---|---|---|---|---|
| ||||
const char *src_file = /* ... */; const char *dest_file = /* ... */; if (!MoveFileEx(src_file, dest_file, MOVEFILE_REPLACE_EXISTING)) { /* Handle error condition */ } |
While Although this code is not portable code, it does avoid the race condition when using _access_s(), remove()
, and rename()
.
Compliant Solution (POSIX)
...
A programmer who wants an application to behave the same on any C implementation must first determine what behavior to implement.
...
Calling rename()
has implementation-defined behavior when the new file name refers to an existing file. Incorrect use of rename()
can result in a file being unexpectedly overwritten or other unexpected behavior.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO10-C | medium | probable | medium | P8 | L2 |
...
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...