Time-of-Check Time-of-Use is a race condition in which the state of a resource (typically a file) is changed after the check, invalidating the check itself.
I have two linux users - abhishek
and sachin
and two files - temporary-file
, owned by abhishek and
privileged-file
, owned by sachin. abhishek does not have read,
write or execute permissions to the privileged-file
.
However, the program is run as root and uses
access()
to
verify whether the current user has write permission to
temporary-file
. However, after the check, there is a gap before the
file is used - during which the attacker deletes temporary-file
and
creates a symlink to privileged-file
. This incorrectly updates the
privileged-file
instead of temporary-file
.
safe_open_wplus()
works as follows:
lstat()
the file before opening.open()
the file, returning a file descriptor.fstat()
the file descriptor returned in second step.- Compare the file type and mode, inode numbmer and ID of device containing file between stat structures returned in first and third steps.
- If the stat structures are same, return FILE pointer by opening the file descriptor.
safe_open_wplus()
is safer because:
- Uses
lstat()
instead ofstat()
oraccess()
and does not resolve symbolic links. - Compares the stat structures before and after opening the file, and verifies if they are same.
- Relies on file descriptor and inode numbers which are immutable instead of file names, which can point to different files.