|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import io |
| 4 | +import lzma |
| 5 | +import os |
| 6 | +import zlib |
| 7 | +from typing import Any, Optional |
| 8 | + |
| 9 | +from ..utils.filetype import read_magic_bytes |
| 10 | +from .base import BaseScanner, IssueSeverity, ScanResult |
| 11 | +from .pickle_scanner import PickleScanner |
| 12 | + |
| 13 | + |
| 14 | +class JoblibScanner(BaseScanner): |
| 15 | + """Scanner for joblib serialized files.""" |
| 16 | + |
| 17 | + name = "joblib" |
| 18 | + description = "Scans joblib files by decompressing and analyzing embedded pickle" |
| 19 | + supported_extensions = [".joblib"] |
| 20 | + |
| 21 | + def __init__(self, config: Optional[dict[str, Any]] = None): |
| 22 | + super().__init__(config) |
| 23 | + self.pickle_scanner = PickleScanner(config) |
| 24 | + # Security limits |
| 25 | + self.max_decompression_ratio = self.config.get("max_decompression_ratio", 100.0) |
| 26 | + self.max_decompressed_size = self.config.get( |
| 27 | + "max_decompressed_size", 100 * 1024 * 1024 |
| 28 | + ) # 100MB |
| 29 | + self.max_file_read_size = self.config.get( |
| 30 | + "max_file_read_size", 100 * 1024 * 1024 |
| 31 | + ) # 100MB |
| 32 | + self.chunk_size = self.config.get("chunk_size", 8192) # 8KB chunks |
| 33 | + |
| 34 | + @classmethod |
| 35 | + def can_handle(cls, path: str) -> bool: |
| 36 | + if not os.path.isfile(path): |
| 37 | + return False |
| 38 | + ext = os.path.splitext(path)[1].lower() |
| 39 | + if ext != ".joblib": |
| 40 | + return False |
| 41 | + return True |
| 42 | + |
| 43 | + def _read_file_safely(self, path: str) -> bytes: |
| 44 | + """Read file in chunks with size validation""" |
| 45 | + data = b"" |
| 46 | + file_size = self.get_file_size(path) |
| 47 | + |
| 48 | + if file_size > self.max_file_read_size: |
| 49 | + raise ValueError( |
| 50 | + f"File too large: {file_size} bytes (max: {self.max_file_read_size})" |
| 51 | + ) |
| 52 | + |
| 53 | + with open(path, "rb") as f: |
| 54 | + while True: |
| 55 | + chunk = f.read(self.chunk_size) |
| 56 | + if not chunk: |
| 57 | + break |
| 58 | + data += chunk |
| 59 | + if len(data) > self.max_file_read_size: |
| 60 | + raise ValueError(f"File read exceeds limit: {len(data)} bytes") |
| 61 | + return data |
| 62 | + |
| 63 | + def _safe_decompress(self, data: bytes) -> bytes: |
| 64 | + """Safely decompress data with bomb protection""" |
| 65 | + compressed_size = len(data) |
| 66 | + |
| 67 | + # Try zlib first |
| 68 | + decompressed = None |
| 69 | + try: |
| 70 | + decompressed = zlib.decompress(data) |
| 71 | + except Exception: |
| 72 | + # Try lzma |
| 73 | + try: |
| 74 | + decompressed = lzma.decompress(data) |
| 75 | + except Exception as e: |
| 76 | + raise ValueError(f"Unable to decompress joblib file: {e}") |
| 77 | + |
| 78 | + # Check decompression ratio for compression bomb detection |
| 79 | + if compressed_size > 0: |
| 80 | + ratio = len(decompressed) / compressed_size |
| 81 | + if ratio > self.max_decompression_ratio: |
| 82 | + raise ValueError( |
| 83 | + f"Suspicious compression ratio: {ratio:.1f}x " |
| 84 | + f"(max: {self.max_decompression_ratio}x) - possible compression bomb" |
| 85 | + ) |
| 86 | + |
| 87 | + # Check absolute decompressed size |
| 88 | + if len(decompressed) > self.max_decompressed_size: |
| 89 | + raise ValueError( |
| 90 | + f"Decompressed size too large: {len(decompressed)} bytes " |
| 91 | + f"(max: {self.max_decompressed_size})" |
| 92 | + ) |
| 93 | + |
| 94 | + return decompressed |
| 95 | + |
| 96 | + def scan(self, path: str) -> ScanResult: |
| 97 | + path_check_result = self._check_path(path) |
| 98 | + if path_check_result: |
| 99 | + return path_check_result |
| 100 | + |
| 101 | + result = self._create_result() |
| 102 | + file_size = self.get_file_size(path) |
| 103 | + result.metadata["file_size"] = file_size |
| 104 | + |
| 105 | + try: |
| 106 | + self.current_file_path = path |
| 107 | + magic = read_magic_bytes(path, 4) |
| 108 | + data = self._read_file_safely(path) |
| 109 | + |
| 110 | + if magic.startswith(b"PK"): |
| 111 | + # Treat as zip archive |
| 112 | + from .zip_scanner import ZipScanner |
| 113 | + |
| 114 | + zip_scanner = ZipScanner(self.config) |
| 115 | + sub_result = zip_scanner.scan(path) |
| 116 | + result.merge(sub_result) |
| 117 | + result.bytes_scanned = sub_result.bytes_scanned |
| 118 | + result.metadata.update(sub_result.metadata) |
| 119 | + result.finish(success=sub_result.success) |
| 120 | + return result |
| 121 | + |
| 122 | + if magic.startswith(b"\x80"): |
| 123 | + file_like = io.BytesIO(data) |
| 124 | + sub_result = self.pickle_scanner._scan_pickle_bytes( |
| 125 | + file_like, len(data) |
| 126 | + ) |
| 127 | + result.merge(sub_result) |
| 128 | + result.bytes_scanned = len(data) |
| 129 | + else: |
| 130 | + # Try safe decompression |
| 131 | + try: |
| 132 | + decompressed = self._safe_decompress(data) |
| 133 | + except ValueError as e: |
| 134 | + result.add_issue( |
| 135 | + str(e), |
| 136 | + severity=IssueSeverity.CRITICAL, |
| 137 | + location=path, |
| 138 | + details={"security_check": "compression_bomb_detection"}, |
| 139 | + ) |
| 140 | + result.finish(success=False) |
| 141 | + return result |
| 142 | + except Exception as e: |
| 143 | + result.add_issue( |
| 144 | + f"Error decompressing joblib file: {e}", |
| 145 | + severity=IssueSeverity.CRITICAL, |
| 146 | + location=path, |
| 147 | + ) |
| 148 | + result.finish(success=False) |
| 149 | + return result |
| 150 | + file_like = io.BytesIO(decompressed) |
| 151 | + sub_result = self.pickle_scanner._scan_pickle_bytes( |
| 152 | + file_like, len(decompressed) |
| 153 | + ) |
| 154 | + result.merge(sub_result) |
| 155 | + result.bytes_scanned = len(decompressed) |
| 156 | + except Exception as e: # pragma: no cover |
| 157 | + result.add_issue( |
| 158 | + f"Error scanning joblib file: {e}", |
| 159 | + severity=IssueSeverity.CRITICAL, |
| 160 | + location=path, |
| 161 | + details={"exception": str(e), "exception_type": type(e).__name__}, |
| 162 | + ) |
| 163 | + result.finish(success=False) |
| 164 | + return result |
| 165 | + |
| 166 | + result.finish(success=True) |
| 167 | + return result |
0 commit comments