Skip to content

Commit

Permalink
Adding tarfile member sanitization to extractall()
Browse files Browse the repository at this point in the history
  • Loading branch information
TrellixVulnTeam committed Oct 30, 2022
1 parent 64e3677 commit 8a64461
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
21 changes: 20 additions & 1 deletion zipdist/zip.py
Expand Up @@ -353,7 +353,26 @@ def _extract_tarfile(self, dest_tar = None, verbose = True):
"""
with tarfile.open(dest_tar , "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)
if verbose:
contents = tar.getnames()
sys.stdout.write(f"\tContents of {dest_tar} :\n\t\t")
Expand Down
21 changes: 20 additions & 1 deletion zipdist/zip2.py
Expand Up @@ -374,7 +374,26 @@ def _extract_tarfile(self, dest_tar = None, verbose = True):
"""
with tarfile.open(dest_tar , "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)
if verbose:
contents = tar.getnames()
sys.stdout.write(f"\tContents of {dest_tar} :\n\t\t")
Expand Down

0 comments on commit 8a64461

Please sign in to comment.