Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In situations where the source file is supposed not to be a directory or symbolic link, an alternative solution is to use link() to link the source file to the destination file and then use unlink() (or remove()) to delete the source file. Since link() fails if the destination file exists, the need for calling access() is avoided. However, this solution has two race conditions related to the source file. First, before calling link(), the program must use lstat() to check that the source file is not a directory or symbolic link. Second, the source file could change during time during the time window between the link() and the unlink(). Consequently, this alternative solution can be safely executed only when the source file is located within a secure directory.

...

Code Block
bgColor#ccccff
langc
const char *src_file = /* ... */;
const char *dest_file = /* ... */;
if (rename(src_file, dest_file) != 0) {
  /* Handle Errorerror */
}

Remove Existing Destination File

...

The file_exists() function is provided by the application and is not shown here because it must be implemented differently on different platforms. (On POSIX systems, it would use access(), ; on Windows, _access_s(), ; and on other platforms, whatever function is available to test file existence.)

Risk Assessment

Calling rename() has 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.

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

ISO/IEC 9899:2011 Section 7.21.4.2, "The rename function"

Bibliography

...