4 ms·
> An application running as root may try to check that /data/mydir is a regular directory (not a symlink) before opening the file /data/mydir/passwd. In between
by kazinator 4y ago
> An application running as root may try to check that /data/mydir is a regular directory (not a symlink) before opening the file /data/mydir/passwd. In between the time the program does the directory check and the file open, an attacker could replace the mydir directory with a symlink to /etc, and now the file opened is, unexpectedly, /etc/passwd. This is a kind of race condition known as a time-of-check-to-time-of-use (TOCTOU) race.
That application is doing the wrong check; it should be validating that every component of the path is a directory which is only writable to root.
First you stat("/"). OK, that is a directory and writable only to root: so no non-root process can put a symlink there. Next we check "/data". OK, that's a directory, and since we know / is owned by root and not world-writable, /data cannot be replaced by a symlink.
And so on ...
This can easily be made into a function like safe_path("/data/dir/path/to/mypasswd") which returns true only if no pathname component is something which a user other than the caller, or root, could tamper with to point to a different file.
The open system call should have a flag for this, O_SAFE. That would alter the behavior of the name resolution function (traditionally, "namei") to do these checks along the path.
The path could have symlinks, if they are not tamperable from the POV of the calling user.
Typically superuser applications in Unix rely on filesystem structure. They set environment variables like PATH carefully, and stick to accessing data in known directories that had better be safe. If /data/mydir/passwd is something that is manipulated by a root application, then the system is misconfigured if any of these is writable to a non-root user: /, /data, /data/mydir or /data/mydir/passwd.
If that is the case, you don't need symlinks to wreak havoc on the application. You can, for instance, write your own password into that password file and then falsely authenticate with that app.