Repository navigation
fix(storage): prevent symlink TOCTOU race in transfer_manager.download_many_to_path - #19275
chandra-siri wants to merge 2 commits into
Conversation
…86733922) download_many_to_path checked that each destination resolves inside destination_directory in the parent, but the worker later opened the path with a plain open(), so a directory component swapped for a symlink in between redirected the write outside destination_directory. os.makedirs, os.remove (on DataCorruption/NotFound) and os.utime had the same path-containment bug. Move the containment check to time of use: * Add the private _path_containment module. On POSIX it opens the canonical root with O_NOFOLLOW, walks every component with dir_fd + O_DIRECTORY|O_NOFOLLOW, creates the leaf with O_NOFOLLOW|O_NONBLOCK relative to the pinned parent, and performs cleanup and mtime updates against the pinned descriptors. Platforms without dir_fd (Windows) use a best-effort lstat/reparse-point check and verify before truncating. * download_many_to_path wraps targets in a picklable _ContainedPath(str) carrying the destination root, so download_many's signature is unchanged and THREAD and PROCESS workers both get the root. Directory creation uses the same pinned walk; a symlink found there is reported as InvalidPathError for that blob (raised after the batch when raise_exception=True). * Blob._handle_filename_and_download routes _ContainedPath targets through the pinned file; plain filenames are unchanged. A symlink or special file encountered at time of use raises the existing InvalidPathError; all other OSErrors keep their types.
There was a problem hiding this comment.
Code Review
This pull request introduces a new private helper module, _path_containment.py, to secure file downloads against directory traversal and symlink TOCTOU race conditions by verifying that destination paths remain strictly within the target directory. These checks are integrated into Blob downloads and transfer_manager.download_many_to_path, with comprehensive unit tests added. The review feedback correctly identifies a high-severity issue on Windows where the fallback check over-aggressively rejects non-malicious reparse points (such as OneDrive placeholders or NTFS compressed files) by checking for any non-zero st_reparse_tag. Implementing the suggested fix to only reject name surrogates (using the 0x20000000 bitmask) will prevent these false positives.
| def _fallback_check_component(path, root): | ||
| """``lstat`` ``path`` and reject symbolic links / reparse points.""" | ||
| st = os.lstat(path) | ||
| if stat.S_ISLNK(st.st_mode) or getattr(st, "st_reparse_tag", 0): | ||
| raise _not_contained(path, root) | ||
| return st |
There was a problem hiding this comment.
On Windows, os.lstat returns a non-zero st_reparse_tag for many types of reparse points that are not symbolic links or directory junctions, and do not perform path redirection. For example, OneDrive/iCloud placeholders, NTFS compressed files, and Windows Overlay Filter (WOF) compressed files all have non-zero reparse tags.
Rejecting any non-zero st_reparse_tag will cause download_many_to_path to fail with InvalidPathError when downloading to OneDrive folders or compressed directories on Windows.
To prevent these false positives while still securing against path traversal/redirection, we should only reject reparse points that are "Name Surrogates" (which can redirect paths, such as symbolic links and mount points/junctions). In Windows, a reparse tag is a name surrogate if its 29th bit (the Name Surrogate bit, 0x20000000) is set.
| def _fallback_check_component(path, root): | |
| """``lstat`` ``path`` and reject symbolic links / reparse points.""" | |
| st = os.lstat(path) | |
| if stat.S_ISLNK(st.st_mode) or getattr(st, "st_reparse_tag", 0): | |
| raise _not_contained(path, root) | |
| return st | |
| def _fallback_check_component(path, root): | |
| """lstat path and reject symbolic links / reparse points.""" | |
| st = os.lstat(path) | |
| tag = getattr(st, "st_reparse_tag", 0) | |
| if stat.S_ISLNK(st.st_mode) or (tag & 0x20000000): | |
| raise _not_contained(path, root) | |
| return st |
Summary
Fixes a TOCTOU (time-of-check to time-of-use) race condition in
transfer_manager.download_many_to_pathwhere path containment was checked in the parent process before worker threads or processes created directories and opened destination files by string path.Changes
google/cloud/storage/_path_containment.py):_ContainedPath(str): picklablestrsubclass carryingdestination_rootacross bothTHREADandPROCESSworker pools without changingtransfer_manager.download_many's public signature.makedirs_within&open_for_write_within: on POSIX, opens the resolved root withO_NOFOLLOW+samestatverification and walks each relative path component usingdir_fd+O_NOFOLLOW(O_NONBLOCKon leaf open to avoid blocking on FIFOs, cleared viafcntlafterS_ISREGverification). On Windows (os.name == "nt"), performs per-componentos.lstat/ reparse-tag verification and opens withoutO_TRUNC, verifyingsamestatandS_ISREGbefore callingos.ftruncate(fd, 0).ContainedFile: context manager providing descriptor-pinned.remove()(closing beforedir_fd-pinned unlink) and.set_mtime()(os.utimeonfileno()).google/cloud/storage/transfer_manager.py:download_many_to_pathwraps validated destination paths in_ContainedPathand usesmakedirs_withinwhencreate_directories=True, raisingInvalidPathErroron symlink/special-file containment mismatches while preserving existingOSErrorpropagation andUserWarningbehavior.google/cloud/storage/blob.py:Blob._handle_filename_and_downloadroutes_ContainedPathtargets throughopen_for_write_withinandContainedFile, leaving legacy callers (download_to_filename, plaindownload_many) unchanged.tests/unit/test__path_containment.py(POSIX + forced fallback matrix,fdcleanup checks).tests/unit/test_transfer_manager.py(includingTHREADandPROCESSpool TOCTOU race tests,create_directoriesrace tests,DataCorruption/NotFoundcleanup, andmtimeverification).tests/unit/test_blob.pyfor the_ContainedPathbranch of_handle_filename_and_download.Testing
pytestontests/unit/test_transfer_manager.py,tests/unit/test__path_containment.py, andtests/unit/test_blob.py: 528 passed with 100% line+branch coverage on_path_containment.py,transfer_manager.py, and all modified lines/branches inblob.py.ruff(I+ format check) andflake8: clean.