diff --git a/observations/util.py b/observations/util.py index 9f088b1..c6d1b20 100644 --- a/observations/util.py +++ b/observations/util.py @@ -603,7 +603,26 @@ def maybe_download_and_extract(path, url, extract=True, if extract: if tarfile.is_tarfile(filepath): with tarfile.open(filepath) as f: - f.extractall(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(f, path) elif filename.endswith('.gz'): with gzip.open(filepath, 'rb') as f: s = f.read()