Skip to content
9 changes: 9 additions & 0 deletions Doc/library/tempfile.rst
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,15 @@ The module defines the following user-callable items:
(the :meth:`!cleanup` call, exiting the context manager, when the object
is garbage-collected or during interpreter shutdown).

.. warning::

Cleanup is not robust against the tree being modified while it is removed.
Files outside of the tree may have their permissions and file flags reset.

On systems where :data:`shutil.rmtree.avoids_symlink_attacks` is
false, manipulating symbolic links during cleanup
may cause files outside of the tree to be removed.

.. audit-event:: tempfile.mkdtemp fullpath tempfile.TemporaryDirectory

.. versionadded:: 3.2
Expand Down
1 change: 1 addition & 0 deletions Lib/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ def _add(str, fn):
_add("HAVE_FCHMODAT", "chmod")
_add("HAVE_FCHOWNAT", "chown")
_add("HAVE_FSTATAT", "stat")
_add("HAVE_LSTAT", "lstat")
_add("HAVE_FUTIMESAT", "utime")
_add("HAVE_LINKAT", "link")
_add("HAVE_MKDIRAT", "mkdir")
Expand Down
47 changes: 27 additions & 20 deletions Lib/shutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,13 +638,15 @@ def _rmtree_unsafe(path, onerror):
onerror(os.rmdir, path, sys.exc_info())

# Version using fd-based APIs to protect against races
def _rmtree_safe_fd(topfd, path, onerror):
def _rmtree_safe_fd(topfd, path, onerror, parent_fd=None, orig_entry=None):
# parent_fd: the parent of topfd (None for top-level)
# orig_entry: the DirEntry of topfd (None for top-level)
try:
with os.scandir(topfd) as scandir_it:
entries = list(scandir_it)
except OSError as err:
err.filename = path
onerror(os.scandir, path, sys.exc_info())
onerror(os.scandir, path, sys.exc_info(), direntry=orig_entry, dir_fd=parent_fd)
return
for entry in entries:
fullname = os.path.join(path, entry.name)
Expand All @@ -658,29 +660,29 @@ def _rmtree_safe_fd(topfd, path, onerror):
orig_st = entry.stat(follow_symlinks=False)
is_dir = stat.S_ISDIR(orig_st.st_mode)
except OSError:
onerror(os.lstat, fullname, sys.exc_info())
onerror(os.lstat, fullname, sys.exc_info(), direntry=entry, dir_fd=topfd)
continue
if is_dir:
try:
dirfd = os.open(entry.name, os.O_RDONLY | os.O_NONBLOCK, dir_fd=topfd)
dirfd_closed = False
except OSError:
onerror(os.open, fullname, sys.exc_info())
onerror(os.open, fullname, sys.exc_info(), direntry=entry, dir_fd=topfd)
else:
try:
if os.path.samestat(orig_st, os.fstat(dirfd)):
_rmtree_safe_fd(dirfd, fullname, onerror)
_rmtree_safe_fd(dirfd, fullname, onerror, parent_fd=topfd, orig_entry=entry)
try:
os.close(dirfd)
except OSError:
# close() should not be retried after an error.
dirfd_closed = True
onerror(os.close, fullname, sys.exc_info())
onerror(os.close, fullname, sys.exc_info(), direntry=entry, dir_fd=topfd)
dirfd_closed = True
try:
os.rmdir(entry.name, dir_fd=topfd)
except OSError:
onerror(os.rmdir, fullname, sys.exc_info())
onerror(os.rmdir, fullname, sys.exc_info(), direntry=entry, dir_fd=topfd)
else:
try:
# This can only happen if someone replaces
Expand All @@ -689,25 +691,26 @@ def _rmtree_safe_fd(topfd, path, onerror):
raise OSError("Cannot call rmtree on a symbolic "
"link")
except OSError:
onerror(os.path.islink, fullname, sys.exc_info())
onerror(os.path.islink, fullname, sys.exc_info(), direntry=entry, dir_fd=topfd)
finally:
if not dirfd_closed:
try:
os.close(dirfd)
except OSError:
onerror(os.close, fullname, sys.exc_info())
onerror(os.close, fullname, sys.exc_info(), direntry=entry, dir_fd=topfd)
else:
try:
os.unlink(entry.name, dir_fd=topfd)
except OSError:
onerror(os.unlink, fullname, sys.exc_info())
onerror(os.unlink, fullname, sys.exc_info(), direntry=entry, dir_fd=topfd)

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

def rmtree(path, ignore_errors=False, onerror=None, *, dir_fd=None):
def rmtree(path, ignore_errors=False, onerror=None, *, dir_fd=None,
_onerror_kwargs=False):
"""Recursively delete a directory tree.

If dir_fd is not None, it should be a file descriptor open to a directory;
Expand All @@ -725,11 +728,15 @@ def rmtree(path, ignore_errors=False, onerror=None, *, dir_fd=None):
"""
sys.audit("shutil.rmtree", path, dir_fd)
if ignore_errors:
def onerror(*args):
def onerror(*args, **kwargs):
pass
elif onerror is None:
def onerror(*args):
def onerror(*args, **kwargs):
raise
elif not _onerror_kwargs:
_orig_onerror = onerror
def onerror(*args, **kwargs):
return _orig_onerror(*args)
if _use_fd_functions:
# While the unsafe rmtree works fine on bytes, the fd based does not.
if isinstance(path, bytes):
Expand All @@ -739,40 +746,40 @@ def onerror(*args):
try:
orig_st = os.lstat(path, dir_fd=dir_fd)
except Exception:
onerror(os.lstat, path, sys.exc_info())
onerror(os.lstat, path, sys.exc_info(), dir_fd=dir_fd)
return
try:
fd = os.open(path, os.O_RDONLY | os.O_NONBLOCK, dir_fd=dir_fd)
fd_closed = False
except Exception:
onerror(os.open, path, sys.exc_info())
onerror(os.open, path, sys.exc_info(), dir_fd=dir_fd)
return
try:
if os.path.samestat(orig_st, os.fstat(fd)):
_rmtree_safe_fd(fd, path, onerror)
_rmtree_safe_fd(fd, path, onerror, parent_fd=dir_fd)
try:
os.close(fd)
except OSError:
# close() should not be retried after an error.
fd_closed = True
onerror(os.close, path, sys.exc_info())
onerror(os.close, path, sys.exc_info(), dir_fd=dir_fd)
fd_closed = True
try:
os.rmdir(path, dir_fd=dir_fd)
except OSError:
onerror(os.rmdir, path, sys.exc_info())
onerror(os.rmdir, path, sys.exc_info(), dir_fd=dir_fd)
else:
try:
# symlinks to directories are forbidden, see bug #1669
raise OSError("Cannot call rmtree on a symbolic link")
except OSError:
onerror(os.path.islink, path, sys.exc_info())
onerror(os.path.islink, path, sys.exc_info(), dir_fd=dir_fd)
finally:
if not fd_closed:
try:
os.close(fd)
except OSError:
onerror(os.close, path, sys.exc_info())
onerror(os.close, path, sys.exc_info(), dir_fd=dir_fd)
else:
if dir_fd is not None:
raise NotImplementedError("dir_fd unavailable on this platform")
Expand Down
105 changes: 93 additions & 12 deletions Lib/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,15 +277,68 @@ def _dont_follow_symlinks(func, path, *args):
elif _os.name == 'nt' or not _os.path.islink(path):
func(path, *args)

def _resetperms(path):
def _resetflags(path):
try:
chflags = _os.chflags
except AttributeError:
pass
else:
_dont_follow_symlinks(chflags, path, 0)

def _resetperms(path):
_resetflags(path)
_dont_follow_symlinks(_os.chmod, path, 0o700)

# True if TemporaryDirectory._rmtree() can work relative to open directories
# instead of resolving paths again.
_rmtree_use_dir_fd = (
{_os.chmod, _os.unlink, _os.lstat} <= _os.supports_dir_fd
and _os.chmod in _os.supports_fd
)

def _resetperms_fd(dir_fd, path):
# Same as _resetperms(), but for the directory referred to by dir_fd.
if dir_fd is None:
_resetperms(path)
return
_resetflags(path)
_os.chmod(dir_fd, 0o700)

try:
_nofollow_mode = _os.O_RDONLY | _os.O_NONBLOCK | _os.O_NOFOLLOW
except AttributeError:
_nofollow_mode = None

def _resetperms_at(name, dir_fd, path):
# Same as _resetperms(), but name is resolved relative to the directory
# file descriptor dir_fd. path is only used for os.chflags(), which
# doesn't support dir_fd or file descriptors.
if dir_fd is None:
_resetperms(path)
return
_resetflags(path)
if _os.chmod in _os.supports_follow_symlinks:
_os.chmod(name, 0o700, dir_fd=dir_fd, follow_symlinks=False)
else:
# dir_fd & follow_symlinks is not supported on this platform.
# Try chmod opening the file with O_NOFOLLOW.
if _nofollow_mode is not None:
try:
fd = _os.open(name, _nofollow_mode, dir_fd=dir_fd)
except OSError:
pass
else:
try:
_os.chmod(fd, 0o700)
finally:
_os.close(fd)
return
# If that did not work, we change by name, which is subject to a race
# condition.
stat = _os.lstat(name, dir_fd=dir_fd)
if not _stat.S_ISLNK(stat.st_mode):
_os.chmod(name, 0o700, dir_fd=dir_fd)


# User visible interfaces.

Expand Down Expand Up @@ -876,33 +929,55 @@ def __init__(self, suffix=None, prefix=None, dir=None,
ignore_errors=self._ignore_cleanup_errors)

@classmethod
def _rmtree(cls, name, ignore_errors=False, repeated=False):
def onerror(func, path, exc_info):
def _rmtree(cls, name, ignore_errors=False, repeated=False, dir_fd=None,
fullname=None):

# work with str paths throughout
name = _os.fsdecode(name)
fullname = name if fullname is None else _os.fsdecode(fullname)

def onerror(func, path, exc_info, direntry=None, dir_fd=None):
path = _os.fsdecode(path)
if issubclass(exc_info[0], PermissionError):
if repeated and path == name:
if ignore_errors:
return
raise

# fullpath is path as seen from the working directory
fullpath = fullname + path[len(name):]
# base is path relative to dir_fd, the directory rmtree()
# reached it through, or the whole path when there is none
if dir_fd is None or not _rmtree_use_dir_fd:
base, dir_fd = path, None
elif direntry is None:
base = path
else:
base = direntry.name

try:
if path != name:
_resetperms(_os.path.dirname(path))
_resetperms(path)
# The parent directory of path is the one referred to
# by dir_fd.
_resetperms_fd(dir_fd, _os.path.dirname(fullpath))
_resetperms_at(base, dir_fd, fullpath)

try:
_os.unlink(path)
_os.unlink(base, dir_fd=dir_fd)
except IsADirectoryError:
cls._rmtree(path, ignore_errors=ignore_errors)
cls._rmtree(base, ignore_errors=ignore_errors,
repeated=(path == name),
dir_fd=dir_fd, fullname=fullpath)
except PermissionError:
# The PermissionError handler was originally added for
# FreeBSD in directories, but it seems that it is raised
# on Windows too.
# bpo-43153: Calling _rmtree again may
# raise NotADirectoryError and mask the PermissionError.
# So we must re-raise the current PermissionError if
# path is not a directory.
# fullpath is not a directory.
try:
st = _os.lstat(path)
st = _os.lstat(fullpath)
except OSError:
if ignore_errors:
return
Expand All @@ -916,17 +991,23 @@ def onerror(func, path, exc_info):
if ignore_errors:
return
raise
cls._rmtree(path, ignore_errors=ignore_errors,
repeated=(path == name))
cls._rmtree(base, ignore_errors=ignore_errors,
repeated=(path == name),
dir_fd=dir_fd, fullname=fullpath)
except FileNotFoundError:
pass
except OSError:
if ignore_errors:
return
raise
elif issubclass(exc_info[0], FileNotFoundError):
pass
else:
if not ignore_errors:
raise

_shutil.rmtree(name, onerror=onerror)
_shutil.rmtree(name, onerror=onerror, dir_fd=dir_fd,
_onerror_kwargs=True)

@classmethod
def _cleanup(cls, name, warn_message, ignore_errors=False):
Expand Down
5 changes: 5 additions & 0 deletions Lib/test/support/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2289,3 +2289,8 @@ def control_characters_c0() -> list[str]:
C0 control characters defined as the byte range 0x00-0x1F, and 0x7F.
"""
return [chr(c) for c in range(0x00, 0x20)] + ["\x7F"]


_ROOT_IN_POSIX = hasattr(os, 'geteuid') and os.geteuid() == 0
requires_root_user = unittest.skipUnless(_ROOT_IN_POSIX, "test needs root privilege")
requires_non_root_user = unittest.skipIf(_ROOT_IN_POSIX, "test needs non-root account")
Loading
Loading