Skip to content

Commit a88d1b8

Browse files
AZero13sobolevn
andauthored
gh-143010: Prevent a TOCTOU issue by only calling open once (#143011)
* gh-143010: Prevent a TOCTOU issue by gh-143010: Prevent a TOCTOU issue by only calling open once RDM: per AZero13's research the 'x' option did not exist when this code was written, This modernization can thus drop the fd trick in _create_carefully and just use open with 'x' to achieve the same goal more securely. Co-authored-by: sobolevn <mail@sobolevn.me>
1 parent 700e9fa commit a88d1b8

File tree

2 files changed

+2
-5
lines changed

2 files changed

+2
-5
lines changed

Lib/mailbox.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2181,11 +2181,7 @@ def _unlock_file(f):
21812181

21822182
def _create_carefully(path):
21832183
"""Create a file if it doesn't exist and open for reading and writing."""
2184-
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
2185-
try:
2186-
return open(path, 'rb+')
2187-
finally:
2188-
os.close(fd)
2184+
return open(path, 'xb+')
21892185

21902186
def _create_temporary(path):
21912187
"""Create a temp file based on path and open for reading and writing."""
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed a bug in :mod:`mailbox` where the precise timing of an external event could result in the library opening an existing file instead of a file it expected to create.

0 commit comments

Comments
 (0)