SV.TOCTOU.FILE_ACCESS

TOCTOU race in file access

Functions like access, chown, chgrp, and chmod that operate on file names are vulnerable to time-of-check time-of-use (TOCTOU) errors. A TOCTOU error refers to a situation in which a resource's status can change between the time software checks it and the time it's used. The lapse of time invalidates the check, and can cause invalid actions when the resource is in an unexpected state.

If an attacker is able to change the state of an object between the time of the check and the time it's used, there is potential for a TOCTOU error, which typically happens with shared resources such as files, memory, and variables in multi-threaded programs.

The following functions are prone to this type of attack:

  • acct
  • access
  • chmod
  • lchown
  • chown
  • fopen
  • fdopen
  • freopen
  • fchmod
  • fchown
  • chdir
  • chgrp
  • creat
  • open
  • pathconf
  • opendir
  • lstat
  • stat
  • rename
  • link
  • lchown

The SV.TOCTOU.FILE_ACCESS checker flags function calls that have the potential for a TOCTOU error.

Vulnerability and risk

A typical instance of this vulnerability occurs when a system call is used to check whether the current process has rights to a file before opening the file. A process using this approach can be suspended between the time the check is made and the time the actual file is opened. While the process is suspended, another process can change which file is associated with the name.

Usually this situation involves an operating system that supports symbolic links to files. For instance, using symbolic links to manipulate the meaning of a string given for a password file allows an attacker to get a bogus entry into any location. In one case, an .rhosts file was created in a targeted user directory, allowing the attacker to log in remotely as that user.

This vulnerability can allow a malicious user to gain access to unauthorized resources, and make alterations, delete files, and gain elevated privileges.

Mitigation and prevention

Avoid using functions and system calls that take a file name as an argument-use calls that take a file handle or file descriptor instead. Once the operating system has assigned a file handler or descriptor, it can't be changed as easily as the manipulation of a file name with symbolic links.

If you need to specify a file name in a function

  • set the effective gid and uid for statement execution to that of the current user and group
  • limit the interval of time between the check and the use of a resource
  • check the resource after the use call to make sure that the appropriate action was taken
  • use environmental locking mechanisms to protect resources

Security training

Application security training materials provided by Secure Code Warrior.