Content · Programming · Python

Python Verify Extracted File Paths Stay Inside a Destination

Reject archive members that resolve outside the chosen extraction root.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Reject archive members that resolve outside the chosen extraction root.

How It Works


Even if a member name looks relative, components such as .. and symlinks can send an extraction elsewhere. A basic screening function should reject absolute names and parent components. For hostile archives, pair this with restrictive extraction facilities and an isolated destination.

The sample is an initial filter for POSIX ZIP/TAR entry names, not a complete platform-independent archive extraction sandbox.

Step-by-Step Example


from pathlib import Path, PurePosixPath

def acceptable_name(entry_name):
    entry = PurePosixPath(entry_name)
    return not entry.is_absolute() and ".." not in entry.parts and "\\" not in entry_name

for name in ["docs/note.txt", "../secrets.txt", "/tmp/escape.txt"]:
    print(name, acceptable_name(name))

Understanding the Example


  • The function definition gives the operation a reusable name and makes its inputs explicit.
  • The expression 'PurePosixPath(entry_name)' supplies the value stored as 'entry'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

docs/note.txt True
../secrets.txt False
/tmp/escape.txt False

Where This Fits in a Real Program


A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.

Practice: Try It Yourself


Add test cases with an empty name, nested directories and Windows-style separators.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Checking only for the substring "../" and overlooking other path representations.
  • Believing a lexical path check can prevent malicious symlink redirection during extraction.

Key Takeaways


  • Reject archive members that resolve outside the chosen extraction root.
  • Even if a member name looks relative, components such as .
  • The sample is an initial filter for POSIX ZIP/TAR entry names, not a complete platform-independent archive extraction sandbox.
Share this resourceSend this page to someone who may find it useful.