Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[TF FE] Fix signed integer overflow in BundleEntryProto bounds checks (#34370)

Evgeny Kotov834ab7be7078
diff --git a/src/frontends/tensorflow/src/checkpoint_utils.hpp b/src/frontends/tensorflow/src/checkpoint_utils.hpp
index 29e8ea1f680..bd7dddec45b 100644
--- a/src/frontends/tensorflow/src/checkpoint_utils.hpp
+++ b/src/frontends/tensorflow/src/checkpoint_utils.hpp
@@ -96,6 +96,30 @@ bool get_varint64(std::string& input, uint64_t* value);
std::string encode_tensor_name_slice(const std::string& name,
const std::vector<int64_t>& starts,
const std::vector<int64_t> lengths);
+/// \brief Validates that a BundleEntryProto's offset and size are non-negative
+/// and that offset + size fits within data_size, using overflow-safe arithmetic.
+/// \param offset The entry offset (int64 from protobuf)
+/// \param size The entry size (int64 from protobuf)
+/// \param data_size The total size of the shard data (mmap or file)
+/// \param context_msg Error context prefix for diagnostics
+inline void validate_bundle_entry_bounds(int64_t offset, int64_t size, uint64_t data_size, const char* context_msg) {
+ FRONT_END_GENERAL_CHECK(offset >= 0, context_msg, ": entry offset is negative (", offset, ")");
+ FRONT_END_GENERAL_CHECK(size >= 0, context_msg, ": entry size is negative (", size, ")");
+ auto u_offset = static_cast<uint64_t>(offset);
+ auto u_size = static_cast<uint64_t>(size);
+ // Overflow-safe: instead of checking u_offset + u_size <= data_size (which can overflow),
+ // check u_size <= data_size && u_offset <= data_size - u_size
+ FRONT_END_GENERAL_CHECK(u_size <= data_size && u_offset <= data_size - u_size,
+ context_msg,
+ ": entry bounds [offset=",
+ offset,
+ ", size=",
+ size,
+ "] exceed data size (",
+ data_size,
+ " bytes)");
+}
+
} // namespace tensorflow
} // namespace frontend
} // namespace ov
\ No newline at end of file
diff --git a/src/frontends/tensorflow/src/op/var_handle.cpp b/src/frontends/tensorflow/src/op/var_handle.cpp
index 05f241682ee..cbcb7fe4992 100644
--- a/src/frontends/tensorflow/src/op/var_handle.cpp
+++ b/src/frontends/tensorflow/src/op/var_handle.cpp
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
//
+#include "checkpoint_utils.hpp"
#include "common_op_table.hpp"
#include "graph_iterator_saved_model.hpp"
#include "helper_ops/unsupported_constant.hpp"
@@ -41,10 +42,10 @@ static std::shared_ptr<ov::Node> read_variable(std::shared_ptr<VariablesIndex> v
if (!mapped_memory.get()) {
TENSORFLOW_OP_VALIDATION(node, var_index, "[TensorFlow Frontend] Internal error: Cannot get shard file.");
}
- TENSORFLOW_OP_VALIDATION(
- node,
- static_cast<int64_t>(mapped_memory->size()) >= entry.offset() + entry.size(),
- "[TensorFlow Frontend] Internal error: Variable entry size is out of bounds of mapped memory size.");
+ validate_bundle_entry_bounds(entry.offset(),
+ entry.size(),
+ mapped_memory->size(),
+ "[TensorFlow Frontend] Variable data (mmap)");
return std::make_shared<v0::Constant>(
ov_type,
shape,
@@ -58,6 +59,19 @@ static std::shared_ptr<ov::Node> read_variable(std::shared_ptr<VariablesIndex> v
if (!fs.get()) {
TENSORFLOW_OP_VALIDATION(node, var_index, "[TensorFlow Frontend] Internal error: Cannot get shard file.");
}
+ fs->seekg(0, std::ios::end);
+ TENSORFLOW_OP_VALIDATION(node,
+ fs->good(),
+ "[TensorFlow Frontend] Variable data (stream): failed to seek to end of data file");
+ auto pos = fs->tellg();
+ TENSORFLOW_OP_VALIDATION(node,
+ pos != static_cast<std::streampos>(-1),
+ "[TensorFlow Frontend] Variable data (stream): failed to determine data file size");
+ auto file_size = static_cast<uint64_t>(pos);
+ validate_bundle_entry_bounds(entry.offset(),
+ entry.size(),
+ file_size,
+ "[TensorFlow Frontend] Variable data (stream)");
fs->seekg(entry.offset(), std::ios::beg);
fs->read(reinterpret_cast<char*>(var_data.data()), entry.size());
return std::make_shared<v0::Constant>(ov_type, shape, var_data);
diff --git a/src/frontends/tensorflow/src/variables_index.cpp b/src/frontends/tensorflow/src/variables_index.cpp
index b75e414750f..d269b91ef90 100644
--- a/src/frontends/tensorflow/src/variables_index.cpp
+++ b/src/frontends/tensorflow/src/variables_index.cpp
@@ -34,8 +34,9 @@ void VariablesIndex::read_variables_index_block(std::ifstream& fs,
data.resize(block_size + BLOCK_TRAILER_SIZE);
FRONT_END_GENERAL_CHECK(index.m_offset <= m_variables_index_size,
"Block offset is bigger than variables index size");
- FRONT_END_GENERAL_CHECK(index.m_offset + data.size() <= m_variables_index_size,
- "Block size is bigger than variables index size");
+ FRONT_END_GENERAL_CHECK(
+ data.size() <= m_variables_index_size && index.m_offset <= m_variables_index_size - data.size(),
+ "Block size is bigger than variables index size");
fs.seekg(index.m_offset, std::ios::beg);
fs.read(data.data(), data.size());
#ifndef ENABLE_SNAPPY_COMPRESSION
@@ -156,13 +157,33 @@ void VariablesIndex::read_checkpointable_object_graph() {
auto shard = m_data_files.find(entry.shard_id());
FRONT_END_GENERAL_CHECK(shard != m_data_files.end(), "CMO: data files isn't found");
- std::vector<char> data(entry.size());
- ::tensorflow::TrackableObjectGraph tog;
-
// TODO: have to understand this offset
// It looks like reinterpret_cast artifact
// https://github.com/tensorflow/tensorflow/blob/d90f1947ebcf510b23c238f43c2191e5b3817cb3/tensorflow/cc/experimental/libexport/load.cc#L70
int chg = 6;
+
+ // Validate entry.size() >= chg to avoid underflow in (entry.size() - chg)
+ FRONT_END_GENERAL_CHECK(entry.size() >= chg, "CMO: Bundle entry size is too small");
+
+ // Validate offset and size bounds before any pointer arithmetic or memory allocation
+ if (m_mmap_enabled) {
+ validate_bundle_entry_bounds(entry.offset(),
+ entry.size(),
+ static_cast<uint64_t>(shard->second.mmap->size()),
+ "CMO (mmap)");
+ } else {
+ shard->second.stream->seekg(0, std::ios::end);
+ FRONT_END_GENERAL_CHECK(*shard->second.stream, "CMO (stream): failed to seek to end of data file");
+ auto pos = shard->second.stream->tellg();
+ FRONT_END_GENERAL_CHECK(pos != static_cast<std::streampos>(-1),
+ "CMO (stream): failed to determine data file size");
+ auto file_size = static_cast<uint64_t>(pos);
+ validate_bundle_entry_bounds(entry.offset(), entry.size(), file_size, "CMO (stream)");
+ }
+
+ std::vector<char> data(entry.size());
+ ::tensorflow::TrackableObjectGraph tog;
+
if (m_mmap_enabled) {
auto srcPtr = static_cast<char*>(shard->second.mmap->data() + entry.offset() + chg);
std::copy(srcPtr, srcPtr + entry.size() - chg, data.data());
diff --git a/src/frontends/tensorflow/tests/convert_saved_model.cpp b/src/frontends/tensorflow/tests/convert_saved_model.cpp
index e70b897b2d8..efa5b2891ef 100644
--- a/src/frontends/tensorflow/tests/convert_saved_model.cpp
+++ b/src/frontends/tensorflow/tests/convert_saved_model.cpp
@@ -5,6 +5,7 @@
#include "common_test_utils/test_common.hpp"
#include "conversion_with_reference.hpp"
#include "gtest/gtest.h"
+#include "openvino/frontend/exception.hpp"
#include "openvino/op/add.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/gather.hpp"
@@ -191,3 +192,47 @@ TEST_F(FrontEndConversionWithReferenceTestsF, SavedModelWithNumericalNames) {
model_ref = make_shared<Model>(ResultVector{result}, ParameterVector{x, y, z});
}
}
+
+// Test that a crafted SavedModel with integer overflow in BundleEntryProto
+// offset/size fields produces a clean exception, not a SIGSEGV.
+// The malicious variables.index has entry.offset = 0x7FFFFFFFFFFFFFF0 and entry.size = 16.
+// The sum overflows signed int64 to INT64_MIN, which would bypass the old bounds check.
+TEST(FrontEndConvertModelTest, SavedModelMaliciousOverflowOffset) {
+ shared_ptr<Model> model = nullptr;
+ // Test with mmap enabled (default) — triggers crash at variables_index.cpp CKOG path
+ try {
+ model = convert_model("saved_model_malicious_overflow");
+ FAIL() << "Loading a malicious SavedModel with overflow offset should throw an exception.";
+ } catch (const ov::Exception& error) {
+ string error_message = error.what();
+ EXPECT_TRUE(error_message.find("entry") != string::npos || error_message.find("offset") != string::npos ||
+ error_message.find("bounds") != string::npos || error_message.find("negative") != string::npos ||
+ error_message.find("size") != string::npos)
+ << "Unexpected error message: " << error_message;
+ EXPECT_EQ(model, nullptr);
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected exception type: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception thrown";
+ }
+}
+
+// Same test with mmap disabled to verify the stream code path is also protected
+TEST(FrontEndConvertModelTest, SavedModelMaliciousOverflowOffsetNoMmap) {
+ shared_ptr<Model> model = nullptr;
+ try {
+ model = convert_model("saved_model_malicious_overflow", nullptr, {}, {}, {}, {}, {}, true /* disable_mmap */);
+ FAIL() << "Loading a malicious SavedModel with overflow offset should throw an exception.";
+ } catch (const ov::Exception& error) {
+ string error_message = error.what();
+ EXPECT_TRUE(error_message.find("entry") != string::npos || error_message.find("offset") != string::npos ||
+ error_message.find("bounds") != string::npos || error_message.find("negative") != string::npos ||
+ error_message.find("size") != string::npos)
+ << "Unexpected error message: " << error_message;
+ EXPECT_EQ(model, nullptr);
+ } catch (const std::exception& e) {
+ FAIL() << "Unexpected exception type: " << e.what();
+ } catch (...) {
+ FAIL() << "Unexpected non-std exception thrown";
+ }
+}
diff --git a/src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_malicious_overflow.py b/src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_malicious_overflow.py
new file mode 100644
index 00000000000..546e0da7ce8
--- /dev/null
+++ b/src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_malicious_overflow.py
@@ -0,0 +1,219 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import os
+import struct
+import sys
+
+
+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_signed_varint(value):
+ """Encode a signed int64 as a protobuf varint (two's complement)."""
+ if value < 0:
+ value = (1 << 64) + value
+ return encode_varint(value)
+
+
+def encode_field(field_number, wire_type, data):
+ """Encode a protobuf field."""
+ tag = (field_number << 3) | wire_type
+ return encode_varint(tag) + data
+
+
+def encode_varint_field(field_number, value):
+ return encode_field(field_number, 0, encode_varint(value))
+
+
+def encode_signed_varint_field(field_number, value):
+ return encode_field(field_number, 0, encode_signed_varint(value))
+
+
+def encode_bytes_field(field_number, data):
+ return encode_field(field_number, 2, encode_varint(len(data)) + data)
+
+
+def encode_string_field(field_number, s):
+ return encode_bytes_field(field_number, s.encode('utf-8'))
+
+
+def encode_fixed32_field(field_number, value):
+ return encode_field(field_number, 5, struct.pack('<I', value))
+
+
+def build_bundle_header_proto():
+ """BundleHeaderProto: num_shards=1, endianness=LITTLE, version={producer=1, min_consumer=0}"""
+ version = encode_varint_field(1, 1) + encode_varint_field(2, 0)
+ return encode_varint_field(1, 1) + encode_varint_field(2, 0) + encode_bytes_field(3, version)
+
+
+def build_bundle_entry_proto(dtype, shape_dims, shard_id, offset, size):
+ """BundleEntryProto with given parameters."""
+ shape_bytes = b''
+ for d in shape_dims:
+ dim_msg = encode_signed_varint_field(1, d)
+ shape_bytes += encode_bytes_field(2, dim_msg)
+ return (encode_varint_field(1, dtype) +
+ encode_bytes_field(2, shape_bytes) +
+ encode_varint_field(3, shard_id) +
+ encode_signed_varint_field(4, offset) +
+ encode_signed_varint_field(5, size) +
+ encode_fixed32_field(6, 0))
+
+
+def build_sstable_block(entries):
+ """Build an SSTable data block from key-value pairs."""
+ block = bytearray()
+ restart_offsets = []
+ prev_key = b''
+ for i, (key, value) in enumerate(entries):
+ key_bytes = key.encode('utf-8') if isinstance(key, str) else key
+ shared = 0
+ for j in range(min(len(prev_key), len(key_bytes))):
+ if prev_key[j] == key_bytes[j]:
+ shared += 1
+ else:
+ break
+ non_shared = len(key_bytes) - shared
+ if i % 16 == 0:
+ restart_offsets.append(len(block))
+ shared = 0
+ non_shared = len(key_bytes)
+ block.extend(encode_varint(shared))
+ block.extend(encode_varint(non_shared))
+ block.extend(encode_varint(len(value)))
+ block.extend(key_bytes[shared:])
+ block.extend(value)
+ prev_key = key_bytes
+ if not restart_offsets:
+ restart_offsets = [0]
+ for off in restart_offsets:
+ block.extend(struct.pack('<I', off))
+ block.extend(struct.pack('<I', len(restart_offsets)))
+ return bytes(block)
+
+
+def build_sstable_footer(index_block_offset, index_block_size,
+ metaindex_block_offset=0, metaindex_block_size=0):
+ """Build SSTable footer (48 bytes)."""
+ metaindex_handle = encode_varint(metaindex_block_offset) + encode_varint(metaindex_block_size)
+ index_handle = encode_varint(index_block_offset) + encode_varint(index_block_size)
+ footer = bytearray()
+ footer.extend(metaindex_handle)
+ footer.extend(index_handle)
+ while len(footer) < 40:
+ footer.append(0)
+ footer.extend(struct.pack('<Q', 0xdb4775248b80fb57))
+ return bytes(footer)
+
+
+def build_saved_model_pb():
+ """Build minimal saved_model.pb with VarHandleOp using raw protobuf encoding."""
+ DT_FLOAT = 1
+ dtype_attr_value = encode_varint_field(6, DT_FLOAT)
+ dim2 = encode_signed_varint_field(1, 2)
+ shape_proto = encode_bytes_field(2, dim2) + encode_bytes_field(2, dim2)
+ shape_attr_value = encode_bytes_field(7, shape_proto)
+ t_attr_value = encode_varint_field(6, DT_FLOAT)
+
+ def build_node_def(name, op, inputs=None, attrs=None):
+ msg = encode_string_field(1, name) + encode_string_field(2, op)
+ if inputs:
+ for inp in inputs:
+ msg += encode_string_field(3, inp)
+ if attrs:
+ for key, val in attrs.items():
+ map_entry = encode_string_field(1, key) + encode_bytes_field(2, val)
+ msg += encode_bytes_field(5, map_entry)
+ return msg
+
+ varhandle_node = build_node_def(
+ "my_var", "VarHandleOp",
+ attrs={"dtype": dtype_attr_value, "shape": shape_attr_value})
+ readvariable_node = build_node_def(
+ "read_var", "ReadVariableOp",
+ inputs=["my_var"],
+ attrs={"dtype": dtype_attr_value})
+ identity_node = build_node_def(
+ "Identity", "Identity",
+ inputs=["read_var"],
+ attrs={"T": t_attr_value})
+
+ graph_def = (encode_bytes_field(1, varhandle_node) +
+ encode_bytes_field(1, readvariable_node) +
+ encode_bytes_field(1, identity_node))
+ meta_info_def = encode_string_field(1, "serve")
+ tensor_info = encode_string_field(1, "Identity:0") + encode_varint_field(2, DT_FLOAT)
+ sig_output_entry = encode_string_field(1, "output_0") + encode_bytes_field(2, tensor_info)
+ signature_def = encode_bytes_field(2, sig_output_entry)
+ sig_map_entry = encode_string_field(1, "serving_default") + encode_bytes_field(2, signature_def)
+ meta_graph_def = (encode_bytes_field(1, meta_info_def) +
+ encode_bytes_field(2, graph_def) +
+ encode_bytes_field(5, sig_map_entry))
+ return encode_signed_varint_field(1, 1) + encode_bytes_field(2, meta_graph_def)
+
+
+def main():
+ output_dir = os.path.join(sys.argv[1], "saved_model_malicious_overflow")
+ os.makedirs(os.path.join(output_dir, "variables"), exist_ok=True)
+
+ # Malicious offset that causes signed int64 overflow when added to size
+ malicious_offset = 0x7FFFFFFFFFFFFFF0
+
+ # Build variables.index SSTable with 3 entries:
+ # "" -> BundleHeaderProto
+ # "_CHECKPOINTABLE_OBJECT_GRAPH" -> BundleEntryProto (malicious offset)
+ # "my_var" -> BundleEntryProto (malicious offset)
+ header_proto = build_bundle_header_proto()
+ ckog_entry = build_bundle_entry_proto(
+ dtype=7, shape_dims=[], shard_id=0,
+ offset=malicious_offset, size=16)
+ var_entry = build_bundle_entry_proto(
+ dtype=1, shape_dims=[2, 2], shard_id=0,
+ offset=malicious_offset, size=16)
+
+ data_entries = [
+ ("", header_proto),
+ ("_CHECKPOINTABLE_OBJECT_GRAPH", ckog_entry),
+ ("my_var", var_entry),
+ ]
+ data_block = build_sstable_block(data_entries)
+ data_block_full = data_block + b'\x00' + struct.pack('<I', 0)
+
+ metaindex_block = build_sstable_block([])
+ metaindex_full = metaindex_block + b'\x00' + struct.pack('<I', 0)
+
+ last_key = "my_var"
+ data_block_handle = encode_varint(0) + encode_varint(len(data_block))
+ index_block = build_sstable_block([(last_key, data_block_handle)])
+ index_full = index_block + b'\x00' + struct.pack('<I', 0)
+
+ metaindex_offset = len(data_block_full)
+ index_offset = metaindex_offset + len(metaindex_full)
+
+ footer = build_sstable_footer(
+ index_block_offset=index_offset,
+ index_block_size=len(index_block),
+ metaindex_block_offset=metaindex_offset,
+ metaindex_block_size=len(metaindex_block))
+
+ index_file = data_block_full + metaindex_full + index_full + footer
+
+ with open(os.path.join(output_dir, "saved_model.pb"), 'wb') as f:
+ f.write(build_saved_model_pb())
+ with open(os.path.join(output_dir, "variables", "variables.index"), 'wb') as f:
+ f.write(index_file)
+ with open(os.path.join(output_dir, "variables", "variables.data-00000-of-00001"), 'wb') as f:
+ f.write(b'\x00' * 64)
+
+
+if __name__ == '__main__':
+ main()