Skip to content

Ensure that FileManager.copyItem cannot copy directory metadata to files #1081

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 11, 2024

Conversation

jmschonfeld
Copy link
Contributor

FileManager.copyItem(atPath:toPath:) has a TOCTOU bug due to how it recursively copies directories. As we recursively copy directories, we copy the directory itself with default metadata/permissions, copy the contents of the directory, then copy the metadata over (which may change permissions on the directory, including potentially making it read-only). This TOCTOU bug allows another process with write access to the source directory to (with the right timing) cause a process that uses FileManager.copyItem to copy and apply metadata to a file rather than a directory.

To fix the TOCTOU issue, the post-order traversal which copies the metadata now:

  • Opens a file descriptor to both the source and destination directories
  • fstats the source and destination directories to validate that they are directories (and not files)
  • Then copies metadata from one open file descriptor to the other
    • This uses fcopyfile on Darwin, and a custom function on Linux where fcopyfile does not exist

This ensures that we only copy metadata between directories and cannot accidentally apply metadata to a file.

@jmschonfeld
Copy link
Contributor Author

@swift-ci please test

@jmschonfeld
Copy link
Contributor Author

@swift-ci please test

@jmschonfeld
Copy link
Contributor Author

@swift-ci please test Windows platform

@jmschonfeld
Copy link
Contributor Author

@swift-ci please test

@jmschonfeld
Copy link
Contributor Author

@swift-ci please test Linux platform

@jmschonfeld
Copy link
Contributor Author

@swift-ci please test macOS Platform

@jmschonfeld jmschonfeld merged commit bb3fccf into swiftlang:main Dec 11, 2024
3 checks passed
@jmschonfeld jmschonfeld deleted the fm-directory-copy-toctou branch December 11, 2024 23:05
jmschonfeld added a commit to jmschonfeld/swift-foundation that referenced this pull request Dec 11, 2024
…les (swiftlang#1081)

* (135575520) Ensure that FileManager.copyItem cannot copy directory metadata to files

* Fix whitespacing

* Fix Windows test failure
jmschonfeld added a commit that referenced this pull request Dec 12, 2024
…les (#1081) (#1083)

* (135575520) Ensure that FileManager.copyItem cannot copy directory metadata to files

* Fix whitespacing

* Fix Windows test failure
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.

2 participants