Temporary Files
Creating temporary files in a shared space such as /tmp is common practice. Temporary files are susceptible to the same potential problems that regular files are, with the added issue that a smart attacker may be able to guess the filename (see Chapter 10 for problems with generating data that cannot be guessed). To alleviate the situation, most C libraries 2provide calls to generate temporary files. Unfortunately, many of these calls are themselves insecure.
We recommend the following strategy for creating a secure temporary file, especially if you must create one in a shared directory for some reason:
Pick a prefix for your filename. For example, /tmp/my_app.
Generate at least 64 bits of high-quality randomness from a cryptographically secure source (see Chapter 10).
base64 encode the random bits (see Chapter 11).
Concatenate the prefix with the encoded random data.
Set umask appropriately (0066 is usually good).
Use fopen() to create the file, opening it in the proper mode.
Unless the file is on a disk mounted off the network (which is not recommended), delete the file immediately using unlink(). Don't worry, the file does not go away until you close it.
Perform reads, writes, and seeks on the file as necessary.
Finally, close the file.
Never close and reopen the file if it lives in a directory that may be susceptible to a race condition. If you absolutely must close and reopen such a file, then you should be sure to use a secure directory, just as we recommend with regular files.