Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 C99 standard function fopen() is typically used to open existing, and create new files. 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. Howerver, there is no gauruntee that the file referenced by file_name does not exist prior to calling fopen(). This may cause an unintended file to be overwritten.

Code Block


...
FILE * fptr = fopen(file_name, "w");
if (!fptr) {
  /* Handle Error */
}
...

Compliant Solution 1.

The open() function (defined in the POSIX standard) provides a a way to test for file existence . If the O_CREAT and O_EXCL flags are used together, the open() function will fail if the file file specified by file_name already exists.

Code Block

...
int fd = open(file_name, O_CREAT | O_EXCL | O_WR_ONLY, 0600);
if (fd == -1) {
  /* Handle Error */
}
...

References