Skip to content

fix(storage): prevent symlink TOCTOU race in transfer_manager.download_many_to_path - #19275

Draft
chandra-siri wants to merge 2 commits into
googleapis:mainfrom
chandra-siri:fix/b-586733922-toctou-repro
Draft

chandra-siri wants to merge 2 commits into
googleapis:mainfrom
chandra-siri:fix/b-586733922-toctou-repro

Conversation

@chandra-siri

Copy link
Copy Markdown
Contributor

Summary

Fixes a TOCTOU (time-of-check to time-of-use) race condition in transfer_manager.download_many_to_path where path containment was checked in the parent process before worker threads or processes created directories and opened destination files by string path.

Changes

  • New private helper module (google/cloud/storage/_path_containment.py):
    • _ContainedPath(str): picklable str subclass carrying destination_root across both THREAD and PROCESS worker pools without changing transfer_manager.download_many's public signature.
    • makedirs_within & open_for_write_within: on POSIX, opens the resolved root with O_NOFOLLOW + samestat verification and walks each relative path component using dir_fd + O_NOFOLLOW (O_NONBLOCK on leaf open to avoid blocking on FIFOs, cleared via fcntl after S_ISREG verification). On Windows (os.name == "nt"), performs per-component os.lstat / reparse-tag verification and opens without O_TRUNC, verifying samestat and S_ISREG before calling os.ftruncate(fd, 0).
    • ContainedFile: context manager providing descriptor-pinned .remove() (closing before dir_fd-pinned unlink) and .set_mtime() (os.utime on fileno()).
  • google/cloud/storage/transfer_manager.py:
    • download_many_to_path wraps validated destination paths in _ContainedPath and uses makedirs_within when create_directories=True, raising InvalidPathError on symlink/special-file containment mismatches while preserving existing OSError propagation and UserWarning behavior.
  • google/cloud/storage/blob.py:
    • Blob._handle_filename_and_download routes _ContainedPath targets through open_for_write_within and ContainedFile, leaving legacy callers (download_to_filename, plain download_many) unchanged.
  • Unit tests:
    • Added tests/unit/test__path_containment.py (POSIX + forced fallback matrix, fd cleanup checks).
    • Updated tests/unit/test_transfer_manager.py (including THREAD and PROCESS pool TOCTOU race tests, create_directories race tests, DataCorruption/NotFound cleanup, and mtime verification).
    • Updated tests/unit/test_blob.py for the _ContainedPath branch of _handle_filename_and_download.

Testing

  • pytest on tests/unit/test_transfer_manager.py, tests/unit/test__path_containment.py, and tests/unit/test_blob.py: 528 passed with 100% line+branch coverage on _path_containment.py, transfer_manager.py, and all modified lines/branches in blob.py.
  • ruff (I + format check) and flake8: clean.

…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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +177 to +182
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

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.

Suggested change
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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant