...
When creating new files, it may be possible to use functions that create a new file only where a file does not already exist. This prevents the application from overwriting an existing file during file creation. (See FIO03-C. Do not make assumptions about fopen() and file creation.)
In rare cases, it is necessary to check for the existence of symbolic or hard links to ensure that a program is reading from an intended file and not a different file in another directory. In these cases, avoid creating a race condition when checking for the existence of symbolic links. (See POS35-C. Avoid race conditions while checking for the existence of a symbolic link.)
Noncompliant Code Example
This noncompliant code example opens the file specified by the string file_name for read/write access and then writes user-supplied data to the file.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char *file_name = /* something */;
char *userbuf = /* something */;
unsigned int userlen = /* length of userbuf string */;
int fd = open(file_name, O_RDWR);
if (fd == -1) {
/* handle error */
}
write(fd, userbuf, userlen);
|
...
This compliant solution uses the lstat-fopen-fstat idiom illustrated in FIO05-C. Identify files using multiple file attributes.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
char *file_name = /* some value */;
struct stat orig_st;
if (lstat( file_name, &orig_st) != 0) {
/* handle error */
}
if (!S_ISREG( orig_st.st_mode)) {
/* file is irregular or symlink */
}
int fd = open(file_name, O_RDWR);
if (fd == -1) {
/* handle error */
}
struct stat new_st;
if (fstat(fd, &new_st) != 0) {
/* handle error */
}
if (orig_st.st_dev != new_st.st_dev ||
orig_st.st_ino != new_st.st_ino) {
/* file was tampered with during race window */
}
/* ... file is good, operate on fd ... */
|
...
One way to deal with hard links is simply to disallow opening of any file with two or more hard links. The following code snippet, when inserted into the previous example, will identify if a file has multiple hard links.:
| Code Block | ||||
|---|---|---|---|---|
| ||||
if (orig_st.st_nlink > 1) {
/* file has multiple hard links */
}
|
...
Tool | Version | Checker | Description |
|---|---|---|---|
Compass/ROSE |
|
| Could report possible violations of this rule by flagging calls to |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
| Failure to resolve links before file access (aka "link following") |
...
...
...
| Race condition |
...
...
...
| Time-of-check, time-of-use (TOCTOU) race condition |
"
Sources
...
| 2013] | Chapter 7, "File I/O" |
...