...
| Code Block | ||
|---|---|---|
| ||
struct stat st;
dev_t dev; /* device */
ino_t ino; /* file serial number */
int fd = open(filename, O_WRONLY);
if ((fd != -1) && (fstat(fd, &st) != -1)) {
ino = st.st_ino;
dev = st.st_dev;
/* write to file */
close(fd);
}
else {
/* handle error condition */
}
/* reopen previously written file */
fd = open(filename, O_RDONLY);
if ((fd != -1) &&
(fstat(fd, &st) != -1) &&
(st.st_ino == ino) &&
(st.st_dev == dev)
) {
/* read from file */
close(fd);
}
else {
/* handle error condition */
}
|
Alternatively, the same solution could be implemented using the C99 fopen() function top open the file and the POSIX fileno() function to convert the FILE object pointer to a file descriptor.
The structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime should all have meaningful values for all file types on POSIX compliant systems. The st_ino field contains the file serial number. The st_dev field identifies the device containing the file. The st_ino and st_dev, taken together, uniquely identifies the file. The st_dev value is not necessarily consistent across reboots or system crashes, however, so you may not be able to use this field for file identification if there is a possibility of a system crash or reboot before you attempt to reopen a file.
| Wiki Markup |
|---|
It is also necessary to call the {{fstat()}} function on an already opened file, rather than calling {{stat()}} on a file name followed by {{open()}} to ensure the file for which the information is being collected is the same file which is opened. See \[[FIO01-A. Be careful using functions that use file names for identification]\] for more information on avoiding race conditions resulting from the use of file names for identification. |
Compliant Solution (POSIX)
...
Alternatively, the same solution could be implemented using the C99 fopen() function top open the file and the POSIX fileno() function to convert the FILE object pointer to a file descriptor
. |
...
| bgColor | #ccccff |
|---|
Risk Assessment
Many file related vulnerabilities are exploited to cause a program to access an unintended file. Proper identification of a file is necessary to prevent exploitation.
...