Home > Articles > Software Development & Management > Architecture and Design

  • Print
  • + Share This
This chapter is from the book

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:

  1. Pick a prefix for your filename. For example, /tmp/my_app.

  2. Generate at least 64 bits of high-quality randomness from a cryptographically secure source (see Chapter 10).

  3. base64 encode the random bits (see Chapter 11).

  4. Concatenate the prefix with the encoded random data.

  5. Set umask appropriately (0066 is usually good).

  6. Use fopen() to create the file, opening it in the proper mode.

  7. 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.

  8. Perform reads, writes, and seeks on the file as necessary.

  9. 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.

  • + Share This
  • 🔖 Save To Your Account