The ISO/IEC 9899-1999 C specification provides standard functions to manipulate files that are designed to avoid the details of the underlying system. However, file manipulation and file operations are inherently tied to the operating system. Many of the common vulnerabilities associated with file operations exist because the ISO/IEC 9899-1999 C specification lacks facilities to adequately interact with files and the file system, making it impossible to specify the correct behavior.
A better way to interact with files, in terms of security, is to use functions designed for the native system. Many implementation specific functions offer a level of control over file objects that the ISO/IEC 9899-1999 C specification does not.
Additionally, there are well-known recommendations for dealing with common file operations securely that use non-standard functions. This recommendation opens those options up to implementers of this standard.
Non-Compliant Example 1
The ISO/IEC 9899-1999 C standard function
fopen() is typically used to open an existing file, or create a new one. However,
fopen() does not provide a way to test file existence potentially allowing a program to overwrite or access and unintended file.
In this example, a file name is supplied to
fopen() to create and open for writing. However, there is no guaruntee that the file referenced by
file_name does not exist prior to calling
fopen(). This may cause an unintended file to be overwritten.
Compliant Solution 1.
open() function (Open Group 04c) provides a a way to test for file existence . If the
O_EXCL flags are used together, the
open() function will fail if the file file specified by
file_name already exists.