Versions Compared

Key

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

...

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

This compliant solution uses a "check, use, check" pattern to ensure that the file opened for reading is the same file that was opened for writing. In this solution, the file is opened using the open() function. If the file is successfully opened, the fstat() function is used to read information about the file into the stat structure. This information is compared with existing information about the file (stored in the dev and ino variables) to improve identification.

...

This compliant solution may not work in some cases. For instance a long-running service might choose to occasionally re-open a log file to add log messages, but leave the file closed, so that the log file may be periodically rotated. In this case, the inode number would change, negating preventing this solution.

Non-Compliant Code Example (owner)

In this non-compliant code example, the programmer's intent is to open a file for reading, but only if the user running the process owns the specified file. This is a different, and generally more restrictive , requirement that that imposed by the operating system, which only requires that the effective user have permissions to read the file. The code, however, relies solely on the file name to identify the file.

...

If this code is run with superuser privileges as part of a setuid-root program, an attacker could exploit this program to read files for which the real user normally lacks sufficient privileges, including files not owned by the user.

...