Many file related security vulnerabilities result from a program accessing a file different from the one intended. This type of error may be caused by an attacker manipulating the underlying directory structure to cause a program to access and operate on an arbitrary file. This type of manipulation is the premise for vulnerabilities involving UNIX symlinks and Windows shortcuts. However, once a file has been opened, it is no longer susceptible to these types of attacks so long at it is accessed via a file descriptor. Thus, it is recommended that files are accessed through file handles, versus filenames.
Non-Compliant Example 1
In this example, the function chmod(...)
is called to set the permissions of a file. However, if the file file_name
is has been changed from the time it was opened, the permissions may be changed on a different, unintended file.
if (chmod("file_name", new_mode) == -1) { /* Handle Error */ } /* Process file */
Compliant Solution 1
To correct the error, use the function fchmod(...)
instead of chmod(...)
. The fchmod(...)
operates on a file descriptor versus a file name. By using fchmod(...)
the program is no longer vulnerable to a symlink attack file between opening and changing the file's permissions.
if (fchmod(fd, new_mode) == -1) { /* Handle Error */ } /* Process file */