docs/Security.md
This document describes the security model for loading and saving external data files in ONNX models. It is intended for maintainers working on the external data code paths.
When an ONNX model references external data files via relative paths, an attacker who controls the model file can attempt:
/etc/shadow), causing ONNX to read or overwrite arbitrary files... segments or absolute paths to escape the model directory.We use a 4-layer defense-in-depth approach. Each layer is applied at every entry point that opens external data files.
std::filesystem::weakly_canonical() resolves the path, then verifies it starts with the canonical base directory.os.path.realpath() resolves all symlinks in the full path, then verifies the result is within the model base directory.This catches .. traversal and symlinks in any path component (not just the final one).
std::filesystem::is_symlink(data_path) rejects the final-component symlink.os.path.islink(path) rejects the final-component symlink.This is a belt-and-suspenders check alongside containment. It provides a clear, specific error message when the final path component is a symlink.
os.O_NOFOLLOW added to os.open() flags where available (hasattr(os, "O_NOFOLLOW")).The C++ checker validates paths but does not open files, so O_NOFOLLOW is not applicable there. In Python, this is the last-resort defense: even if a symlink is created between the check and the open (TOCTOU race), the kernel rejects the open with ELOOP on Linux/macOS.
std::filesystem::hard_link_count(data_path) > 1 rejects files with multiple hardlinks.os.stat(path).st_nlink > 1 rejects files with multiple hardlinks.This prevents an attacker from using a hardlink (which is not a symlink) to point external data at a sensitive file. Note that O_NOFOLLOW does not protect against hardlinks — only this explicit check does.
Not all layers apply at every entry point. The C++ checker validates paths but does not open files, so Layer 3 (O_NOFOLLOW) is Python-only.
| Entry Point | File | Layers |
|---|---|---|
_resolve_external_data_location | onnx/checker.cc | 1, 2, 4 |
load_external_data_for_tensor | onnx/external_data_helper.py | 1, 2, 3, 4 |
save_external_data | onnx/external_data_helper.py | 1, 2, 3, 4 |
ModelContainer._load_large_initializers | onnx/model_container.py | 1, 2, 3, 4 |
The C++ checker runs first for all Python load paths (via c_checker._resolve_external_data_location). The Python checks serve as defense-in-depth.
There is an inherent race window between the security checks (Layers 1-2, 4) and the file open (Layer 3). An attacker with write access to the model directory could:
Mitigation: O_NOFOLLOW (Layer 3) catches late symlink replacement on Linux/macOS at the kernel level. However, O_NOFOLLOW does not protect against hardlink replacement — this TOCTOU gap cannot be fully closed at the application level.
O_NOFOLLOW is not available on Windows (hasattr(os, "O_NOFOLLOW") returns False). The TOCTOU window for symlink attacks is fully open on Windows, relying solely on Layers 1-2.The canonical path containment check uses string comparison. On case-insensitive filesystems (Windows NTFS, macOS HFS+), paths with different casing may incorrectly fail containment. This fails closed (false rejection, not a bypass).
Test coverage is in:
onnx/test/cpp/checker_test.cc — SymLink* tests for symlink detection and containment.onnx/test/test_external_data.py:
TestSaveExternalDataSymlinkProtection — save-side symlink rejection.TestLoadExternalDataSymlinkProtection — load-side symlink rejection, parent-directory symlink, load_external_data_for_model rejection.TestLoadExternalDataHardlinkProtection — load-side hardlink rejection.TestSaveExternalDataAbsolutePathValidation — absolute path rejection.Symlink and hardlink tests are skipped on Windows (os.name == "nt").
This section describes the security model for validating external data attributes in ExternalDataInfo. It covers defenses against attribute injection (CWE-915) and resource exhaustion (CWE-400) via crafted external_data entries in TensorProto.
Advisory: GHSA-538c-55jv-c5g9
An attacker provides a malicious ONNX model with crafted external_data entries in TensorProto. The external_data field is a repeated StringStringEntryProto — a key-value store that accepts arbitrary strings for both key and value.
The attack is triggered during onnx.load() with no explicit checker invocation required. ExternalDataInfo.__init__ processes these key-value pairs to populate object attributes.
Attack vectors:
evil_attr) causes setattr() to create arbitrary attributes on the ExternalDataInfo object. While no current consumer iterates over attributes, injected attributes create latent risk for future code.__class__ or __dict__ corrupts the Python object's internal state, enabling type confusion attacks.offset cause file.seek() to raise OSError. Negative length causes file.read(-1) to read the entire file to EOF, bypassing intended size limits.length to a multi-petabyte value causes unbounded memory allocation when reading external data, even if the actual data file is small.Four Python consumers of ExternalDataInfo exist: load_external_data_for_tensor, set_external_data / write_external_data_tensors, ModelContainer._load_large_initializers, and ReferenceEvaluator (in onnx/reference/reference_evaluator.py). (The C++ checker validates paths but does not use the Python ExternalDataInfo class.)
We use a 3-layer defense-in-depth approach. Each layer addresses a different class of attack and operates at a different point in the processing pipeline.
ExternalDataInfo.__init__ only accepts keys in _ALLOWED_EXTERNAL_DATA_KEYS: location, offset, length, checksum, basepath. Unknown keys are warned via warnings.warn() and ignored — this prevents arbitrary attribute injection.
This also blocks dunder attribute injection (e.g. __class__, __dict__) that could cause object type confusion.
Rationale: While we cannot prevent someone from constructing malicious protobuf directly, rejecting unknown keys at the Python object level is defense-in-depth that limits the attack surface. The whitelist is a frozenset to prevent runtime mutation.
offset and length must be non-negative integers. Non-numeric strings raise ValueError. This catches obviously invalid values early, before any file I/O occurs.
Rationale: Negative offset causes file.seek(-1) to raise OSError; negative length causes file.read(-1) to read the entire file, bypassing intended size limits. Validating at parse time provides a clear error message at the point closest to the malicious input.
In load_external_data_for_tensor() and ModelContainer._load_large_initializers, before reading: offset <= file_size and offset + length <= file_size are verified. A 1KB data file cannot cause a multi-petabyte memory allocation.
Rationale: This is the critical safety net. It prevents memory exhaustion regardless of how the model was constructed — even via direct protobuf APIs that bypass Python-level parsing entirely. Validation happens at the point of actual file I/O, the last opportunity before harm occurs.
| Entry Point | File | Layers |
|---|---|---|
ExternalDataInfo.__init__ | onnx/external_data_helper.py | 1, 2 |
load_external_data_for_tensor | onnx/external_data_helper.py | 1, 2, 3 |
set_external_data | onnx/external_data_helper.py | 1 (whitelist by overwrite) |
ModelContainer._load_large_initializers | onnx/model_container.py | 1, 2, 3 |
Test coverage is in onnx/test/test_external_data.py:
TestExternalDataInfoSecurity:
test_unknown_key_rejected, test_dunder_key_rejected, test_multiple_unknown_keys_all_rejected, test_allowed_keys_constant_is_frozentest_negative_offset_rejected, test_negative_length_rejected, test_non_numeric_offset_raises, test_non_numeric_length_raisestest_valid_external_data_accepted, test_zero_offset_and_length_acceptedTestLoadExternalDataFileSizeValidation:
test_offset_exceeds_file_size_raises, test_length_exceeds_available_data_raises, test_valid_offset_and_length_load_correctly