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. However, once a file has been opened, it is no longer susceptible to these types of attacks so long as it is accessed via a file descriptor. Thus, it is recommended that files are accessed through file handles, versus filenames.
Non-Compliant Example
In this example, the function chmod(...)
is called to set the permissions of a file. However, if the file file_name
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
To correct the error, use the function fchmod(...)
instead of chmod(...)
. The fchmod(...)
function 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 */
Priority: ?? Level: ??
References
- Seacord 05 Chapter 7, File I/O
- ISO/IEC 9899-1999 Sections 7.19.3, Files
- ISO/IEC 9899-1999 Sections 7.19.4, Operations on Files
- Apple Secure Coding Guide Avoiding Race Conditions and Insecure File Operations