Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The POSIX lstat() function collects information about a symbolic link rather than its target. This noncompliant code example uses the lstat() function to collect information about the file, checks the st_mode field to determine if the file is a symbolic link, and then opens the file if it is not a symbolic link.:

Code Block
bgColor#FFCCCC
langc
char *filename = /* file name */;
char *userbuf = /* user data */;
unsigned int userlen = /* length of userbuf string */;

struct stat lstat_info;
int fd;
/* ... */
if (lstat(filename, &lstat_info) == -1) {
  /* Handle error */
}

if (!S_ISLNK(lstat_info.st_mode)) {
   fd = open(filename, O_RDWR);
   if (fd == -1) {
       /* Handle error */
   }
}
if (write(fd, userbuf, userlen) < userlen) {
  /* Handle error */
}

...

This compliant solution eliminates the race condition by

  1. calling Calling lstat() on the file name.
  2. calling Calling open() to open the file.
  3. calling Calling fstat() on the file descriptor returned by open().
  4. comparing Comparing the file information returned by the calls to lstat() and fstat() to ensure that the files are the same.

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

ISO/IEC 9899:2011 Section 7.21, "Input/output <stdio.h>"

...

...

Race condition enabling link following
CWE-365,

...

Race

...

condition in

...

switch

...

[Dowd 2006]Chapter 9, "UNIX 1: Privileges and Files"
[ISO/IEC 9899:2011]Section 7.21, "Input/output <stdio.h>"
[Open Group 2004]lstat()

...

...

...

2013]Chapter

...

8, "File I/O"

 

...