Prevent path traversal in Directory.read()#362
Open
assinscreedFC wants to merge 1 commit into
Open
Conversation
Directory.read() joined the source directory with a subname taken from EPUB OPF manifest hrefs (attacker-controlled and URL-decoded) without any sanitisation, so a crafted value such as '../../etc/passwd' (or its percent-encoded form) could escape the directory and read arbitrary files (CWE-22). Resolve both the base directory and the target with os.path.realpath and reject any target that falls outside the base directory before opening it. Add tests for a normal read and a rejected traversal. Fixes aerkalov#359
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #359 (path traversal / CWE-22).
Directory.read()joined the source directory with asubnametaken from EPUB OPF manifesthrefattributes (attacker-controlled, and URL-decoded viaunquote) without any sanitisation:A crafted href such as
../../etc/passwd(or its percent-encoded form%2e%2e%2f...) could escape the intended directory and read arbitrary files from disk.Fix
Resolve both the base directory and the requested target with
os.path.realpath(which also collapses..and follows symlinks), then reject any target that does not stay within the base directory before opening it.Legitimate relative hrefs (e.g.
Text/chapter1.xhtml) are unaffected.Tests
Added
TestDirectoryintests/test_utils.py:test_read_within_directory— a normal in-directory read still works.test_read_rejects_path_traversal— a../../href raises.Verification
pytest tests/test_utils.py— passed; full suite: 26 passed.ruff checkandruff format --check— clean.