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 |
FIFO | Either |
Symbolic link |
|
Special device | Usually the |
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)
...