diff --git a/lava_dispatcher/actions/deploy/testdef.py b/lava_dispatcher/actions/deploy/testdef.py index b783dbcdc..1a696e7b8 100644 --- a/lava_dispatcher/actions/deploy/testdef.py +++ b/lava_dispatcher/actions/deploy/testdef.py @@ -424,7 +424,26 @@ def run(self, connection, max_end_time): write_tar.write(decoded_out.getvalue()) with tarfile.open(temp_tar) as tar: - tar.extractall(path=runner_path) + 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(tar, path=runner_path) except OSError as exc: raise InfrastructureError( "Unable to extract the tar archive: %s" % str(exc) diff --git a/lava_dispatcher/utils/compression.py b/lava_dispatcher/utils/compression.py index 138eb45f6..2d3246735 100644 --- a/lava_dispatcher/utils/compression.py +++ b/lava_dispatcher/utils/compression.py @@ -92,7 +92,26 @@ def decompress_file(infile, compression): def untar_file(infile, outdir): try: with tarfile.open(infile, encoding="utf-8") as tar: - tar.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(tar, outdir) except tarfile.TarError as exc: raise JobError("Unable to unpack %s: %s" % (infile, str(exc))) except OSError as exc: