107 lines
5.0 KiB
Python
107 lines
5.0 KiB
Python
"""Bounded, traversal-safe ZIP/tar extraction for package inspection. Standard library only."""
|
|
import pathlib
|
|
import shutil
|
|
import stat
|
|
import sys
|
|
import tarfile
|
|
import zipfile
|
|
|
|
MAX_BYTES = 8 * 1024 * 1024 * 1024
|
|
MAX_FILES = 100000
|
|
|
|
|
|
def destination(root, name):
|
|
name = name.replace('\\', '/')
|
|
part = pathlib.PurePosixPath(name)
|
|
if part.is_absolute() or '..' in part.parts or ':' in name or '\x00' in name:
|
|
raise ValueError(f'unsafe archive member: {name!r}')
|
|
result = root.joinpath(*part.parts)
|
|
if not result.resolve().is_relative_to(root.resolve()):
|
|
raise ValueError('archive destination escapes root')
|
|
return result
|
|
|
|
|
|
def extract(source, root):
|
|
seen = set()
|
|
total = 0
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
if zipfile.is_zipfile(source):
|
|
with zipfile.ZipFile(source) as archive:
|
|
if len(archive.infolist()) > MAX_FILES:
|
|
raise ValueError('too many archive members')
|
|
for member in archive.infolist():
|
|
path = destination(root, member.filename)
|
|
key = str(path).casefold()
|
|
if key in seen:
|
|
raise ValueError('duplicate archive destination')
|
|
seen.add(key)
|
|
mode = member.external_attr >> 16
|
|
if stat.S_ISLNK(mode):
|
|
# Apple zip bundles may contain relative framework symlinks.
|
|
link = archive.read(member).decode('utf-8')
|
|
target = (path.parent / link).resolve()
|
|
if pathlib.Path(link).is_absolute() or not target.is_relative_to(root.resolve()):
|
|
raise ValueError('symlink escapes archive')
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.symlink_to(link)
|
|
continue
|
|
total += member.file_size
|
|
if total > MAX_BYTES:
|
|
raise ValueError('archive uncompressed budget exceeded')
|
|
if member.is_dir():
|
|
path.mkdir(parents=True, exist_ok=True)
|
|
else:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with archive.open(member) as src, path.open('xb') as dst:
|
|
shutil.copyfileobj(src, dst)
|
|
if mode:
|
|
path.chmod(mode & 0o777)
|
|
else:
|
|
with tarfile.open(source, 'r:*') as archive:
|
|
for index, member in enumerate(archive):
|
|
if index >= MAX_FILES:
|
|
raise ValueError('too many archive members')
|
|
path = destination(root, member.name)
|
|
if path == root and member.isdir():
|
|
continue
|
|
key = str(path).casefold()
|
|
if key in seen:
|
|
raise ValueError('duplicate archive destination')
|
|
seen.add(key)
|
|
total += member.size
|
|
if total > MAX_BYTES:
|
|
raise ValueError('archive uncompressed budget exceeded')
|
|
if member.isdir():
|
|
path.mkdir(parents=True, exist_ok=True)
|
|
elif member.isfile():
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with archive.extractfile(member) as src, path.open('xb') as dst:
|
|
shutil.copyfileobj(src, dst)
|
|
path.chmod(member.mode & 0o777)
|
|
elif member.issym():
|
|
target = (path.parent / member.linkname).resolve()
|
|
if pathlib.Path(member.linkname).is_absolute() or not target.is_relative_to(root.resolve()):
|
|
raise ValueError('symlink escapes archive')
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.symlink_to(member.linkname)
|
|
else:
|
|
raise ValueError('special/hardlinked archive member refused')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
if len(sys.argv) == 4 and sys.argv[1] == 'extract':
|
|
extract(pathlib.Path(sys.argv[2]), pathlib.Path(sys.argv[3]))
|
|
elif len(sys.argv) == 4 and sys.argv[1] == 'android-manifest':
|
|
import xml.etree.ElementTree as ET
|
|
manifest = pathlib.Path(sys.argv[2])
|
|
if manifest.stat().st_size > 1024 * 1024:
|
|
raise SystemExit('Android manifest exceeds inspection bound')
|
|
node = ET.parse(manifest).getroot()
|
|
android = '{http://schemas.android.com/apk/res/android}'
|
|
if node.tag != 'manifest' or node.get('package') != 'dev.teamspeach.mobile' or node.get(android + 'versionName') != sys.argv[3]:
|
|
raise SystemExit('AAB application identity/version mismatch')
|
|
if any(permission.get(android + 'name') == 'android.permission.REQUEST_INSTALL_PACKAGES' for permission in node.findall('uses-permission')):
|
|
raise SystemExit('store AAB contains direct self-install permission')
|
|
else:
|
|
raise SystemExit('usage: archive.py extract <archive> <fresh-destination> | android-manifest <xml> <version>')
|