Content · Programming · Python

Python tarfile Extraction Filters: Prevent Unsafe Extraction

TAR extraction filters inspect each member before it is written.

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

TAR extraction filters inspect each member before it is written.

How It Works


TAR extraction filters inspect each member before it is written. The built-in data filter rejects many unsafe links, special files and paths outside the destination; a custom filter can also reject unexpected entries or enforce a whitelist.

Step-by-Step Example


import tarfile

def regular_files_only(archive_member, destination_path):
    filtered_member = tarfile.data_filter(archive_member, destination_path)
    if filtered_member is not None and not filtered_member.isfile():
        return None
    return filtered_member

print(regular_files_only.__name__)

Understanding the Example


  • The function definition gives the operation a reusable name and makes its inputs explicit.
  • The expression 'tarfile.data_filter(archive_member, destination_path)' supplies the value stored as 'filtered_member'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

regular_files_only

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


Implement a custom filter that rejects non-regular archive members before extraction.

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


  • Disabling filters to silence exceptions instead of understanding why an archive contains unsafe paths.
  • Keep extracted member count and total decompressed size within explicit limits.

Key Takeaways


  • TAR extraction filters inspect each member before it is written.
  • TAR extraction filters inspect each member before it is written.
  • Keep extracted member count and total decompressed size within explicit limits.
Share this resourceSend this page to someone who may find it useful.