[Python-Dev] tempnam/tmpnam_r

Martin v. Loewis martin@loewis.home.cs.tu-berlin.de
Sat, 18 Aug 2001 09:09:20 +0200


> I realize this has come up before.  Is it possible to preserve the
> semantics of posix_tmpnam and posix_tempnam while switching the
> implementation over to mkstemp where it's available?

No. If it was possible, the C library would have taken such an
approach to fix it, instead of coming up with a way to complain.

In case you wonder what is dangerous about these functions: they both
return strings of filenames that where unique at the time this was
tested. Typically, the application will then pass that string to
open(). Now, a malicious application may wait for the moment when
tempnam returns, and create the file. Then, the Python application
will open the temporary file, which happens to be created already.
Thus, the malicious application will be able to find out and modify
the data that the Python application has put into the temporary file.

The only true solution is to find a temporary name and open the file
for exclusive access (O_EXCL); if that fails, pick another temporary
name. mkstemp does that and returns both the open file handle, and the
file name.

Regards,
Martin