diff --git a/stacs/scan/loader/archive.py b/stacs/scan/loader/archive.py index a2937c9..cdd2331 100644 --- a/stacs/scan/loader/archive.py +++ b/stacs/scan/loader/archive.py @@ -77,7 +77,26 @@ def tar_handler(filepath: str, directory: str) -> None: # Attempt to unpack the tarball to the new unpack directory. try: with tarfile.open(filepath, "r") as reader: - reader.extractall(directory) + 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) + + + safe_extract(reader, directory) except (PermissionError, tarfile.TarError) as err: raise InvalidFileException( f"Unable to extract archive {filepath} to {directory}: {err}"