diff --git a/dnppy/convert/extract_archive.py b/dnppy/convert/extract_archive.py index 418d77c..badf611 100644 --- a/dnppy/convert/extract_archive.py +++ b/dnppy/convert/extract_archive.py @@ -29,7 +29,26 @@ def extract_archive(filepaths, delete_originals = False): if filepath.endswith(".tar.gz"): with tarfile.open(filepath, 'r:gz') as tfile: outdir = os.path.join(head, tail.replace(".tar.gz","")) - tfile.extractall(outdir) + def is_within_directory(directory, target): + + abs_directory = os.path.abspath(directory) + abs_target = os.path.abspath(target) + + prefix = os.path.commonprefix([abs_directory, abs_target]) + + return prefix == 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("Attempted Path Traversal in Tar File") + + tar.extractall(path, members, numeric_owner=numeric_owner) + + + safe_extract(tfile, outdir) # gzip only compresses single files elif filepath.endswith(".gz"): @@ -42,7 +61,26 @@ def extract_archive(filepaths, delete_originals = False): elif filepath.endswith(".tar"): with tarfile.open(filepath, 'r') as tfile: outdir = os.path.join(head, tail.replace(".tar","")) - tfile.extractall(outdir) + def is_within_directory(directory, target): + + abs_directory = os.path.abspath(directory) + abs_target = os.path.abspath(target) + + prefix = os.path.commonprefix([abs_directory, abs_target]) + + return prefix == 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("Attempted Path Traversal in Tar File") + + tar.extractall(path, members, numeric_owner=numeric_owner) + + + safe_extract(tfile, outdir) elif filepath.endswith(".zip"): with zipfile.ZipFile(filepath, "r") as zipf: