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 1
In this example, the function fopen(...)
is called to open a stream to the object referred to by file_name
. However, future file operations on file_name
are not gauranteed to refer to the same object file_name
referred to in the call to fopen()
.
FILE * f_ptr = fopen(file_name,"w");
Compliant Solution 1
To correct this, use open()
to get a file descriptor for to the file object referred to by file_name
and then using fdopen()
to open the file stream. Future operations should then be performed on the file descriptor, rather than the file_name
as the file descriptor will refer to the same object that was opened.
fd = open(file_name, O_WRONLY | O_CREAT, 0600); if (fd == -1) { /* Handle open() error */ } f_ptr = fdopen(fd,"w");
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