Versions Compared

Key

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

...

When creating new files, it may be possible to use functions that create a new file only where a file does not already exist. This prevents the application from overwriting an existing file during file creation. (See FIO03-C. Do not make assumptions about fopen() and file creation.)

In rare cases, it is necessary to check for the existence of symbolic or hard links to ensure that a program is reading from an intended file and not a different file in another directory. In these cases, avoid creating a race condition when checking for the existence of symbolic links. (See VOID POS35-C. Avoid race conditions while checking for the existence of a symbolic link.)

Noncompliant Code Example

...

This compliant solution uses the lstat-fopen-fstat idiom illustrated in FIO05-C. Identify files using multiple file attributes.

Code Block
bgColor#ccccff
langc
char *file_name = /* some value */;

struct stat orig_st;
if (lstat( file_name, &orig_st) != 0) {
  /* handle error */
}

if (!S_ISREG( orig_st.st_mode)) {
  /* file is irregular or symlink */
}

int fd = open(file_name, O_RDWR);
if (fd == -1) {
  /* handle error */
}

struct stat new_st;
if (fstat(fd, &new_st) != 0) {
  /* handle error */
}

if (orig_st.st_dev != new_st.st_dev ||
    orig_st.st_ino != new_st.st_ino) {
  /* file was tampered with during race window */
}

/* ... file is good, operate on fd ... */

...

MITRE CWE: CWE-367, "Time-of-check, time-of-use (TOCTOU) race condition"

Sources

[Austin Group 2008]
[Open Group 2004] open()
[Open Group 2008]
[Seacord 2005] Chapter 7, "File I/O"

...