임의 파일 쓰기 아카이브 추출을 통한 공격 (Tar Slip)

Arbitrary File Write via Archive Extraction (Tar Slip)

설명

tar 아카이브는 신뢰할 수 있는 부모 아래의 새 비공개 디렉터리에 추출하세요. 추출 정책이 경로와 링크를 제한하지 않으면 그 밖의 파일을 덮어쓸 수 있습니다.

잠재적 영향

서비스 계정이 쓸 수 있는 파일이 손상될 수 있습니다. 다른 프로세스가 변경된 파일을 사용하면 서비스 중단, 정보 유출 또는 권한 상승으로 이어질 수 있습니다.

해결 방법

  • 추출 필터가 있는 Python에서는 extractall(..., filter="data")를 명시해 대상 밖의 경로와 링크, 특수 파일, 과도한 권한을 제한하세요. Python 3.14부터 기본 필터는 data입니다. 필터를 생략하면 실행 환경의 기본값을 따릅니다.
  • 필터가 없는 환경에서는 일반 파일과 디렉터리만 허용하고 심볼릭 링크·하드 링크를 거부하세요. 각 대상의 실제 경로를 확인한 뒤 새 파일을 만드세요.
  • 실제 압축 해제 바이트 수, 항목 수와 처리 시간은 별도로 제한하세요.

예시

변경 전

python
# Tar extraction using the runtime default filter
import tarfile

def unsafe_extract(tar_file_path, extract_path):
    with tarfile.open(tar_file_path) as tar:
        tar.extractall(path=extract_path)

변경 후

python
# Safe tar extraction
import tarfile
import os
import shutil
from pathlib import Path

def safe_extract(tar_file_path, extract_path):
    destination = Path(extract_path)
    # 기존 파일이나 링크가 없는 새 전용 디렉터리에서만 추출
    destination.mkdir(mode=0o700, exist_ok=False)
    destination = destination.resolve()

    with tarfile.open(tar_file_path) as tar:
        if hasattr(tarfile, "data_filter"):
            # 추출 필터를 지원하는 런타임의 제한적 데이터 추출 정책
            tar.extractall(path=destination, filter="data")
            return

        # 레거시 fallback: 링크와 특수 파일을 모두 거부하고 경계를 검증
        for member in tar.getmembers():
            if member.issym() or member.islnk():
                raise ValueError("Tar links are not allowed")
            if not (member.isfile() or member.isdir()):
                raise ValueError("Unsupported tar entry type")

            target = (destination / member.name).resolve()
            try:
                target.relative_to(destination)
            except ValueError as error:
                raise ValueError("Tar entry escapes extraction directory") from error

            if member.isdir():
                target.mkdir(parents=True, exist_ok=True, mode=0o700)
                continue

            target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
            source = tar.extractfile(member)
            if source is None:
                raise ValueError("Tar entry has no file data")
            fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
            with source, os.fdopen(fd, "wb") as output:
                shutil.copyfileobj(source, output)

이 함수는 tarfile.data_filter 지원 여부로 처리 방법을 고릅니다. 이전 버전용 분기에서는 대상이 추출 디렉터리 안인지 확인하고 os.O_EXCL로 기존 파일을 보호합니다.

참조