Check then use is a dangerous security pattern
A commentator here recently noted the danger of the Unix pattern of stat()'ing a filename, checking to see if the stat results look good, and then open()'ing the file. The problem is that in many cases an attacker can change what the filename is pointing to between the time you stat() it and when you open() it, so that you check a harmless thing but open a dangerous thing.
In thinking about this, I came to realize that this is an example of general security problem pattern: checking something and then using it. If an attacker can figure out how to mutate the thing between your check and your use of it, you have a security vulnerability. You either need atomic 'check and use' operations, or you need to change to a 'capture and check' pattern instead, where you make your checks only after you have captured an immutable reference to the real object you will be working on.
(This also implies that you need some safe way of getting an immutable
open() does not quite qualify on most Unixes,
because there is no way to tell it to refuse to do opens that would have
side effects, such as opening some device files.)
It doesn't matter if you can't see a way to mutate the thing between your check and the actual use. First, attackers have proven they are very ingenious, and second, even if there is no way now, later changes to the overall system may introduce one, because you are ultimately counting on behavior that is not guaranteed.
Comments on this page:Written on 14 December 2007.