...
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, preventing this solution.
Compliant Solution (POSIX) (device / i-node)
A simpler alternative, in this case, is simply not to re-open the file. In this code example, the file is opened once for both writing and reading. After the writing is complete, the fseek() function resets the file pointer to the beginning of the file, and its contents are read.
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.
| Code Block | ||
|---|---|---|
| ||
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;
|
Non-Compliant Code Example (owner)
...