Versions Compared

Key

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

...

Non-Compliant Code Example: fopen()

In this example, an attempt is made to check whether a file exists before opening it for writing by trying to open the file for readingnon-compliant coding example, the file referenced by file_name is opened for writing. This example is non-compliant, however, if the programmer's intent was to create a new file, but the reference file already exists.

Code Block
bgColor#FFCCCC
char *file_name;
FILE *fp;

/* initialize file_name */

fp = fopen(file_name, "rw");
if (!fp) { /* file does not exist */
  fp = fopen(file_name, "w");
  /* ... */
  fclose(fp);
} else {
   /* file exists */
  fclose(fp);
}

...

handle error */
}

Non-Compliant Code Example: fopen_s() (ISO/IEC TR 24731-1)

The fopen_s() function defined in ISO/IEC TR 24731-1:2007 is designed to improve the security of the fopen() function. However, like fopen(), fopen_s() provides no mechanism to determine if an existing file has been opened for writing or a new file has been created. The code below contains the same TOCTOU race condition as the first non-compliant code example using fopen().

Code Block
bgColor#FFCCCC
char *file_name;
FILE *fp;

/* initialize file_name */
errno_t res = fopen_s(&fp, file_name, "rw");
if (res != 0) { /* file does not exist */
  res = fopen_s(&fp, file_name, "w");
  /* ...handle error */
  fclose(fp);
} else {
  fclose(fp);
}

Compliant Solution: open() (POSIX)

...

Wiki Markup
Care should be observed when using {{O_EXCL}} with remote file systems as it does not work with NFS version 2. NFS version 3 added support for {{O_EXCL}} mode in {{open()}}. IETF RFC 1813 defines the {{EXCLUSIVE}} value to the {{mode}} argument of {{CREATE}} \[[Callaghan 95|AA. C References#Callaghan 95]\].

EXCLUSIVE specifies that the server is to follow exclusive creation semantics, using the verifier to ensure exclusive creation of the target. No attributes may be provided in this case, since the server may use the target file metadata to store the createverf3 verifier.

...