Skip to content

Commit 2ed2bc5

Browse files
azurelinux-securityaninda-aljslobodzian
authored
[AutoPR- Security] Patch pytorch for CVE-2026-34446, CVE-2026-34445 [HIGH] (#16538)
Co-authored-by: Aninda <v-anipradhan@microsoft.com> Co-authored-by: jslobodzian <joslobo@microsoft.com>
1 parent 409c67f commit 2ed2bc5

4 files changed

Lines changed: 387 additions & 3 deletions

File tree

SPECS/pytorch/CVE-2025-55560.patch

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,14 @@ Approved by: https://github.com/jansel
1313

1414
Modified to apply to Azure Linux
1515
Upstream Patch Reference: https://github.com/pytorch/pytorch/commit/225742838bcbf4656a90010257062188f7fcae82.patch
16+
17+
Note: The original patch authored by Zhiyi Zhang was modified by Microsoft to apply to version 2.2.2 of PyTorch on Azure Linux.
18+
1619
---
1720
test/dynamo/test_compile.py | 13 +++++++++++++
1821
torch/_dynamo/variables/builtin.py | 11 +++++++++++
19-
2 files changed, 24 insertions(+)
22+
torch/_subclasses/meta_utils.py | 17 +++++++++++++++++
23+
3 files changed, 41 insertions(+)
2024

2125
diff --git a/test/dynamo/test_compile.py b/test/dynamo/test_compile.py
2226
index 5b2de2b7..a38c1d3e 100644
@@ -71,6 +75,34 @@ index 2a2e9893..beababef 100644
7175
try:
7276
return obj.var_getattr(tx, name).clone(source=source)
7377
except NotImplementedError:
78+
diff --git a/torch/_subclasses/meta_utils.py b/torch/_subclasses/meta_utils.py
79+
index 8db8f94b..e27a0493 100644
80+
--- a/torch/_subclasses/meta_utils.py
81+
+++ b/torch/_subclasses/meta_utils.py
82+
@@ -79,6 +79,23 @@ def assert_metadata_eq(assert_eq, m1, m2, *, skip_symbolic=False):
83+
return go(m1, m2)
84+
85+
86+
+def is_sparse_coo(t):
87+
+ return isinstance(t, torch.Tensor) and t.layout is torch.sparse_coo
88+
+
89+
+
90+
+def is_sparse_compressed(t):
91+
+ return isinstance(t, torch.Tensor) and t.layout in {
92+
+ torch.sparse_csr,
93+
+ torch.sparse_csc,
94+
+ torch.sparse_bsr,
95+
+ torch.sparse_bsc,
96+
+ }
97+
+
98+
+
99+
+def is_sparse_any(t):
100+
+ return is_sparse_coo(t) or is_sparse_compressed(t)
101+
+
102+
+
103+
# This is a class for converting multiple tensors into meta tensors which
104+
# share the same view/storage structure. The operation model is you allocate
105+
# one of these, and then call it repeatedly on all the tensors you want to
74106
--
75-
2.43.0
107+
2.34.1
76108

SPECS/pytorch/CVE-2026-34445.patch

Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
From a3ac7f97a0dacdbc4df51322541cb4b1d063fe12 Mon Sep 17 00:00:00 2001
2+
From: AllSpark <allspark@microsoft.com>
3+
Date: Thu, 9 Apr 2026 09:13:59 +0000
4+
Subject: [PATCH] Security hardening for external_data: whitelist keys,
5+
parse-time bounds, file-size validation; warnings; export constants
6+
7+
Signed-off-by: Azure Linux Security Servicing Account <azurelinux-security@microsoft.com>
8+
Upstream-reference: AI Backport of https://github.com/onnx/onnx/commit/e30c6935d67cc3eca2fa284e37248e7c0036c46b.patch
9+
---
10+
third_party/onnx/onnx/external_data_helper.py | 102 ++++++++++++++++--
11+
1 file changed, 91 insertions(+), 11 deletions(-)
12+
13+
diff --git a/third_party/onnx/onnx/external_data_helper.py b/third_party/onnx/onnx/external_data_helper.py
14+
index 05c486c..8f7d42f 100644
15+
--- a/third_party/onnx/onnx/external_data_helper.py
16+
+++ b/third_party/onnx/onnx/external_data_helper.py
17+
@@ -5,12 +5,65 @@ import os
18+
import re
19+
import sys
20+
import uuid
21+
+import warnings
22+
from itertools import chain
23+
-from typing import Callable, Iterable, Optional
24+
+from typing import Callable, Iterable, Optional, IO
25+
26+
import onnx.onnx_cpp2py_export.checker as c_checker
27+
from onnx.onnx_pb import AttributeProto, GraphProto, ModelProto, TensorProto
28+
29+
+# Security: 3-layer defense against malicious external_data entries (GHSA-538c-55jv-c5g9)
30+
+#
31+
+# Layer 1 (here) — Attribute whitelist: Only spec-defined keys are accepted.
32+
+# Unknown keys are warned and ignored, preventing arbitrary attribute injection (CWE-915).
33+
+#
34+
+# Layer 2 (ExternalDataInfo.__init__) — Bounds validation: offset and length must be
35+
+# non-negative integers. Catches invalid values at parse time (CWE-400).
36+
+#
37+
+# Layer 3 (load_external_data_for_tensor) — File-size validation: offset and length are
38+
+# checked against actual file size before reading. This is the critical safety net that
39+
+# prevents memory exhaustion regardless of how the model was constructed (CWE-400).
40+
+#
41+
+# 'basepath' is included because set_external_data() writes it to protobuf entries;
42+
+# it must survive save/load round-trips.
43+
+_ALLOWED_EXTERNAL_DATA_KEYS = frozenset({"location", "offset", "length", "checksum", "basepath"})
44+
+_SORTED_ALLOWED_KEYS = sorted(_ALLOWED_EXTERNAL_DATA_KEYS)
45+
+_MAX_UNKNOWN_KEYS_IN_WARNING = 10
46+
+
47+
+
48+
+def _validate_external_data_file_bounds(
49+
+ data_file: IO[bytes],
50+
+ info: ExternalDataInfo,
51+
+ tensor_name: str,
52+
+) -> bytes:
53+
+ """Validate offset/length against actual file size and read data.
54+
+
55+
+ Layer 3 defense-in-depth (CWE-400): prevents memory exhaustion even if the
56+
+ model was crafted via direct protobuf APIs that bypass Python parsing.
57+
+
58+
+ Returns the raw bytes read from the file.
59+
+ """
60+
+ file_size = os.fstat(data_file.fileno()).st_size
61+
+
62+
+ if info.offset is not None:
63+
+ if info.offset > file_size:
64+
+ raise ValueError(
65+
+ f"External data offset ({info.offset}) exceeds file size ({file_size}) for tensor {tensor_name!r}"
66+
+ )
67+
+ data_file.seek(info.offset)
68+
+
69+
+ if info.length is not None:
70+
+ read_start = info.offset if info.offset is not None else 0
71+
+ available = file_size - read_start
72+
+ if info.length > available:
73+
+ raise ValueError(
74+
+ f"External data length ({info.length}) exceeds available data ({available} bytes from offset {read_start}) for tensor {tensor_name!r}"
75+
+ )
76+
+ return data_file.read(info.length)
77+
+ return data_file.read()
78+
+
79+
+_MAX_KEY_DISPLAY_LENGTH = 100
80+
+
81+
82+
class ExternalDataInfo:
83+
def __init__(self, tensor: TensorProto) -> None:
84+
@@ -20,14 +73,45 @@ class ExternalDataInfo:
85+
self.checksum = None
86+
self.basepath = ""
87+
88+
+ unknown_keys: set[str] = set()
89+
+ unknown_key_count = 0
90+
for entry in tensor.external_data:
91+
- setattr(self, entry.key, entry.value)
92+
+ # Layer 1: reject unknown keys (CWE-915 defense-in-depth)
93+
+ if entry.key in _ALLOWED_EXTERNAL_DATA_KEYS:
94+
+ setattr(self, entry.key, entry.value)
95+
+ else:
96+
+ unknown_key_count += 1
97+
+ if len(unknown_keys) < _MAX_UNKNOWN_KEYS_IN_WARNING:
98+
+ truncated = entry.key[:_MAX_KEY_DISPLAY_LENGTH]
99+
+ if len(entry.key) > _MAX_KEY_DISPLAY_LENGTH:
100+
+ truncated += "..."
101+
+ unknown_keys.add(truncated)
102+
+
103+
+ if unknown_keys:
104+
+ shown = sorted(unknown_keys)
105+
+ extra = unknown_key_count - len(shown)
106+
+ key_list = repr(shown)
107+
+ if extra > 0:
108+
+ key_list += f" and {extra} more"
109+
+ warnings.warn(
110+
+ f"Ignoring unknown external data key(s) {key_list} for tensor {tensor.name!r}. "
111+
+ f"Allowed keys: {_SORTED_ALLOWED_KEYS}",
112+
+ stacklevel=2,
113+
+ )
114+
115+
- if self.offset:
116+
+ if self.offset is not None:
117+
self.offset = int(self.offset)
118+
+ if self.offset < 0:
119+
+ raise ValueError(
120+
+ f"External data offset must be non-negative, got {self.offset} for tensor {tensor.name!r}"
121+
+ )
122+
123+
- if self.length:
124+
+ if self.length is not None:
125+
self.length = int(self.length)
126+
+ if self.length < 0:
127+
+ raise ValueError(
128+
+ f"External data length must be non-negative, got {self.length} for tensor {tensor.name!r}"
129+
+ )
130+
131+
132+
def load_external_data_for_tensor(tensor: TensorProto, base_dir: str) -> None:
133+
@@ -44,13 +128,9 @@ def load_external_data_for_tensor(tensor: TensorProto, base_dir: str) -> None:
134+
base_dir, info.location, tensor.name
135+
)
136+
with open(external_data_file_path, "rb") as data_file:
137+
- if info.offset:
138+
- data_file.seek(info.offset)
139+
-
140+
- if info.length:
141+
- tensor.raw_data = data_file.read(info.length)
142+
- else:
143+
- tensor.raw_data = data_file.read()
144+
+ tensor.raw_data = _validate_external_data_file_bounds(
145+
+ data_file, info, tensor.name
146+
+ )
147+
148+
149+
def load_external_data_for_model(model: ModelProto, base_dir: str) -> None:
150+
--
151+
2.45.4
152+

SPECS/pytorch/CVE-2026-34446.patch

Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
From 3667d980becce3b499b5e2fee4a3d94694fb7d3a Mon Sep 17 00:00:00 2001
2+
From: AllSpark <allspark@microsoft.com>
3+
Date: Thu, 9 Apr 2026 09:28:45 +0000
4+
Subject: [PATCH] Backport security improvements for ONNX external data
5+
handling: canonical containment, symlink rejection, O_NOFOLLOW usage, and
6+
hardlink checks in C++ and Python paths; update tests accordingly.
7+
8+
Signed-off-by: Azure Linux Security Servicing Account <azurelinux-security@microsoft.com>
9+
Upstream-reference: AI Backport of https://github.com/onnx/onnx/commit/4755f8053928dce18a61db8fec71b69c74f786cb.patch
10+
Note: The original patch authored by AllSpark was backported by AI and corrected by Aninda <v-anipradhan@microsoft.com> to apply to version 2.2.2 of PyTorch on Azure Linux.
11+
12+
---
13+
third_party/onnx/onnx/checker.cc | 41 ++++++++++
14+
third_party/onnx/onnx/external_data_helper.py | 81 ++++++++++++++++++-
15+
2 files changed, 121 insertions(+), 1 deletion(-)
16+
17+
diff --git a/third_party/onnx/onnx/checker.cc b/third_party/onnx/onnx/checker.cc
18+
index 66716e97..be1f06a6 100644
19+
--- a/third_party/onnx/onnx/checker.cc
20+
+++ b/third_party/onnx/onnx/checker.cc
21+
@@ -26,6 +26,7 @@
22+
23+
#else // POSIX
24+
#include <sys/stat.h>
25+
+#include <filesystem>
26+
#endif
27+
28+
namespace ONNX_NAMESPACE {
29+
@@ -1033,7 +1034,47 @@ std::string resolve_external_data_location(
30+
location,
31+
"' points outside the directory");
32+
}
33+
+ // Verify the resolved path stays within the base directory to prevent
34+
+ // path traversal via symlinks in parent directory components.
35+
+ // is_symlink() only checks the final component; a path like
36+
+ // "symlink_subdir/real_file.data" would bypass it.
37+
std::string data_path = path_join(base_dir, relative_path);
38+
+ if (!data_path.empty() && data_path[0] != '#') {
39+
+ std::error_code ec;
40+
+ auto canonical_base = std::filesystem::weakly_canonical(std::filesystem::path(base_dir), ec);
41+
+ if (ec) {
42+
+ fail_check(
43+
+ "Data of TensorProto ( tensor name: ",
44+
+ tensor_name,
45+
+ ") references external data at ",
46+
+ location,
47+
+ ", but the model directory path could not be resolved.");
48+
+ }
49+
+ auto canonical_data = std::filesystem::weakly_canonical(std::filesystem::path(data_path), ec);
50+
+ if (ec) {
51+
+ fail_check(
52+
+ "Data of TensorProto ( tensor name: ",
53+
+ tensor_name,
54+
+ ") references external data at ",
55+
+ location,
56+
+ ", but the data path could not be resolved.");
57+
+ }
58+
+ auto canonical_base_native = canonical_base.native();
59+
+ auto canonical_data_native = canonical_data.native();
60+
+ if (!canonical_base_native.empty() && canonical_base_native.back() != std::filesystem::path::preferred_separator) {
61+
+ canonical_base_native += std::filesystem::path::preferred_separator;
62+
+ }
63+
+ if (canonical_data_native.find(canonical_base_native) != 0) {
64+
+ fail_check(
65+
+ "Data of TensorProto ( tensor name: ",
66+
+ tensor_name,
67+
+ ") at ",
68+
+ location,
69+
+ " resolves to a location outside the model directory, "
70+
+ "indicating a potential path traversal attack via symbolic links in directory components.");
71+
+ }
72+
+ }
73+
+
74+
// use stat64 to check whether the file exists
75+
#if defined(__APPLE__) || defined(__wasm__) || !defined(__GLIBC__)
76+
struct stat buffer; // APPLE, wasm and non-glic stdlibs do not have stat64
77+
diff --git a/third_party/onnx/onnx/external_data_helper.py b/third_party/onnx/onnx/external_data_helper.py
78+
index 8f7d42ff..2b5ea70a 100644
79+
--- a/third_party/onnx/onnx/external_data_helper.py
80+
+++ b/third_party/onnx/onnx/external_data_helper.py
81+
@@ -10,6 +10,7 @@ from itertools import chain
82+
from typing import Callable, Iterable, Optional, IO
83+
84+
import onnx.onnx_cpp2py_export.checker as c_checker
85+
+import onnx.checker as onnx_checker
86+
from onnx.onnx_pb import AttributeProto, GraphProto, ModelProto, TensorProto
87+
88+
# Security: 3-layer defense against malicious external_data entries (GHSA-538c-55jv-c5g9)
89+
@@ -123,6 +124,73 @@ def load_external_data_for_tensor(tensor: TensorProto, base_dir: str) -> None:
90+
tensor: a TensorProto object.
91+
base_dir: directory that contains the external data.
92+
"""
93+
+ info = ExternalDataInfo(tensor)
94+
+ external_data_file_path = c_checker._resolve_external_data_location( # type: ignore[attr-defined]
95+
+ base_dir, info.location, tensor.name
96+
+ )
97+
+ # Security checks (symlink, containment, hardlink) already performed
98+
+ # by C++ _resolve_external_data_location() above.
99+
+ # Use O_NOFOLLOW where available as defense-in-depth for symlink protection
100+
+ open_flags = os.O_RDONLY
101+
+ if hasattr(os, "O_NOFOLLOW"):
102+
+ open_flags |= os.O_NOFOLLOW
103+
+ fd = os.open(external_data_file_path, open_flags)
104+
+ with os.fdopen(fd, "rb") as data_file:
105+
+ if info.offset:
106+
+ data_file.seek(info.offset)
107+
+
108+
+ if info.length:
109+
+ tensor.raw_data = data_file.read(info.length)
110+
+ else:
111+
+ tensor.raw_data = data_file.read()
112+
+
113+
+
114+
+def _validate_external_data_path(
115+
+ base_dir: str,
116+
+ data_path: str,
117+
+ tensor_name: str,
118+
+ *,
119+
+ check_exists: bool = True,
120+
+) -> str:
121+
+ """Validate that an external data path is safe to open.
122+
+
123+
+ Performs three security checks:
124+
+ 1. Canonical path containment — resolved path must stay within base_dir.
125+
+ 2. Symlink rejection — final-component symlinks are not allowed.
126+
+ 3. Hardlink count — files with multiple hard links are rejected.
127+
+
128+
+ Args:
129+
+ base_dir: The model base directory that data_path must be contained in.
130+
+ data_path: The external data file path to validate.
131+
+ tensor_name: Tensor name for error messages.
132+
+ check_exists: If True (default), check hardlink count. Set to False
133+
+ for save-side paths where the file may not exist yet.
134+
+
135+
+ Returns:
136+
+ The validated data_path (unchanged).
137+
+
138+
+ Raises:
139+
+ onnx.checker.ValidationError: If any security check fails.
140+
+ """
141+
+ real_base = os.path.realpath(base_dir)
142+
+ real_path = os.path.realpath(data_path)
143+
+ if not real_path.startswith(real_base + os.sep) and real_path != real_base:
144+
+ raise onnx_checker.ValidationError(
145+
+ f"Tensor {tensor_name!r} external data path resolves to "
146+
+ f"{real_path!r} which is outside the model directory {real_base!r}."
147+
+ )
148+
+ if os.path.islink(data_path):
149+
+ raise onnx_checker.ValidationError(
150+
+ f"Tensor {tensor_name!r} external data path {data_path!r} "
151+
+ f"is a symbolic link, which is not allowed for security reasons."
152+
+ )
153+
+ if check_exists and os.path.exists(data_path) and os.stat(data_path).st_nlink > 1:
154+
+ raise onnx_checker.ValidationError(
155+
+ f"Tensor {tensor_name!r} external data path {data_path!r} "
156+
+ f"has multiple hard links, which is not allowed for security reasons."
157+
+ )
158+
+ return data_path
159+
+
160+
info = ExternalDataInfo(tensor)
161+
external_data_file_path = c_checker._resolve_external_data_location( # type: ignore[attr-defined]
162+
base_dir, info.location, tensor.name
163+
@@ -261,6 +329,12 @@ def save_external_data(tensor: TensorProto, base_path: str) -> None:
164+
info = ExternalDataInfo(tensor)
165+
external_data_file_path = os.path.join(base_path, info.location)
166+
167+
+ # C++ _resolve_external_data_location() cannot be used on save path
168+
+ # (file may not exist yet), so Python performs its own security validation.
169+
+ _validate_external_data_path(
170+
+ base_path, external_data_file_path, tensor.name, check_exists=True
171+
+ )
172+
+
173+
# Retrieve the tensor's data from raw_data or load external file
174+
if not tensor.HasField("raw_data"):
175+
raise ValueError("raw_data field doesn't exist.")
176+
@@ -271,7 +345,12 @@ def save_external_data(tensor: TensorProto, base_path: str) -> None:
177+
pass
178+
179+
# Open file for reading and writing at random locations ('r+b')
180+
- with open(external_data_file_path, "r+b") as data_file:
181+
+ # Use O_NOFOLLOW for symlink protection when opening
182+
+ open_flags = os.O_RDWR
183+
+ if hasattr(os, "O_NOFOLLOW"):
184+
+ open_flags |= os.O_NOFOLLOW
185+
+ fd = os.open(external_data_file_path, open_flags)
186+
+ with os.fdopen(fd, "r+b") as data_file:
187+
data_file.seek(0, 2)
188+
if info.offset is not None:
189+
# Pad file to required offset if needed
190+
--
191+
2.34.1
192+

0 commit comments

Comments
 (0)