Versions Compared

Key

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

File names on many operating systems, including Windows and UNIX, may be used to access special files, which are actually devices. Reserved Microsoft Windows device names include AUX, CON, PRN, COM1, and LPT1 or paths using the \\.\ device namespace. Device files on UNIX systems are used to apply access rights and to direct operations on the files to the appropriate device drivers.

Performing operations on device files that are intended for ordinary character or binary files can result in crashes and denial-of-service attacks. For example, when Windows attempts to interpret the device name as a file resource, it performs an provides invalid resource access that usually results in a crash [Howard 2002].

...

When available (Linux 2.1.126+, FreeBSD, Solaris 10, POSIX.1-2008), the O_NOFOLLOW flag should also be used. (see See POS01-C. Check for the existence of links when dealing with files.) . When O_NOFOLLOW is not available, symbolic link checks should use the method from POS35-C. Avoid race conditions while checking for the existence of a symbolic link.

...

This code contains an intractable TOCTOU (time-of-check, time-of-use) race condition under which an attacker can alter the file referenced by file_name following the call to lstat() but before the call to open(). The switch will be discovered after the file is opened, but opening the file cannot be prevented in the case where this action itself causes undesired behavior. (see See FIO45-C. Avoid TOCTOU race conditions while accessing files for more information about TOCTOU race conditions.).

Essentially, an attacker can switch out a file for one of the file types shown in the following table with the specified effect.

...

Type

Note on Effect

Another regular file

The fstat() verification fails.

FIFO

Either open() returns -1 and sets errno to ENXIO, or open() succeeds and the fstat() verification fails.

Symbolic link

open() returns -1 if O_NOFOLLOW is available; otherwise, the fstat() verification fails.

Special device

Usually the fstat() verification fails on st_mode. This can still be a problem if the device is one for which just opening (or closing) it causes a side effect. If st_mode compares equal, then the device is one that, after opening, appears to be a regular file. It would then fail the fstat() verification on st_dev and st_ino (unless it happens to be the same file, as can happen with /dev/fd/* on Solaris, but this would not be a problem).

 

To be compliant with this rule and to prevent this TOCTOU race condition, file_name must refer to a file in a secure directory. (see See FIO15-C. Ensure that file operations are performed in a secure directory.).

Noncompliant Code Example (Windows)

...