File functions that accept file name arguements to determine which file to operate may be vulnerable to a race condition. If the underlying file object is manipulated in a way that causes a program access a different, unintended file, corrupted or malicious data may be used possibly introducing a security vulnerability. This type of error is the premise for many vulnerabilities affecting UNIX symlinks and Windows shortcuts.
Once the correct file has been opened, a program is no longer vulnerable to these types of attacks so long as the file is accessed via a file descriptor. Thus, it is recommended that files are accessed through valid file handles, versus filenames.
Non-Compliant Example 1
In this example, the function chmod(...)
is called twice to set the permissions of a file. However, if the file file_name
is changed between calls, the permissions may be changed on a different, unintended file .
if (chmod("file_name", new_mode_1) == -1) { /* Handle Error */ } /* Process File */ ... if (chmod("file_name", new_mode_2)== -1) { /* Handle Error */ } /* Process file */
Compliant Solution 1
One way to correct this error is to use the function fchmod(...)
instead of chmod(...)
. The fchmod(...)
operates on a file descriptor versus a file name. By using fchmod(...)
it is no longer possible to change the target file between changing the file's permissions by simply changing the file that file_name
refers to.
if (fchmod(fd, new_mode_1) == -1) { /* Handle Error */ } ... if (fchmod(fd, new_mode_2)== -1) { /* Handle Error */ } /* Process file */