How safe are command lists in shell (or bash) from race conditions?
if [ -h "$dir" ]; then
echo 'Directory exists and is a symlink'
exit 1
fi
cd "$dir"
The above code is obviously prone to race conditions: An attacker can create a symlink after the check, but still before changing the directory into it.
Does the same apply to || command lists? In other words: is the below command immune to race conditions, or do the same rules as above still apply?
[ -h "$dir" ] || cd "$dir"
With error message:
[ -h "$dir" ]
&& { echo 'Directory exists and is a symlink'; exit 1; }
|| cd "$dir"
There are only two secure and relatively portable ways to change directory without following a symbolic link. Neither is easily possible in shell scripts.
Assume for the sake of discussion that we’re trying to safely chdir into “foo”. The first way is to save the current directory in an open file descriptor with
open(".", O_RDONLY),lstat()the “foo” directory, record thest_devandst_inovalues that result, call chdir(“foo”) and then stat() “.”. Compare the resulting thest_devandst_inovalues. If they are the same, you won the race. If not, issue an error message,fchdir()back using your saved fd, and then either abort or try again.The second, less portable way, is to use
fd = open("foo", O_RDONLY|O_NOFOLLOW)and thenfchdir(fd). You can also useopenatinstead ofopenhere. The portability problem is that not all systems haveO_NOFOLLOWand some older kernels won’t correctly interpret that flag (instead they ignore it, which is a security issue).For more information take a look at the source code of GNU find, in which I go to quite some trouble to avoid this kind of problem, using a method very similar to the one described above.
As for solving this problem in a shell script:
If your system has a
stat(1)command or something like Perl, you can use those to perform the stat operations; you can record the result in a shell variable. This means you can more or less implement the first method in a shell script, except for the need to usefchdirto recover. If it is OK to simply abort immediately when your shell script loses the race, you can certainly adapt the first method for use in the shell. But in the end writing secure code in shell is very, very difficult.