next up previous
Next: There be Dragons Up: Working with Temporary Files Previous: Symlink Flipping

Generated file names

Quite often, a program will generate a unique filename and use that to store temporary data in it. One might think that this affords a reasonable protection. In the elm example above the attacker could plant the symlink because he knew the file name (mbox.joe) in advance. If elm used its process ID instead of the user name, an attacker would find it a lot harder to create the proper symlink. Would he?

Not really. Usually, the process IDs of new processes are pretty easy to predict. In fact, the kernel uses a simple counter internally to generate them, which is incremented by one for every new process. All an attacker needs to do is spawn a dummy process every couple of seconds, get its PID, and create symlinks for the next hundred or two hundred PIDs (this technique is also called symlink farming occasionally).

There is an entire family of functions in the C library that suffer from related problems. These are functions used for generating temporary file names, such as mktemp, tmpnam, and tempnam. They are called like this:

    char    filename[128];
    FILE    *fp;

    strcpy(filename, "/tmp/fooXXXXXX");
    if (!mktemp(filename))
        abort("unable to generate temp file name");
    fp = fopen(filename, "w");

When mktemp is successful, it will replace the six X's with some gibberish that makes the file name unique. The way this works is that within mktemp there is a loop that generates different chunks of gibberish, inserts it in place of the X's, and checks whether a file of that name exists (for example, lstat).

Again, this approach has a race condition. All we know that when mktemp called lstat, there was no file or symlink of that name. But by the time execution hasn reached the fopen call, anything may have happened. For instance, an attacker may have created a symbolic link of that name.

This is easier than it may appear. The algorithm by which mktemp generates file names is straightforward, and usually just uses the process ID and a single character for uniquifying; if the PID is 1234, it will generate a1234, b1234, and so on.4.2 If you have the PID of the process you want to attack, the next file name generated by mktemp can thus be predicted.


next up previous
Next: There be Dragons Up: Working with Temporary Files Previous: Symlink Flipping
Olaf Kirch 2002-01-16