You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
NamedTemporaryFile() sample code is vulnerable to file squatting #111783
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.
withtempfile.NamedTemporaryFile(delete_on_close=False) asfp:
fp.write(b'Hello world!')
fp.close()
# the file is closed, but not removed# open the file again by using its namewithopen(fp.name, mode='rb') asf:
f.read()
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.
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.
Activity
Sim4n6 commentedon Nov 6, 2023
gpshead commentedon Nov 6, 2023
This was intended to be a concise example of features of the API.
fp.namebeing 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.
Sim4n6 commentedon Nov 6, 2023
Fair enough
gpshead commentedon Nov 6, 2023
We do want docs to raise awareness so I'm keeping this open. Thanks for pointing it out.
gh-111783: Add a warning for reopening files by name to `NamedTempora…
[3.15] gh-111783: Add a warning for reopening files by name to `Named…
[3.14] gh-111783: Add a warning for reopening files by name to `Named…