python.lang.correctness.tempfile.mktemp.tempfile-insecure

Community Favorite
profile photo of semgrepsemgrep
Author
12,763
Download Count*

Use tempfile.NamedTemporaryFile instead. From the official Python documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file name may refer to a file that did not exist at some point, but by the time you get around to creating it, someone else may have beaten you to the punch.

Run Locally

Run in CI

Defintion

rules:
  - id: tempfile-insecure
    pattern: tempfile.mktemp(...)
    message: "Use tempfile.NamedTemporaryFile instead. From the official Python
      documentation: THIS FUNCTION IS UNSAFE AND SHOULD NOT BE USED. The file
      name may refer to a file that did not exist at some point, but by the time
      you get around to creating it, someone else may have beaten you to the
      punch."
    languages:
      - python
    severity: ERROR
    metadata:
      category: correctness
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

mktemp.py

import tempfile as tf

# ruleid: tempfile-insecure
x = tempfile.mktemp()
# ruleid: tempfile-insecure
x = tempfile.mktemp(dir="/tmp")