next up previous
Next: Generated file names Up: Working with Temporary Files Previous: Defenses that Don't Work

Symlink Flipping

A common attack that is quite successful against this type of bug is called symlink flipping. The attacker creates a small program that runs in a tight loop, creating a symbolic link and removing it. When he starts the setuid application he wants to exploit, the two processes execute in parallel. There's a certain probability that the sequence of events is this:

Process A Process B
symlink("/etc/foo", filename)  
...  
unlink(filename)  
Context Switch
  do various stuff
  lstat(filename, &stb)
Context Switch
symlink("/etc/foo", filename)  
unlink(filename)  
/* repeat many times */  
symlink("/etc/foo", filename)  
Context Switch
  fopen(filename)

The odds for a context switch arriving exactly between the lstat and the fopen call aren't very high. However when you're dealing with a setuid program, you can invoke it as often as you like, until you succeed. From my experience, a couple of minutes are enough in most cases.

Defeating the lstat check in applications such as daemon programs is harder, because you usually cannot make the daemon execute the critical code section as often as you like. However, that doesn't mean that it's safe to use. Here's why:

The sequence of events described above implicitly assumed that we were running on a single-processor machine, where you do not have real parallelism. On a multi-processor machine, both processes will really run in parallel, so that the attacking process will keep creating and removing the symlink all the time. As a consequence, at any point in time, there is a 50 % chance that the symbolic link exists. Thus, the probability that lstat will not see a symlink, but fopen will, is 25 %! So even if we're attacking a server process that creates the temporary file just once a day, chances are extremely good that we'll have defeated the lstat check by the end of a week.


next up previous
Next: Generated file names Up: Working with Temporary Files Previous: Defenses that Don't Work
Olaf Kirch 2002-01-16