Python 3.12+tarfilefunction
tarfile.data_filter()
extraction filters
The 'data' extraction filter: it blocks everything dangerous for plain data — paths outside, links outside, devices, extra permissions.
Syntax
tar.extractall(path, filter='data') # или tarfile.data_filter(member, path)
It is the default since Python 3.14 and the right choice for untrusted archives: filter='data' in extract()/extractall(). On top of tar_filter checks it refuses links to absolute paths or outside the folder, devices and pipes, drops ownership and sets permissions so the file is readable. A leading '/' is silently stripped rather than refused. It does not stop denial of service (huge files).
Examples
import io, tarfile
with tarfile.open('evil.tar', 'w') as tar:
info = tarfile.TarInfo('../escape.txt')
info.size = 3
tar.addfile(info, io.BytesIO(b'bad'))
with tarfile.open('evil.tar') as tar:
try:
tar.extractall('out', filter='data')
except tarfile.OutsideDestinationError as e:
print(type(e).__name__, e.tarinfo.name) # → OutsideDestinationError ../escape.txt
import tarfile
m = tarfile.TarInfo('/etc/app.conf')
m.mode = 0o4777
safe = tarfile.data_filter(m, 'out')
print(safe.name, oct(safe.mode), safe.uid) # → etc/app.conf 0o755 None
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy