]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-143010: Prevent a TOCTOU issue by only calling open once (#143011)
authorAZero13 <gfunni234@gmail.com>
Mon, 22 Dec 2025 17:48:11 +0000 (12:48 -0500)
committerGitHub <noreply@github.com>
Mon, 22 Dec 2025 17:48:11 +0000 (12:48 -0500)
* 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>
Lib/mailbox.py
Misc/NEWS.d/next/Library/2025-12-20-01-49-02.gh-issue-143010._-SWX0.rst [new file with mode: 0644]

index 4a44642765cc9a434604ff366b727410c5cb4193..65923e9c5de3246adc71b743693791722a2378d7 100644 (file)
@@ -2181,11 +2181,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 (file)
index 0000000..4914d0b
--- /dev/null
@@ -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.