Versions Compared

Key

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

...

There is no guarantee that the file opened for reading is the same file that was opened for writing. An attacker could replace the original file (for example, with a symbolic link) between the first fclose() and the second fopen(). This solutions is also non-compliant with VOID FIOxx-A. Avoid reopening a file stream.

Compliant Solution (POSIX) (device / i-node)

Reopening a file stream should generally be avoided (see VOID FIOxx-A. Avoid reopening a file stream). However, this may sometimes be necessary in long running applications to avoid depleting available file descriptors.

...

Compliant Solution (POSIX) (device / i-node)

A simpler alternative, in this case, is solution is to simply not to re-open the file. In this code example, the file is opened once for both writing and reading. After the Once writing is complete, the fseek() function resets the file pointer to the beginning of the file, and its contents are read back (see FIO07-A. Prefer fseek() to rewind()).

Because the file is not re-opened, With no re-opening of the file, we thereby eliminate the possibility of an attacker tampering with the file between the writes and subsequent reads is eliminated.

Code Block
bgColor#ccccff
FILE *fd = fopen(file_name, "w+");
if (fd == NULL) {
  /* Handle Error */
}

/* Write to file */

/* ... */

/* Go to beginning of file */
fseek( fd, 0, SEEK_SET);

/* Read from file */
fclose(fd);
fd = NULL;

...