Insecure temporary file or directory Medium

Insecure ways of creating temporary files and directories can lead to race conditions (which can be exploited for denial of service attacks) and other security vulnerabilities such as privilege escalation.

Detector ID
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1def create_file_noncompliant(results):
2    import tempfile
3    # Noncompliant: uses a temporary file path to create a temporary file.
4    filename = tempfile.mktemp()
5    with open(filename, "w+") as f:
6        f.write(results)
7    print("Results written to", filename)

Compliant example

1def create_temp_file_compliant(results):
2    import tempfile
3    # Compliant: uses the correct mechanism to create a temporary file.
4    with tempfile.NamedTemporaryFile(mode="w+", delete=False) as f:
5        f.write(results)
6    print("Results written to",