Do race conditions occur during pathname resolution with constant string absolute path literals?
0
votes
2
answers
62
views
According to *The Open Group Base Specifications Issue 8*, on the rationale of the
()
and ()
functions:
> The purpose of the openat() function is to enable opening files in directories other than the current working directory without exposure to race conditions. Any part of the path of a file could be changed in parallel to a call to open(), resulting in unspecified behavior. By opening a file descriptor for the target directory and using the openat() function it can be guaranteed that the opened file is located relative to the desired directory.
This wording implies that **any use of ()
with a pathname that doesn't refer to a file in the current working directory is potentially subject to race conditions, even if the path is an absolute constant like /dev/null
.** While the string literal is immutable, the underlying path components (/
,
,
) can be altered by another process between resolution steps, leading to unintended behavior or security issues.
For example:
#define _POSIX_C_SOURCE 202405L
#include
#include
int main(void) {
int fd = open("/dev/null", O_RDONLY);
if (fd == -1) {
return 1;
}
...
(void) close(fd);
return 0;
}
So the only safe way to open it would be:
#define _POSIX_C_SOURCE 202405L
#include
#include
int main(void) {
int rootfd = open("/", O_SEARCH);
if (rootfd == -1) {
return 1;
}
int devfd = openat(rootfd, "dev", O_SEARCH | O_DIRECTORY);
if (devfd == -1) {
(void) close(rootfd);
return 1;
}
int nullfd = openat(devfd, "null", O_RDONLY);
if (nullfd == -1) {
(void) close(devfd);
(void) close(rootfd);
return 1;
}
...
(void) close(nullfd);
(void) close(devfd);
(void) close(rootfd);
return 0;
}
But the path used is a constant character literal that wasn't obtained from another function. I understand how a race condition could occur if there were a time window between retrieving the path and actually opening it, but not in this case. Doesn't my ()
example just replicate what the kernel already does internally during path resolution when using ()
with an absolute path?
**Note:** I used /dev/null
because it's guaranteed to exist, but my question applies to any path that refers to any file or directory in the filesystem.
Asked by Salubia
(1 rep)
May 19, 2025, 07:21 PM
Last activity: May 20, 2025, 08:08 AM
Last activity: May 20, 2025, 08:08 AM