-
Notifications
You must be signed in to change notification settings - Fork 189
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add untar function with guard against path traversal attack and a str…
…ip option
- Loading branch information
Showing
3 changed files
with
25 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
import tarfile | ||
from os.path import exists | ||
from shutil import rmtree | ||
|
||
|
||
def untar(archive_path: str, output_path: str, overwrite=True, strip=0) -> None: | ||
if overwrite and exists(output_path): | ||
rmtree(output_path) | ||
|
||
with tarfile.open(archive_path, mode="r") as archive: | ||
for member in archive.getmembers(): | ||
if member.path.startswith("/") or member.path.startswith("../"): | ||
raise Exception("Attempted Path Traversal in tar file") | ||
|
||
# Change member paths to strip N levels, like untar --strip-components=N | ||
member.path = member.path.split('/', strip)[-1] | ||
|
||
archive.extractall(output_path) |