« Bikestation Seattle | Main | Howto Disable Cron Jobs »

Safe /tmp Use

Despite years of security warnings, people still utilize /tmp on Unix systems in highly unsafe fashions. Attacks include arbitrary and unlogged file deletion against the user writing the file, where a malicious user creates a symbolic link pointing at the file to be evicted. Solutions to this problem: use secure temporary file creation routines, or locate the files in a new directory with the minimum permissions required.

  • Secure Temporary File Creation
  • Use mktemp(1) to create temporary files. Temporary files can be shared by name between scripts, or by filehandle when using the Perl File::Temp module. See also my Term::CallEditor module, which solicits data from an external editor.

    For a single temporary file under a shell script, expand on the following template:

    #!/bin/sh # ensure temporary files cleaned up (unless an # improper kill -9 used on the script - but # that's a different rant!) cleanup () { rm -f $TMPFILE } # To better trace temporary file back to this script BASENAME=`basename $0` TMPFILE=`mktemp /tmp/$BASENAME.XXXXXXXX` || exit 1 trap "cleanup" 0 1 2 13 15 # add code involving TMPFILE here cleanup

    Multiple temporary files could be appended into a string, which during cleanup would be removed in turn. Aadvanced shell scripting languages support arrays, though I would sooner switch to a Perl script.

    For portability, try mktemp(1), then perhaps $RANDOM, and failing that a static file under /tmp. Emit a warning if mktemp(1) cannot be found, so customers can correct the deficiency.

  • Status Files
  • The second major use of /tmp is for process tracking or similar status files. These files must have a static name, so other processes can consult the known file location. Solution: use a different directory, and set the minimum required permissions. Either overload the vendor space, using directories such as /var/run or /var/log, or create a new site specific directory structure that does not conflict with the vendor space.

Technorati Tags: