[Python-Dev] tempnam/tmpnam_r

Skip Montanaro skip@pobox.com (Skip Montanaro)
Sat, 18 Aug 2001 11:32:07 -0500


    >> 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?

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

Understood.

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

Given that these two functions have a race condition and that it can be
exploited when used in C code, it seems to me that it would be even easier
to exploit when used in Python code, since Python programs tend to run so
much slower than C programs at the granularity of measurement we're talking
about.  If that's the case, then I think it makes a stronger argument for
deprecating the existing tmpnam and tempnam functions in favor of mkstemp.

I realize there are some issues to resolve.  First, mkstemp returns a file
descriptor and modifies the input filename template.  The return value to
Python code would have to be a tuple (filename, fd).  Second, if we want to
encourage people to use it in place of the builtin open function, it will
have to return a normal Python file object instead of an integer file
descriptor.  Third, is mkstemp pretty universally available?

Finally, I still think use of tmpnam or tempnam should emit warnings.

Skip