diff --git a/dpgen/auto_test/lib/RemoteJob.py b/dpgen/auto_test/lib/RemoteJob.py index d976b4253..e66df1351 100644 --- a/dpgen/auto_test/lib/RemoteJob.py +++ b/dpgen/auto_test/lib/RemoteJob.py @@ -191,7 +191,26 @@ def _get_files(self, cwd = os.getcwd() os.chdir(self.local_root) with tarfile.open(of, "r:gz") as tar: - tar.extractall() + 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) os.chdir(cwd) # cleanup os.remove(to_f) diff --git a/dpgen/dispatcher/SSHContext.py b/dpgen/dispatcher/SSHContext.py index aca7d8368..7f614f31b 100644 --- a/dpgen/dispatcher/SSHContext.py +++ b/dpgen/dispatcher/SSHContext.py @@ -333,7 +333,26 @@ def _get_files(self, cwd = os.getcwd() os.chdir(self.local_root) with tarfile.open(of, "r:gz") as tar: - tar.extractall() + 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) os.chdir(cwd) # cleanup os.remove(to_f) diff --git a/dpgen/remote/RemoteJob.py b/dpgen/remote/RemoteJob.py index 4cdc76e9c..992fb82f4 100644 --- a/dpgen/remote/RemoteJob.py +++ b/dpgen/remote/RemoteJob.py @@ -288,7 +288,26 @@ def _get_files(self, cwd = os.getcwd() os.chdir(self.local_root) with tarfile.open(of, "r:gz") as tar: - tar.extractall() + 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) os.chdir(cwd) # cleanup os.remove(to_f)