Perl and Temporary Files

Insecure Code | Lock Files under /tmp | Solutions

Far too many security flaws are still being written in code that needs a temporary file for some reason. These notes attempt to illustrate briefly how writing files into /tmp or similar untrustworthy areas is problematic, and should be avoided in favor of modules that handle the troublesome details in a more secure and transparent fashion.

Insecure temporary files allow malicious local users of a system to either delete files they otherwise should not have access to, or possibly run arbitrary code, depending on how the temporary file is used. The attacks are usually opportunistic, requiring the setup of trap that will be triggered when the insecure code is run by something else.

Temporary directories, if needed, can also be managed with File::Temp. Consider also the File::AtomicWrite module, which offers additional features around File::Temp.

Insecure Code

The following examples show various insecure file handling code, and comment on attacks possible against such poor code.

Security Audit

New code can easily be searched for improper temporary file handling, either manually or via a custom program that has been coded to find such problems. Site policy should prohibit the use of such code, or require a rewrite using known secure techniques before the code is put into production. Be sure to also check for uses of the TMP or TMPDIR environment variables.

$ grep -rl /tmp *

Lock Files under /tmp

Never locate lock files under a system-wide temporary directory. These locations allow for needless local security problems: an attacker could create a denial of service by creating the lock file as a different user, or depending on the lock handling code and various race conditions, cause arbitrary file truncation or removal against the user that creates the lock file. Instead, locate lock files under /var/run or similar directories that offer the minimum permissions necessary to carry out the file-based locking.

Ensuring only one copy of a perl script is running at a time on PerlMonks lists various other options. Also consider better job schedulers, such as CFEngine, which include run-only-a-single-copy support as a native feature.

Solutions

For Perl code, there are several solutions that provide secure temporary file handling. General security advice for Perl can be found in the perlsec documentation.