Skip to content

Commit 56caf8e

Browse files
StanFromIrelandencukou
authored andcommitted
gh-157579: Fix race condition in the cleanup of tempfile.TemporaryDirectory (GH-157580)
(cherry picked from commit 5c20517) Co-authored-by: Stan Ulbrych <stan@python.org> Co-authored-by: Petr Viktorin <encukou@gmail.com>
1 parent 69368eb commit 56caf8e

6 files changed

Lines changed: 235 additions & 19 deletions

File tree

‎Doc/library/tempfile.rst‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,15 @@ The module defines the following user-callable items:
207207
debugging or when you need your cleanup behavior to be conditional based on
208208
other logic.
209209

210+
.. warning::
211+
212+
Cleanup is not robust against the tree being modified while it is removed.
213+
Files outside of the tree may have their permissions and file flags reset.
214+
215+
On systems where :data:`shutil.rmtree.avoids_symlink_attacks` is
216+
false, manipulating symbolic links during cleanup
217+
may cause files outside of the tree to be removed.
218+
210219
.. audit-event:: tempfile.mkdtemp fullpath tempfile.TemporaryDirectory
211220

212221
.. versionadded:: 3.2

‎Lib/shutil.py‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,7 @@ def _rmtree_safe_fd(stack, onexc):
650650
# save a call to os.lstat() when walking subdirectories.
651651
func, dirfd, path, orig_entry = stack.pop()
652652
name = path if orig_entry is None else orig_entry.name
653+
parent_fd = None if func is os.close else dirfd
653654
try:
654655
if func is os.close:
655656
os.close(dirfd)
@@ -697,21 +698,22 @@ def _rmtree_safe_fd(stack, onexc):
697698
except FileNotFoundError:
698699
continue
699700
except OSError as err:
700-
onexc(os.unlink, fullname, err)
701+
onexc(os.unlink, fullname, err, direntry=entry, dir_fd=topfd)
701702
except FileNotFoundError as err:
702703
if orig_entry is None or func is os.close:
703704
err.filename = path
704-
onexc(func, path, err)
705+
onexc(func, path, err, direntry=orig_entry, dir_fd=parent_fd)
705706
except OSError as err:
706707
err.filename = path
707-
onexc(func, path, err)
708+
onexc(func, path, err, direntry=orig_entry, dir_fd=parent_fd)
708709

709710
_use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <=
710711
os.supports_dir_fd and
711712
os.scandir in os.supports_fd and
712713
os.stat in os.supports_follow_symlinks)
713714

714-
def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None):
715+
def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None,
716+
_onexc_kwargs=False):
715717
"""Recursively delete a directory tree.
716718
717719
If dir_fd is not None, it should be a file descriptor open to a directory;
@@ -734,24 +736,29 @@ def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None):
734736

735737
sys.audit("shutil.rmtree", path, dir_fd)
736738
if ignore_errors:
737-
def onexc(*args):
739+
def onexc(*args, **kwargs):
738740
pass
739741
elif onerror is None and onexc is None:
740-
def onexc(*args):
742+
def onexc(*args, **kwargs):
741743
raise
742744
elif onexc is None:
743745
if onerror is None:
744-
def onexc(*args):
746+
def onexc(*args, **kwargs):
745747
raise
746748
else:
747749
# delegate to onerror
748-
def onexc(*args):
750+
def onexc(*args, **kwargs):
749751
func, path, exc = args
750752
if exc is None:
751753
exc_info = None, None, None
752754
else:
753755
exc_info = type(exc), exc, exc.__traceback__
754756
return onerror(func, path, exc_info)
757+
elif not _onexc_kwargs:
758+
# Only the internal caller in tempfile asks for the extra arguments.
759+
_onexc = onexc
760+
def onexc(func, path, err, **kwargs):
761+
return _onexc(func, path, err)
755762

756763
if _use_fd_functions:
757764
# While the unsafe rmtree works fine on bytes, the fd based does not.

‎Lib/tempfile.py‎

Lines changed: 90 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
import shutil as _shutil
4444
import errno as _errno
4545
from random import Random as _Random
46+
import stat as _stat
4647
import sys as _sys
4748
import types as _types
4849
import weakref as _weakref
@@ -273,15 +274,68 @@ def _dont_follow_symlinks(func, path, *args):
273274
elif not _os.path.islink(path):
274275
func(path, *args)
275276

276-
def _resetperms(path):
277+
def _resetflags(path):
277278
try:
278279
chflags = _os.chflags
279280
except AttributeError:
280281
pass
281282
else:
282283
_dont_follow_symlinks(chflags, path, 0)
284+
285+
def _resetperms(path):
286+
_resetflags(path)
283287
_dont_follow_symlinks(_os.chmod, path, 0o700)
284288

289+
# True if TemporaryDirectory._rmtree() can work relative to open directories
290+
# instead of resolving paths again.
291+
_rmtree_use_dir_fd = (
292+
{_os.chmod, _os.unlink, _os.lstat} <= _os.supports_dir_fd
293+
and _os.chmod in _os.supports_fd
294+
)
295+
296+
def _resetperms_fd(dir_fd, path):
297+
# Same as _resetperms(), but for the directory referred to by dir_fd.
298+
if dir_fd is None:
299+
_resetperms(path)
300+
return
301+
_resetflags(path)
302+
_os.chmod(dir_fd, 0o700)
303+
304+
try:
305+
_nofollow_mode = _os.O_RDONLY | _os.O_NONBLOCK | _os.O_NOFOLLOW
306+
except AttributeError:
307+
_nofollow_mode = None
308+
309+
def _resetperms_at(name, dir_fd, path):
310+
# Same as _resetperms(), but name is resolved relative to the directory
311+
# file descriptor dir_fd. path is only used for os.chflags(), which
312+
# doesn't support dir_fd or file descriptors.
313+
if dir_fd is None:
314+
_resetperms(path)
315+
return
316+
_resetflags(path)
317+
if _os.chmod in _os.supports_follow_symlinks:
318+
_os.chmod(name, 0o700, dir_fd=dir_fd, follow_symlinks=False)
319+
else:
320+
# dir_fd & follow_symlinks is not supported on this platform.
321+
# Try chmod opening the file with O_NOFOLLOW.
322+
if _nofollow_mode is not None:
323+
try:
324+
fd = _os.open(name, _nofollow_mode, dir_fd=dir_fd)
325+
except OSError:
326+
pass
327+
else:
328+
try:
329+
_os.chmod(fd, 0o700)
330+
finally:
331+
_os.close(fd)
332+
return
333+
# If that did not work, we change by name, which is subject to a race
334+
# condition.
335+
stat = _os.lstat(name, dir_fd=dir_fd)
336+
if not _stat.S_ISLNK(stat.st_mode):
337+
_os.chmod(name, 0o700, dir_fd=dir_fd)
338+
285339

286340
# User visible interfaces.
287341

@@ -893,24 +947,43 @@ def __init__(self, suffix=None, prefix=None, dir=None,
893947
ignore_errors=self._ignore_cleanup_errors, delete=self._delete)
894948

895949
@classmethod
896-
def _rmtree(cls, name, ignore_errors=False, repeated=False):
897-
def onexc(func, path, exc):
950+
def _rmtree(cls, name, ignore_errors=False, repeated=False, dir_fd=None,
951+
fullname=None):
952+
if fullname is None:
953+
fullname = name
954+
955+
def onexc(func, path, exc, direntry=None, dir_fd=None):
898956
# On DragonFly BSD, UF_NOUNLINK removal fails with EISDIR, not EPERM.
899957
if isinstance(exc, (PermissionError, IsADirectoryError)):
900958
if repeated and path == name:
901959
if ignore_errors:
902960
return
903961
raise
904962

963+
# fullpath is path as seen from the working directory
964+
fullpath = fullname + path[len(name):]
965+
# base is path relative to dir_fd, the directory rmtree()
966+
# reached it through, or the whole path when there is none
967+
if dir_fd is None or not _rmtree_use_dir_fd:
968+
base, dir_fd = path, None
969+
elif direntry is None:
970+
base = path
971+
else:
972+
base = direntry.name
973+
905974
try:
906975
if path != name:
907-
_resetperms(_os.path.dirname(path))
908-
_resetperms(path)
976+
# The parent directory of path is the one referred to
977+
# by dir_fd.
978+
_resetperms_fd(dir_fd, _os.path.dirname(fullpath))
979+
_resetperms_at(base, dir_fd, fullpath)
909980

910981
try:
911-
_os.unlink(path)
982+
_os.unlink(base, dir_fd=dir_fd)
912983
except IsADirectoryError:
913-
cls._rmtree(path, ignore_errors=ignore_errors)
984+
cls._rmtree(base, ignore_errors=ignore_errors,
985+
repeated=(path == name),
986+
dir_fd=dir_fd, fullname=fullpath)
914987
except PermissionError:
915988
# The PermissionError handler was originally added for
916989
# FreeBSD in directories, but it seems that it is raised
@@ -919,21 +992,27 @@ def onexc(func, path, exc):
919992
# raise NotADirectoryError and mask the PermissionError.
920993
# So we must re-raise the current PermissionError if
921994
# path is not a directory.
922-
if not _os.path.isdir(path) or _os.path.isjunction(path):
995+
if (not _os.path.isdir(fullpath)
996+
or _os.path.isjunction(fullpath)):
923997
if ignore_errors:
924998
return
925999
raise
926-
cls._rmtree(path, ignore_errors=ignore_errors,
927-
repeated=(path == name))
1000+
cls._rmtree(base, ignore_errors=ignore_errors,
1001+
repeated=(path == name),
1002+
dir_fd=dir_fd, fullname=fullpath)
9281003
except FileNotFoundError:
9291004
pass
1005+
except OSError:
1006+
if ignore_errors:
1007+
return
1008+
raise
9301009
elif isinstance(exc, FileNotFoundError):
9311010
pass
9321011
else:
9331012
if not ignore_errors:
9341013
raise
9351014

936-
_shutil.rmtree(name, onexc=onexc)
1015+
_shutil.rmtree(name, onexc=onexc, dir_fd=dir_fd, _onexc_kwargs=True)
9371016

9381017
@classmethod
9391018
def _cleanup(cls, name, warn_message, ignore_errors=False, delete=True):

‎Lib/test/test_shutil.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,37 @@ def check_args_to_onexc(self, func, arg, exc):
495495
self.assertTrue(isinstance(exc, OSError))
496496
self.errorState = 3
497497

498+
@os_helper.skip_if_dac_override
499+
@os_helper.skip_unless_working_chmod
500+
@unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks,
501+
'requires the fd based implementation of rmtree()')
502+
def test_on_exc_kwargs(self):
503+
os.mkdir(TESTFN)
504+
self.addCleanup(shutil.rmtree, TESTFN)
505+
506+
child_dir_path = os.path.join(TESTFN, 'b')
507+
child_file_path = os.path.join(child_dir_path, 'a')
508+
os.mkdir(child_dir_path)
509+
os_helper.create_empty_file(child_file_path)
510+
old_child_dir_mode = os.stat(child_dir_path).st_mode
511+
# Make unwritable.
512+
new_mode = stat.S_IREAD|stat.S_IEXEC
513+
os.chmod(child_dir_path, new_mode)
514+
515+
self.addCleanup(os.chmod, child_dir_path, old_child_dir_mode)
516+
517+
calls = []
518+
def onexc(func, path, err, direntry=None, dir_fd=None):
519+
calls.append((func, path, err))
520+
if func is os.unlink:
521+
self.assertEqual(direntry.name, os.path.basename(path))
522+
self.assertTrue(os.path.samestat(
523+
os.stat(path), os.stat(direntry.name, dir_fd=dir_fd)))
524+
525+
shutil.rmtree(TESTFN, onexc=onexc, _onexc_kwargs=True)
526+
self.assertIn((os.unlink, child_file_path),
527+
[(func, path) for func, path, err in calls])
528+
498529
@unittest.skipIf(sys.platform[:6] == 'cygwin',
499530
"This test can't be run on Cygwin (issue #1071513).")
500531
@os_helper.skip_if_dac_override

‎Lib/test/test_tempfile.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import gc
1515
import shutil
1616
import subprocess
17+
import sysconfig
1718
from unittest import mock
1819

1920
import unittest
@@ -1854,6 +1855,54 @@ def test(target, target_is_directory):
18541855
new_flags = os.stat(dir1).st_flags
18551856
self.assertEqual(new_flags, old_flags)
18561857

1858+
@os_helper.skip_unless_symlink
1859+
@os_helper.skip_unless_working_chmod
1860+
@support.requires_non_root_user
1861+
@unittest.skipIf(support.is_emscripten, 'Fails due to Emscripten bug:'
1862+
'emscripten-core/emscripten#27761')
1863+
@unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks,
1864+
'requires the fd based implementation of rmtree()')
1865+
def test_cleanup_with_symlink_race(self):
1866+
# cleanup() should not operate on files outside of the temporary
1867+
# directory when a directory is replaced with a symlink while it
1868+
# recovers from a PermissionError (CVE-2026-12345).
1869+
with self.do_create(recurse=0) as target:
1870+
target_file = os.path.join(target, 'file1')
1871+
open(target_file, 'wb').close()
1872+
target_mode = os.stat(target_file).st_mode
1873+
1874+
d1 = self.do_create(recurse=0)
1875+
dir1 = os.path.join(d1.name, 'dir1')
1876+
os.mkdir(dir1)
1877+
open(os.path.join(dir1, 'file1'), 'wb').close()
1878+
# Removing contents of dir1 fails with a PermissionError, and
1879+
# dir1 is replaced with a symlink to target at the very moment
1880+
# cleanup() starts to recover from that error.
1881+
os.chmod(dir1, 0o500)
1882+
unlink = os.unlink
1883+
def hook(path, *, dir_fd=None):
1884+
try:
1885+
return unlink(path, dir_fd=dir_fd)
1886+
except PermissionError:
1887+
if not os.path.islink(dir1):
1888+
os.chmod(dir1, 0o700)
1889+
os.rename(dir1, dir1 + '_moved')
1890+
os.symlink(target, dir1)
1891+
raise
1892+
try:
1893+
with mock.patch('os.unlink', hook):
1894+
with contextlib.suppress(OSError):
1895+
d1.cleanup()
1896+
finally:
1897+
if os.path.islink(dir1):
1898+
os.unlink(dir1)
1899+
os.rename(dir1 + '_moved', dir1)
1900+
os.chmod(dir1, 0o700)
1901+
d1.cleanup()
1902+
1903+
self.assertTrue(os.path.exists(target_file))
1904+
self.assertEqual(os.stat(target_file).st_mode, target_mode)
1905+
18571906
@support.cpython_only
18581907
def test_del_on_collection(self):
18591908
# A TemporaryDirectory is deleted when garbage collected
@@ -2026,6 +2075,29 @@ def test_modes(self):
20262075
d.cleanup()
20272076
self.assertFalse(os.path.exists(d.name))
20282077

2078+
@support.subTests('ignore_errors', (True, False))
2079+
def test_parent_mode_preserved(self, ignore_errors):
2080+
# Test that cleanup does not touch the parent directory,
2081+
# even if that prevents removal.
2082+
for mode in range(8):
2083+
mode <<= 6
2084+
with self.subTest(mode=format(mode, '03o')):
2085+
outer = self.do_create()
2086+
with outer:
2087+
d = self.do_create(dir=outer.name, dirs=2, files=2,
2088+
ignore_cleanup_errors=ignore_errors)
2089+
with d:
2090+
os.chmod(outer.name, mode)
2091+
orig_mode = os.stat(outer.name).st_mode
2092+
try:
2093+
d.cleanup()
2094+
except PermissionError:
2095+
if ignore_errors:
2096+
raise
2097+
self.assertEqual(os.stat(outer.name).st_mode, orig_mode)
2098+
outer.cleanup()
2099+
self.assertFalse(os.path.exists(outer.name))
2100+
20292101
def check_flags(self, flags):
20302102
# skip the test if these flags are not supported (ex: FreeBSD 13)
20312103
filename = os_helper.TESTFN
@@ -2063,5 +2135,17 @@ def test_delete_false(self):
20632135
self.assertTrue(os.path.exists(working_dir))
20642136
shutil.rmtree(working_dir)
20652137

2138+
@unittest.skipUnless(
2139+
sysconfig.get_config_var('PY_SUPPORT_TIER')
2140+
and sysconfig.get_config_var('PY_SUPPORT_TIER') <= 3,
2141+
'regression test for supported platforms')
2142+
@unittest.skipIf(support.MS_WINDOWS, 'dirfd not used on Windows')
2143+
@unittest.skipIf(support.is_wasi, 'WASI has no chmod')
2144+
def test_cleanup_safe(self):
2145+
"""Verify that cleanup uses the safer code path"""
2146+
# This is a regression test. Feel free to add exceptions for new
2147+
# platforms, but don't forget to update the docs.
2148+
self.assertTrue(tempfile._rmtree_use_dir_fd)
2149+
20662150
if __name__ == "__main__":
20672151
unittest.main()

0 commit comments

Comments
 (0)