Commit e978526
committed
fix: eliminate insecure temporary file in atomic_file_write
Replace the close-then-reopen pattern in atomic_file_write() with
os.fdopen() to keep the file descriptor from tempfile.mkstemp() open
throughout the operation. The previous code closed the fd immediately
and reopened the temp file by name, creating a TOCTOU (time-of-check-
time-of-use) race window where an attacker could replace the temporary
file between close and reopen.
The fix passes the mkstemp fd directly to os.fdopen(), ensuring the
file handle is never released and re-acquired by name. For non-
truncating modes (e.g. 'a'), existing file content is copied through
the already-open fd rather than via shutil.copyfile on the path.
Fixes: #54
Signed-off-by: Pierluigi Lenoci <pierluigilenoci@gmail.com>1 parent cc9eca5 commit e978526
1 file changed
Lines changed: 16 additions & 4 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
54 | 54 | | |
55 | 55 | | |
56 | 56 | | |
57 | | - | |
58 | 57 | | |
59 | | - | |
60 | | - | |
61 | | - | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
62 | 70 | | |
63 | 71 | | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
64 | 76 | | |
65 | 77 | | |
66 | 78 | | |
| |||
0 commit comments