TarFile Statement#
The Python tarfile module makes it possible to read and write tar archives.
Code Audit checks on the use of:
TarFile.extractandTarFile.extractallUsing these methods in Python code can give serious security concerns.
The default rule is:
Assume all input is malicious.
Using these commands in Python code can expose systems to several risks:
Privilege escalation: An attacker can change file permissions on sensitive files (for example,
/etc/shadowor SSH keys) if the extraction process runs with root or elevated privileges.Sandbox escape: Many systems rely on extraction directories or temporary paths for isolation; malicious archives can break that isolation and allow code to operate outside the sandbox.
Tampering and log evasion: By modifying file timestamps or other metadata, an attacker can obscure activity, confuse forensic timelines, or mislead incident response.
Easy exploitation: Crafting a malicious tarball is straightforward and requires no specialized tools, making exploitation trivial for an attacker.
Danger
Using TarFile.extractall or TarFile.extract is dangerous.
Always. So good mitigation measurement must be present in the code!
But besides using these tarfile commands in your Python code, there have been some vulnerabilities with the tarfile module implementation in CPython in the past.
So from a security point of view checking if your code is extracting files using the tarfile command is vital.
Note
Use of the tarfile extraction methods in Python code should always be reviewed in depth!
This means:
Check if the code uses defence in-depth measures for extracting files.
Check if the files that will be extracted by the Python code can be assumed secure, so not tampered with. If not: validate if enough additional mitigation measurements are in place when using this code.
Mitigation measurements are always context dependent, and can be e.g. running the Python program in an isolated environment.
Preventive measures#
Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..".
Make sure a proper filter is set:
TarFile.extractall(path='.', members=None, *, numeric_owner=False, filter=None)
The filter argument specifies how members are modified or rejected before extraction. So set minimal filter='data' to prevent the most dangerous security issues, and read the Extraction filters section documentation for details.
Do not pass filter=“tar” or filter=“data” for untrusted archives. If you must unpack, force filter=“none” and run in a dedicated, non-privileged container/VM.
Note
This validation test requires always human inspection if the construct is detected. No automatic test can give you enough confidence! So no AI agent or other GenAI thing will help you.
Using this construct is fine, but make sure you known how to prevent disasters!