...
This code example demonstrates how to verify that two accesses are indeed the same file in POSIX. In POSIX, every file can be uniquely identified by using its device and i-node attributes. This code example checks that a filename does not refer to a refers to a regular file (instead of a directory, symbolic link, etc). This is done using lstat()
; the call also retrives retrieves its device and i-node. The file is subsequently opened. Finally, the program verifies that the file that was opened is the same one (matching device and inodes) as the file that was verified not to be a symbolic linkconfirmed as a regular file.
Code Block | ||||
---|---|---|---|---|
| ||||
#include <sys/stat.h> #include <fcntl.h> int open_realregular_file(char *filename, int flags) { struct stat lstat_info; struct stat fstat_info; int fdf; if (lstat(filename, &lstat_info) == -1) { /* file does not exist, handle error */ } if (!S_ISLNKISREG(lstat_info.st_mode)) { /* file is a symlink, handle error */ } if fd((f = open(filename, flags)); if (fd == -1) { /* file has disappeared, handle error */ } if (fstat(fdf, &fstat_info) == -1) { /* handle error */ } if (!(lstat_info.st_ino !== fstat_info.st_ino &&|| (lstat_info.st_dev !== fstat_info.st_dev) { /* open file is not non-symlink file, handle error */ } /* fdf is true open file, and file was not symlink */ return fdf; } |
Risk Assessment
TOCTOU race conditions can result in unexpected behavior, including privilege escalation.
...