diff --git a/target/cohorte-home/bin/scripts/cohorte_update.py b/target/cohorte-home/bin/scripts/cohorte_update.py index 0d71da9..c3a6cdf 100644 --- a/target/cohorte-home/bin/scripts/cohorte_update.py +++ b/target/cohorte-home/bin/scripts/cohorte_update.py @@ -358,7 +358,26 @@ def install_new_dist(new_dist_file, update): else: new_dist = os.path.join(tmp_dir, new_dist_file) with tarfile.open(new_dist, "r:gz") as t: - t.extractall(cohorte_dir) + 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(t, cohorte_dir) for x in os.listdir(cohorte_dir): if x.startswith('cohorte'): for f in os.listdir(os.path.join(cohorte_dir, x)): @@ -378,7 +397,26 @@ def install_archived_dist(): else: new_dist = os.path.join(tmp_dir, "archived_distribution.tar.gz") with tarfile.open(new_dist, "r:gz") as t: - t.extractall(cohorte_dir) + 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(t, cohorte_dir) for x in os.listdir(cohorte_dir): if x.startswith('cohorte'): for f in os.listdir(os.path.join(cohorte_dir, x)):