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
I recently came across a non-testing use case for tempfile.mktemp() where I struggle to find a viable alternative -- temporary named pipes (FIFOs):
import os
import tempfile
import subprocess as sp
fifo_path = tempfile.mktemp()
os.mkfifo(fifo_path, 0o600)
try:
proc = sp.Popen(["cat", fifo_path], stdout=sp.PIPE, text=True)
with open(fifo_path, "w") as fifo:
for c in "Kočka leze dírou, pes oknem.":
print(c, file=fifo)
proc.wait()
finally:
os.unlink(fifo_path)
for l in proc.stdout:
print(l.strip())
(cat is obviously just a stand-in for some useful program which needs to read from a file, but you want to send it input from Python.)
os.mkfifo() needs a path which doesn't point to an existing file, so it's not possible to use a tempfile.NamedTemporaryFile(delete=False), close it, and pass its .name attribute to mkfifo().
def mktemp(suffix='', prefix='tmp', dir=None):
if dir is None:
dir = gettempdir()
return _os.path.join(dir, prefix + secrets.token_urlsafe(ENTROPY_BYTES) + suffix)
Fixing mktemp would make it possible to get rid of its hybrid deprecated (in the docs) / not depracated (in code) status, which is somewhat confusing for users. Speaking from experience -- when I realized I needed it, the deprecation notice led me down this rabbit hole of reading mailing list threads and submitting issues :) People could stop losing time worrying about mktemp and trying to weed it out whenever they come across it (see e.g. https://bugs.python.org/issue42278).
So I'm wondering whether there would be interest in:
A PR which would modify mktemp along the lines sketched above, to make it safe in practice. Along with that, it would probably make sense to undeprecate it in the docs, or at least indicate that while users should prefer mkstemp when they're fine with the file being created for them, mktemp is alright in cases where this is not acceptable.
Following that, possibly a PR which would encapsulate the new mktemp + mkfifo into a TemporaryNamedPipe or TemporaryFifo:
import os
import tempfile
import subprocess as sp
with tempfile.TemporaryNamedPipe() as fifo:
proc = sp.Popen(["cat", fifo.name], stdout=sp.PIPE, text=True)
for c in "Kočka leze dírou, pes oknem.":
print(c, file=fifo)
proc.wait()
for l in proc.stdout:
print(l.strip())
(Caveat: opening the FIFO for writing cannot happen in __enter__, it would have to be delayed until the first call to fifo.write() because it hangs if no one is reading from it.)
Hm, the random sequence (implemented in tempfile._RandomNameSequence) is
currently derived from the random module, which is not cryptographically
secure. Maybe all we need to do is replace its source of randomness with
one derived from the secrets module. That seems a one-line change.
That was actually the first approach I tried :) I even thought this could be used to make mktemp safe -- just create the name in a TemporaryDirectory.
However, after reading through the mailing list thread, I realized this just restricts the potential collision/hijacking to misbehaving/malicious processes running under the same user or under the super user. But the core problem with too easily guessable filenames (= not random enough, or not at all, as in your example) remains. Correct me if I'm wrong though.
Sorry, I should probably have mentioned this in OP. I thought about doing so, but then it turned out very long even without it, so I decided it would be better to discuss it only if someone else mentions it.
Hey, I was wondering if the tempfile.mktemp() was obviously insipred by POSIX conform mktemp() function. The original POSIX mktemp()creates a filenameXXXXX, where an X character is an alphanumeric character [A-Za-z0-9].
I can understand that capital letters were rejected due to the case insensitive platforms. But why is there an underscore character included in the list?
I mean with the function called in the same way and without any additional mention in the documentation would be expected to have the similar alphanumeric pool of characters.
Should it the given pool be documented somewhere or underscore be removed from the pool of the available characters?
Activity
dlukes commentedon Mar 23, 2021
I recently came across a non-testing use case for
tempfile.mktemp()where I struggle to find a viable alternative -- temporary named pipes (FIFOs):(
catis obviously just a stand-in for some useful program which needs to read from a file, but you want to send it input from Python.)os.mkfifo()needs a path which doesn't point to an existing file, so it's not possible to use atempfile.NamedTemporaryFile(delete=False), close it, and pass its.nameattribute tomkfifo().I know there has been some discussion regarding
mktemp()in the relatively recent past (see the Python-Dev thread starting with https://mail.python.org/pipermail/python-dev/2019-March/156721.html). There has also been some confusion as to what actually makes it unsafe (see https://mail.python.org/pipermail/python-dev/2019-March/156778.html). Before the discussion petered out, it looked like people were reaching a consensus "that mktemp() could be made secure by using a longer name generated by a secure random generator" (quoting from the previous link).A secure
mktempcould be as simple as (see https://mail.python.org/pipermail/python-dev/2019-March/156765.html):There's been some discussion as to what
ENTROPY_BYTESshould be. I like Steven D'Aprano's suggestion (see https://mail.python.org/pipermail/python-dev/2019-March/156777.html) of having an overkill default just to be on the safe side, which can be overridden if needed. Of course, the security implications of lowering it should be clearly documented.Fixing
mktempwould make it possible to get rid of its hybrid deprecated (in the docs) / not depracated (in code) status, which is somewhat confusing for users. Speaking from experience -- when I realized I needed it, the deprecation notice led me down this rabbit hole of reading mailing list threads and submitting issues :) People could stop losing time worrying aboutmktempand trying to weed it out whenever they come across it (see e.g. https://bugs.python.org/issue42278).So I'm wondering whether there would be interest in:
mktempalong the lines sketched above, to make it safe in practice. Along with that, it would probably make sense to undeprecate it in the docs, or at least indicate that while users should prefermkstempwhen they're fine with the file being created for them,mktempis alright in cases where this is not acceptable.mktemp+mkfifointo aTemporaryNamedPipeorTemporaryFifo:(Caveat: opening the FIFO for writing cannot happen in
__enter__, it would have to be delayed until the first call tofifo.write()because it hangs if no one is reading from it.)dlukes commentedon Mar 23, 2021
Though in practice, I'd rather be inclined to make the change in
tempfile._RandomNameSequence, so as to get the same behavior across the entire module, instead of special-casingmktemp. As Guido van Rossum points out (see https://mail.python.org/pipermail/python-dev/2019-March/156746.html), that would improve the security of all the names generated by thetempfilemodule, not justmktemp:serhiy-storchaka commentedon Mar 23, 2021
You can use TemporaryDirectory.
dlukes commentedon Mar 23, 2021
That was actually the first approach I tried :) I even thought this could be used to make
mktempsafe -- just create the name in aTemporaryDirectory.However, after reading through the mailing list thread, I realized this just restricts the potential collision/hijacking to misbehaving/malicious processes running under the same user or under the super user. But the core problem with too easily guessable filenames (= not random enough, or not at all, as in your example) remains. Correct me if I'm wrong though.
Sorry, I should probably have mentioned this in OP. I thought about doing so, but then it turned out very long even without it, so I decided it would be better to discuss it only if someone else mentions it.
Remove some usage of tempfile.mktemp()
Remove some usage of tempfile.mktemp()
Remove some usage of tempfile.mktemp()
Remove some usage of tempfile.mktemp()
Remove some usage of tempfile.mktemp()
lrlunin commentedon Dec 11, 2024
Hey, I was wondering if the
tempfile.mktemp()was obviously insipred by POSIX conformmktemp()function. The original POSIXmktemp()creates afilenameXXXXX, where an X character is an alphanumeric character[A-Za-z0-9].I can understand that capital letters were rejected due to the case insensitive platforms. But why is there an underscore character included in the list?
cpython/Lib/tempfile.py
Line 140 in 8b24d04
I mean with the function called in the same way and without any additional mention in the documentation would be expected to have the similar alphanumeric pool of characters.
Should it the given pool be documented somewhere or underscore be removed from the pool of the available characters?
I would be happy to hear any feedback.