file – Is this usage of python tempfile.NamedTemporaryFile secure? – Education Career Blog

Is this usage of Python tempfile.NamedTemporaryFile secure (i.e. devoid security issues of deprecated tempfile.mktemp)?

def mktemp2():
    """Create and close an empty temporary file.
    Return the temporary filename"""
    tf = tempfile.NamedTemporaryFile(delete=False)
    tfilename = tf.name
    tf.close()
    return tfilename

outfilename = mktemp2()
subprocess.call('program_name','-o',outfilename)

What I need to run external command that requires output file name as one of the arguments. It overwrites the outfilename if that exists without warnings. I want to use temporary file as I just need to read its content, I don’t need it later.

,

Totally unsafe. There is an opportunity for an attacker to create the file with whatever permissions they like (or a symlink) with that name between when it is deleted and opened by the subprocess

If you can instead create the file in a directory other than /tmp that is owned and onnly read/writeable by your process, you don’t need to concern yourself with the security of the file as anything in the directory is protected

Leave a Comment