In: Computer Science
How many race conditions does attackers have to win in the following program?
int main() {
struct stat stat1, stat2;
int fd1, fd2;
if (access("/tmp/XYZ", O_RDWR)) {
fprintf(stderr, "Permission denied\n");
return -1;
}
else fd1 = open("/tmp/XYZ", O_RDWR);
if (access("/tmp/XYZ", O_RDWR)) { '
fprintf(stderr, "Permission denied\n");
return -1;
}
else fd2 = open("/tmp/XYZ", O_RDWR);
// Check whether fd1 and fd2 have the same inode.
fstat(fd1, &stat1);
fstat(fd2, &stat2);
if(stat1.st_ino == stat2.st_ino) {
write_to_file(fd1);
}
else {
fprintf(stderr, "Race condition detected\n");
return -1;
}
return 0;
}
The accessed file in the code snippet "/tmp/XYZ" . In the given code snippet, three race conditions are possible. Race condition is a situation when two or more operations is trying to be done on a critical section (or on a specific file) at the same time. In that case, depending on the sequence of the work flow, results can vary.
Analysis of the code:
The first race can occur between the first access of the file and fd1 (open the file). Here, inside the first if condition, the file will be accessed and fd1 will open the same file by using pointers. Thus, in a situation, both the lines can lead to a race condition since no semaphore is used or checking of the availability of resource is done here.
The second race can occur between the fd1 (open the file) and the second access under the second if condition. Here fd1 will open the file using pointer and the condition under second if statement will try to access the file. Both of them can lead to a race condition since no semaphore is used or checking of the availability of resource is done.
The third race can occur between the second access and fd2 (open the file). Here, inside the second if condition, the file will be accessed and fd2 will open the same file by using pointers. Since no semaphore is used or availability of the resource is checked, it can lead to a race condition.
Conclusion: Thus total three race conditions have to win by attackers.