Skip to content

Commit 2572497

Browse files
Adding tarfile member sanitization to extractall() (#31)
1 parent 87e36d0 commit 2572497

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

napari_cellseg3d/model_workers.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,26 @@ def show_progress(count, block_size, total_size):
140140
url, reporthook=show_progress
141141
)
142142
with tarfile.open(filename, mode="r:gz") as tar:
143-
tar.extractall(pretrained_folder_path)
143+
def is_within_directory(directory, target):
144+
145+
abs_directory = os.path.abspath(directory)
146+
abs_target = os.path.abspath(target)
147+
148+
prefix = os.path.commonprefix([abs_directory, abs_target])
149+
150+
return prefix == abs_directory
151+
152+
def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
153+
154+
for member in tar.getmembers():
155+
member_path = os.path.join(path, member.name)
156+
if not is_within_directory(path, member_path):
157+
raise Exception("Attempted Path Traversal in Tar File")
158+
159+
tar.extractall(path, members, numeric_owner=numeric_owner)
160+
161+
162+
safe_extract(tar, pretrained_folder_path)
144163
else:
145164
raise ValueError(
146165
f"Unknown model: {model_name}. Should be one of {', '.join(neturls)}"

0 commit comments

Comments
 (0)