Skip to content

Fix tempfile.mktemp() #87770

Open
Open

Description

@dlukes
mannequin
BPO 43604
Nosy @serhiy-storchaka, @dlukes

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields:

assignee = None
closed_at = None
created_at = <Date 2021-03-23.15:26:30.711>
labels = ['type-security', 'library', '3.10']
title = 'Fix tempfile.mktemp()'
updated_at = <Date 2021-03-23.19:35:24.997>
user = 'https://github.com/dlukes'

bugs.python.org fields:

activity = <Date 2021-03-23.19:35:24.997>
actor = 'dlukes'
assignee = 'none'
closed = False
closed_date = None
closer = None
components = ['Library (Lib)']
creation = <Date 2021-03-23.15:26:30.711>
creator = 'dlukes'
dependencies = []
files = []
hgrepos = []
issue_num = 43604
keywords = []
message_count = 4.0
messages = ['389393', '389394', '389402', '389407']
nosy_count = 2.0
nosy_names = ['serhiy.storchaka', 'dlukes']
pr_nums = []
priority = 'normal'
resolution = None
stage = None
status = 'open'
superseder = None
type = 'security'
url = 'https://bugs.python.org/issue43604'
versions = ['Python 3.10']

Activity

  1. dlukes commented on Mar 23, 2021

    dlukesmannequin
    MannequinAuthor

    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().

    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 mktemp could be as simple as (see https://mail.python.org/pipermail/python-dev/2019-March/156765.html):

    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)
    

    There's been some discussion as to what ENTROPY_BYTES should 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 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:

    1. 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.
    2. 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.)

  2. added
    3.10 (EOL)
    stdlib
    type-security
    on Mar 23, 2021
  3. dlukes commented on Mar 23, 2021

    dlukesmannequin
    MannequinAuthor

    A secure mktemp could be as simple as ...

    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-casing mktemp. 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 the tempfile module, not just mktemp:

    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.

  4. serhiy-storchaka commented on Mar 23, 2021

    @serhiy-storchaka
    Member

    You can use TemporaryDirectory.

    with tempfile.TemporaryDirectory() as dir:
        fifo_path = os.path.join(dir, "fifo")
        os.mkfifo(fifo_path, 0o600)
        ...
  5. dlukes commented on Mar 23, 2021

    dlukesmannequin
    MannequinAuthor

    You can use TemporaryDirectory.

    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.

  6. transferred this issue fromon Apr 10, 2022
  7. added a commit that references this issue on Nov 6, 2023
  8. lrlunin commented on Dec 11, 2024

    @lrlunin

    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?

    characters = "abcdefghijklmnopqrstuvwxyz0123456789_"

    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.

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

    3.10 (EOL)stdlibtype-security

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions