Unsafe Temporary File Creation

Detects creation of temporary files with predictable names or in world-writable locations, enabling symlink attacks and race conditions.

zakirkun Updated

File contents

Unsafe Temporary File Creation

Overview

Creating temporary files insecurely can lead to:

  • Symlink attacks: Attacker pre-creates a symlink at the predicted temp path, redirecting writes to sensitive files
  • TOCTOU race conditions: Time-of-check vs time-of-use between name generation and file open
  • Information disclosure: Predictable temp file names allow attackers to read sensitive data

Detection Strategy

  • Using mktemp (insecure, returns name only) instead of mkstemp (securely opens file)
  • Building temp file paths from predictable strings: /tmp/app_ + PID
  • Using /tmp directly with hardcoded suffixes

Remediation

Use language-provided secure temp file APIs that atomically create and open the file.

Vulnerable (Python):

import tempfile, os
tmp_path = '/tmp/myapp_' + str(os.getpid())
with open(tmp_path, 'w') as f:  # Race condition!
    f.write(data)

Safe (Python):

import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=True) as f:
    f.write(data)

zakirkun/ice-tea/tree/main/skills/fs/unsafe-temp-files commit 76b8dcc910

Frequently asked questions

npx skillmds@latest add zakirkun/unsafe-temporary-file-creation