dlenski / gp-saml-gui

Interactively authenticate to GlobalProtect VPNs that require SAML
GNU General Public License v3.0
306 stars 69 forks source link

Avoid leaking temporary file #20

Closed davel closed 4 years ago

davel commented 4 years ago

We unlink the file after we have its fd, so that when openconnect terminates the file is removed from disc.

dlenski commented 4 years ago

NamedTemporaryFile should do this automatically (default parameter delete=True). What you've discovered is that this doesn't work correctly with the subsequent exec though… :thinking:

I think simpler solution will be…

1) just close-and-unlink the tempfile before doing the exec

import tempfile
from os import dup2, unlink, read

name = None
with tempfile.NamedTemporaryFile('w+') as tf:
    tf.write('foo')
    tf.flush()
    tf.seek(0)
    dup2(tf.fileno(), 0)
    name = tf.name
    # tempfile gets closed and unlinked

# its contents should still accessible via fd 0
print(read(0, 3))

# but it should no longer be possible to open this file
try:
    open(name)
    print("uh-oh, {} still exists".format(name))
except FileNotFoundError as e:
    print("good, {} no longer exists".format(name))

2) just use TemporaryFile instead of NamedTemporaryFile (since we don't actually need the file to have any FS-visible name ever)