Skip to content

NamedTemporaryFile() sample code is vulnerable to file squatting #111783

Done

Description

@Sim4n6

Documentation

The provided sample code of the typical usage of the NamedTemporaryFile() may be vulnerable to a file squatting vulnerability (CWE-377) due to insecure handling of temporary file.

 with tempfile.NamedTemporaryFile(delete_on_close=False) as fp:
     fp.write(b'Hello world!')
     fp.close()

     # the file is closed, but not removed
     # open the file again by using its name
     with open(fp.name, mode='rb') as f:
         f.read()

Linked PRs

Activity

  1. added
    docs
    on Nov 6, 2023
  2. Sim4n6 commented on Nov 6, 2023

    @Sim4n6
    Author

    The problem is that, although the initial creation of the temporary file was done safely, it’s reopened later in an unsafe fashion. Malicious users might be able to manipulate that temporary file if they have sufficient permissions in the directory. If they could delete or rename the file and replace it with a symbolic link to a sensitive file, the program could potentially manipulate that sensitive file in an exploitable way.

  3. gpshead commented on Nov 6, 2023

    @gpshead
    Member

    This was intended to be a concise example of features of the API. fp.name being an important one because the only point of using a Named temporary file is that you want to refer to the file by name again later.

    The security anti-pattern is that in some situations code should never open a file by name multiple times and assume it is the same thing. But this is very application dependent as to whether or not that it could be a problem. It is not for many uses.

    At best I think all we can really do is include a comment with a warning link to the CWE-377 to help raise awareness. And perhaps mention it directly in the NamedTemporaryFile documentation section.

  4. Sim4n6 commented on Nov 6, 2023

    @Sim4n6
    Author

    Fair enough

  5. gpshead commented on Nov 6, 2023

    @gpshead
    Member

    We do want docs to raise awareness so I'm keeping this open. Thanks for pointing it out.

  6. reopened this on Nov 6, 2023
  7. reopened this on Nov 6, 2023
  8. added 3 commits that reference this issue on Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docstype-security

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions