Skip to content

[Security] tarfile.extractall without member validation in src/crate/testing/layer.py #794

Description

@sudabg

Severity: HIGH (Bandit B202)
File: src/crate/testing/layer.py

Vulnerability

tarfile.extractall() without member validation allows path traversal (zip slip). A malicious archive can write files outside the target directory.

Fix

import os

SAFE_ID = __import__("re").compile(r"^[a-zA-Z0-9_.-]+$")

def _is_within_directory(directory, target):
    abs_directory = os.path.realpath(directory)
    abs_target = os.path.realpath(target)
    return abs_target.startswith(abs_directory + os.sep) or abs_target == 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(f"Path traversal in tar: {member.name}")
    tar.extractall(path, members, numeric_owner=numeric_owner)

References

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions