Python 3.12+tarfilefunction
tarfile.tar_filter()
extraction filters
The 'tar' extraction filter: it keeps UNIX features (links, permissions) but refuses paths outside the folder and dangerous bits.
Syntax
tar.extractall(path, filter='tar') # или tarfile.tar_filter(member, path)
It is softer than 'data': a symbolic link to '/etc/passwd' or outside the folder passes, and a later member can write a file through it — a hole for untrusted archives. It strips a leading '/', refuses paths outside the folder and clears setuid/setgid and group/other write bits. It suits your own backups, where links must be restored.
Examples
import tarfile
link = tarfile.TarInfo('passwd')
link.type = tarfile.SYMTYPE
link.linkname = '/etc/passwd'
print(tarfile.tar_filter(link, 'out').linkname) # → /etc/passwd — ссылка пропущена
try:
tarfile.data_filter(link, 'out')
except tarfile.AbsoluteLinkError:
print('data отклоняет') # → data отклоняет
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy