https://github.com/python/cpython/commit/33c9ebe437064ae5066767128e94c2fc9e388a50
commit: 33c9ebe437064ae5066767128e94c2fc9e388a50
branch: 3.14
author: Miss Islington (bot) <[email protected]>
committer: bitdancer <[email protected]>
date: 2025-12-22T13:14:59-05:00
summary:

[3.14] gh-143010: Prevent a TOCTOU issue by only calling open once (GH-143011) 
(#143080)

gh-143010: Prevent a TOCTOU issue by only calling open once (GH-143011)

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.
(cherry picked from commit a88d1b8dab4cbd3180dd7f1acb44d627db90323b)

Co-authored-by: AZero13 <[email protected]>
Co-authored-by: sobolevn <[email protected]>

files:
A Misc/NEWS.d/next/Library/2025-12-20-01-49-02.gh-issue-143010._-SWX0.rst
M Lib/mailbox.py

diff --git a/Lib/mailbox.py b/Lib/mailbox.py
index b00d9e8634c785..364af6bb010959 100644
--- a/Lib/mailbox.py
+++ b/Lib/mailbox.py
@@ -2183,11 +2183,7 @@ def _unlock_file(f):
 
 def _create_carefully(path):
     """Create a file if it doesn't exist and open for reading and writing."""
-    fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
-    try:
-        return open(path, 'rb+')
-    finally:
-        os.close(fd)
+    return open(path, 'xb+')
 
 def _create_temporary(path):
     """Create a temp file based on path and open for reading and writing."""
diff --git 
a/Misc/NEWS.d/next/Library/2025-12-20-01-49-02.gh-issue-143010._-SWX0.rst 
b/Misc/NEWS.d/next/Library/2025-12-20-01-49-02.gh-issue-143010._-SWX0.rst
new file mode 100644
index 00000000000000..4914d0b7be727b
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2025-12-20-01-49-02.gh-issue-143010._-SWX0.rst
@@ -0,0 +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.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to