Skip to content

Commit

Permalink
Restrict access to temporary files
Browse files Browse the repository at this point in the history
This commit ...

1. replaces `tempfile.mktemp()` function by `uuid.uuid1()` to create temporary
   files' names. The former one is marked unsafe for no reason, but may cause
   this code to be detected as unsafe as a result.

2. explicitly create temporary files with read/write access for owner only on
   unix-like filesystems.
  • Loading branch information
deathaxe committed Nov 8, 2023
1 parent a2a90c2 commit 1128075
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions modules/temp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import tempfile
import time
import uuid

# The folder to place all temporary files into.
TEMP_DIR = os.environ.get('XDG_RUNTIME_DIR')
Expand Down Expand Up @@ -63,7 +64,11 @@ class TempFile(object):

def __init__(self, mode='r'):
"""Initialize TempFile object."""
self.name = tempfile.mktemp(dir=TEMP_DIR)
self.name = None
while self.name is None:
candidate = os.path.join(TEMP_DIR, str(uuid.uuid1()))
if not os.path.exists(candidate):
self.name = candidate
self._file = None
self._mode = mode
# Cache unlink to keep it available even though the 'os' module is
Expand All @@ -90,13 +95,13 @@ def __exit__(self, exc, value, tb):
def open(self):
"""Open temporary file."""
if self._file is None:
try:
# ensure cache directory exists with write permissions
os.makedirs(TEMP_DIR, 0o700)
except OSError as e:
if e.errno != errno.EEXIST:
raise
self._file = open(self.name, mode=self._mode)
# ensure cache directory exists with write permissions
os.makedirs(TEMP_DIR, 0o700, exist_ok=True)
self._file = open(
file=self.name,
mode=self._mode,
opener=lambda file, flags: os.open(file, flags, 0o600)
)
return self._file

def close(self):
Expand Down

0 comments on commit 1128075

Please sign in to comment.