Severity: HIGH (Bandit B202 - tarfile_unsafe_members)
Vulnerability
tarfile.extractall() without member validation allows path traversal (zip slip attack).
Fix
import os
def _is_within_directory(directory, target):
abs_directory = os.path.realpath(directory)
abs_target = os.path.realpath(target)
return abs_target.startswith(abs_directory + os.sep) or abs_target == abs_directory
def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
for member in tar.getmembers():
member_path = os.path.join(path, member.name)
if not _is_within_directory(path, member_path):
raise Exception(f"Path traversal attempt: {member.name}")
tar.extractall(path, members, numeric_owner=numeric_owner)
References
- CWE-22: Path Traversal
- Bandit B202
Severity: HIGH (Bandit B202 - tarfile_unsafe_members)
Vulnerability
tarfile.extractall()without member validation allows path traversal (zip slip attack).Fix
References