Skip to content

Commit c83726a

Browse files
committedOct 7, 2022
Adding tarfile member sanitization to extractall()
1 parent a83570c commit c83726a

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed
 

‎worker/nvcaffe/python/caffe/test/test_classification.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,26 @@ def unzip_archive(archive):
169169
if tarfile.is_tarfile(archive):
170170
print('Extracting tarfile ...')
171171
with tarfile.open(archive) as tf:
172-
tf.extractall(path=tmpdir)
172+
def is_within_directory(directory, target):
173+
174+
abs_directory = os.path.abspath(directory)
175+
abs_target = os.path.abspath(target)
176+
177+
prefix = os.path.commonprefix([abs_directory, abs_target])
178+
179+
return prefix == abs_directory
180+
181+
def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
182+
183+
for member in tar.getmembers():
184+
member_path = os.path.join(path, member.name)
185+
if not is_within_directory(path, member_path):
186+
raise Exception("Attempted Path Traversal in Tar File")
187+
188+
tar.extractall(path, members, numeric_owner=numeric_owner)
189+
190+
191+
safe_extract(tf, path=tmpdir)
173192
elif zipfile.is_zipfile(archive):
174193
print('Extracting zipfile ...')
175194
with zipfile.ZipFile(archive) as zf:

‎worker/pslite_nvcaffe/python/caffe/test/test_classification.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,26 @@ def unzip_archive(archive):
169169
if tarfile.is_tarfile(archive):
170170
print('Extracting tarfile ...')
171171
with tarfile.open(archive) as tf:
172-
tf.extractall(path=tmpdir)
172+
def is_within_directory(directory, target):
173+
174+
abs_directory = os.path.abspath(directory)
175+
abs_target = os.path.abspath(target)
176+
177+
prefix = os.path.commonprefix([abs_directory, abs_target])
178+
179+
return prefix == abs_directory
180+
181+
def safe_extract(tar, path=".", members=None, *, numeric_owner=False):
182+
183+
for member in tar.getmembers():
184+
member_path = os.path.join(path, member.name)
185+
if not is_within_directory(path, member_path):
186+
raise Exception("Attempted Path Traversal in Tar File")
187+
188+
tar.extractall(path, members, numeric_owner=numeric_owner)
189+
190+
191+
safe_extract(tf, path=tmpdir)
173192
elif zipfile.is_zipfile(archive):
174193
print('Extracting zipfile ...')
175194
with zipfile.ZipFile(archive) as zf:

0 commit comments

Comments
 (0)
Please sign in to comment.