Skip to content

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

[TFL FE] Add bounds checking for tensor, buffer, and opcode indices in GraphIteratorFlatBuffer (#34074)

Evgeny Kotov91f33eaf8a31
diff --git a/src/frontends/tensorflow_lite/src/graph_iterator_flatbuffer.cpp b/src/frontends/tensorflow_lite/src/graph_iterator_flatbuffer.cpp
index f660a35ef12..c7fdd3e1f34 100644
--- a/src/frontends/tensorflow_lite/src/graph_iterator_flatbuffer.cpp
+++ b/src/frontends/tensorflow_lite/src/graph_iterator_flatbuffer.cpp
@@ -25,15 +25,21 @@ GraphIteratorFlatBuffer::GraphIteratorFlatBuffer(const std::string& path) {
model_file.close();
m_model = tflite::GetModel(m_data.data());
+ FRONT_END_GENERAL_CHECK(m_model != nullptr, "Failed to parse TFLite model from file: ", path);
auto sub_graphs = m_model->subgraphs();
+ FRONT_END_GENERAL_CHECK(sub_graphs && sub_graphs->size() > 0, "TFLite model has no subgraphs in file: ", path);
m_subgraphs = {sub_graphs->begin(), sub_graphs->end()};
m_graph = m_subgraphs[0];
+ FRONT_END_GENERAL_CHECK(m_graph != nullptr, "First subgraph is null in file: ", path);
const auto operators = m_graph->operators();
+ FRONT_END_GENERAL_CHECK(operators != nullptr, "TFLite subgraph has no operators in file: ", path);
auto operators_vec = std::vector<const tflite::Operator*>{operators->begin(), operators->end()};
m_nodes.assign(operators_vec.begin(), operators_vec.end());
auto outputs = m_graph->outputs();
auto inputs = m_graph->inputs();
+ FRONT_END_GENERAL_CHECK(outputs != nullptr, "TFLite subgraph has no outputs in file: ", path);
+ FRONT_END_GENERAL_CHECK(inputs != nullptr, "TFLite subgraph has no inputs in file: ", path);
m_nodes.insert(m_nodes.begin(), outputs->begin(), outputs->end());
m_nodes.insert(m_nodes.begin(), inputs->begin(), inputs->end());
}
@@ -49,11 +55,15 @@ std::shared_ptr<GraphIterator> GraphIteratorFlatBuffer::get_subgraph(size_t idx)
iterator->m_model = m_model;
iterator->m_subgraphs = {}; // TODO: check if we need to pass all sub-graphs here (while in a while situation)
iterator->m_graph = m_subgraphs[idx];
+ FRONT_END_GENERAL_CHECK(iterator->m_graph != nullptr, "Subgraph at index ", idx, " is null");
const auto operators = iterator->m_graph->operators();
+ FRONT_END_GENERAL_CHECK(operators != nullptr, "TFLite subgraph has no operators");
auto operators_vec = std::vector<const tflite::Operator*>{operators->begin(), operators->end()};
iterator->m_nodes.assign(operators_vec.begin(), operators_vec.end());
auto outputs = iterator->m_graph->outputs();
auto inputs = iterator->m_graph->inputs();
+ FRONT_END_GENERAL_CHECK(outputs != nullptr, "TFLite subgraph has no outputs");
+ FRONT_END_GENERAL_CHECK(inputs != nullptr, "TFLite subgraph has no inputs");
iterator->m_nodes.insert(iterator->m_nodes.begin(), outputs->begin(), outputs->end());
iterator->m_nodes.insert(iterator->m_nodes.begin(), inputs->begin(), inputs->end());
return iterator;
@@ -64,28 +74,66 @@ std::shared_ptr<DecoderBase> GraphIteratorFlatBuffer::get_decoder() const {
bool is_op = any_item.is<const tflite::Operator*>();
FRONT_END_GENERAL_CHECK(is_op || any_item.is<int32_t>());
auto tensors = m_graph->tensors();
+ FRONT_END_GENERAL_CHECK(tensors != nullptr, "TFLite subgraph has no tensors");
+ const auto tensors_size = tensors->size();
if (is_op) {
auto node = m_nodes[node_index].as<const tflite::Operator*>();
+ FRONT_END_GENERAL_CHECK(node != nullptr, "Null operator at node index ", node_index);
auto buffers = m_model->buffers();
+ FRONT_END_GENERAL_CHECK(buffers != nullptr, "TFLite model has no buffers");
+ const auto buffers_size = buffers->size();
std::map<size_t, TensorInfo> input_info = {}, output_info = {};
size_t i = 0;
+ FRONT_END_GENERAL_CHECK(node->inputs() != nullptr, "Operator has no inputs");
for (auto input : *node->inputs()) {
if (input == -1)
continue;
- auto buffer = (*buffers)[(*tensors)[input]->buffer()];
+ FRONT_END_GENERAL_CHECK(input >= 0 && static_cast<size_t>(input) < tensors_size,
+ "Operator input tensor index ",
+ input,
+ " is out of range. Number of tensors: ",
+ tensors_size);
auto tensor = (*tensors)[input];
+ FRONT_END_GENERAL_CHECK(tensor != nullptr, "Null tensor at index ", input);
+ FRONT_END_GENERAL_CHECK(tensor->buffer() < buffers_size,
+ "Tensor buffer index ",
+ tensor->buffer(),
+ " is out of range. Number of buffers: ",
+ buffers_size);
+ auto buffer = (*buffers)[tensor->buffer()];
input_info[i++] = TensorInfo{tensor, buffer};
}
i = 0;
+ FRONT_END_GENERAL_CHECK(node->outputs() != nullptr, "Operator has no outputs");
for (auto output : *node->outputs()) {
- auto buffer = (*buffers)[(*tensors)[output]->buffer()];
+ if (output == -1)
+ continue;
+ FRONT_END_GENERAL_CHECK(output >= 0 && static_cast<size_t>(output) < tensors_size,
+ "Operator output tensor index ",
+ output,
+ " is out of range. Number of tensors: ",
+ tensors_size);
auto tensor = (*tensors)[output];
+ FRONT_END_GENERAL_CHECK(tensor != nullptr, "Null tensor at index ", output);
+ FRONT_END_GENERAL_CHECK(tensor->buffer() < buffers_size,
+ "Tensor buffer index ",
+ tensor->buffer(),
+ " is out of range. Number of buffers: ",
+ buffers_size);
+ auto buffer = (*buffers)[tensor->buffer()];
output_info[i++] = TensorInfo{tensor, buffer};
}
auto op_codes = m_model->operator_codes();
+ FRONT_END_GENERAL_CHECK(op_codes != nullptr, "TFLite model has no operator codes");
+ FRONT_END_GENERAL_CHECK(node->opcode_index() < op_codes->size(),
+ "Operator opcode index ",
+ node->opcode_index(),
+ " is out of range. Number of operator codes: ",
+ op_codes->size());
auto operator_code = (*op_codes)[node->opcode_index()];
+ FRONT_END_GENERAL_CHECK(operator_code != nullptr, "Null operator code at index ", node->opcode_index());
std::string type;
if (operator_code->deprecated_builtin_code() <
tflite::BuiltinOperator::BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES) {
@@ -94,13 +142,21 @@ std::shared_ptr<DecoderBase> GraphIteratorFlatBuffer::get_decoder() const {
type = tflite::EnumNamesBuiltinOperator()[operator_code->builtin_code()];
}
if (type == "CUSTOM") {
- type = operator_code->custom_code()->str();
+ auto custom_code = operator_code->custom_code();
+ FRONT_END_GENERAL_CHECK(custom_code != nullptr, "Operator has CUSTOM type but no custom_code string");
+ type = custom_code->str();
}
auto name = std::to_string(node_index - m_graph->inputs()->size() - m_graph->outputs()->size());
return std::make_shared<DecoderFlatBuffer>(node, type, name, input_info, output_info);
} else {
auto tensor_id = m_nodes[node_index].as<int32_t>();
+ FRONT_END_GENERAL_CHECK(tensor_id >= 0 && static_cast<size_t>(tensor_id) < tensors_size,
+ "Graph input/output tensor index ",
+ tensor_id,
+ " is out of range. Number of tensors: ",
+ tensors_size);
auto tensor = (*tensors)[tensor_id];
+ FRONT_END_GENERAL_CHECK(tensor != nullptr, "Null tensor at index ", tensor_id);
auto info = TensorInfo{tensor, nullptr};
auto inputs = m_graph->inputs();
auto outputs = m_graph->outputs();
diff --git a/src/frontends/tensorflow_lite/tests/convert_unsupported.cpp b/src/frontends/tensorflow_lite/tests/convert_unsupported.cpp
index 23933b31bfe..6e85cb50b6d 100644
--- a/src/frontends/tensorflow_lite/tests/convert_unsupported.cpp
+++ b/src/frontends/tensorflow_lite/tests/convert_unsupported.cpp
@@ -11,44 +11,52 @@ using namespace std;
using namespace ov;
using namespace ov::frontend;
-TEST(FrontEndConvertModelTest, test_zerolen) {
- FrontEndManager fem;
- FrontEnd::Ptr frontEnd;
- InputModel::Ptr inputModel;
- OV_ASSERT_NO_THROW(frontEnd = fem.load_by_framework(TF_LITE_FE));
- ASSERT_NE(frontEnd, nullptr);
- auto model_filename = FrontEndTestUtils::make_model_path(string(TEST_TENSORFLOW_LITE_MODELS_DIRNAME) +
- string("bad_header/zerolen.tflite"));
- OV_ASSERT_NO_THROW(inputModel = frontEnd->load(model_filename));
- ASSERT_NE(inputModel, nullptr);
- shared_ptr<ov::Model> model;
- ASSERT_THROW(model = frontEnd->convert(inputModel), std::exception);
-}
+// Tests where load() succeeds but convert() throws an exception
+class MalformedModelConvertTest : public ::testing::TestWithParam<std::string> {
+protected:
+ void SetUp() override {
+ FrontEndManager fem;
+ OV_ASSERT_NO_THROW(m_frontEnd = fem.load_by_framework(TF_LITE_FE));
+ ASSERT_NE(m_frontEnd, nullptr);
+ }
+ FrontEnd::Ptr m_frontEnd;
+};
-TEST(FrontEndConvertModelTest, test_wrong_len) {
- FrontEndManager fem;
- FrontEnd::Ptr frontEnd;
+TEST_P(MalformedModelConvertTest, convert_throws) {
+ auto model_filename = FrontEndTestUtils::make_model_path(string(TEST_TENSORFLOW_LITE_MODELS_DIRNAME) + GetParam());
InputModel::Ptr inputModel;
- OV_ASSERT_NO_THROW(frontEnd = fem.load_by_framework(TF_LITE_FE));
- ASSERT_NE(frontEnd, nullptr);
- auto model_filename = FrontEndTestUtils::make_model_path(string(TEST_TENSORFLOW_LITE_MODELS_DIRNAME) +
- string("bad_header/wrong_len_3.tflite"));
- OV_ASSERT_NO_THROW(inputModel = frontEnd->load(model_filename));
+ OV_ASSERT_NO_THROW(inputModel = m_frontEnd->load(model_filename));
ASSERT_NE(inputModel, nullptr);
shared_ptr<ov::Model> model;
- ASSERT_THROW(model = frontEnd->convert(inputModel), std::exception);
+ ASSERT_THROW(model = m_frontEnd->convert(inputModel), std::exception);
}
-TEST(FrontEndConvertModelTest, test_wrong_pos) {
- FrontEndManager fem;
- FrontEnd::Ptr frontEnd;
- InputModel::Ptr inputModel;
- OV_ASSERT_NO_THROW(frontEnd = fem.load_by_framework(TF_LITE_FE));
- ASSERT_NE(frontEnd, nullptr);
- auto model_filename = FrontEndTestUtils::make_model_path(string(TEST_TENSORFLOW_LITE_MODELS_DIRNAME) +
- string("bad_header/wrong_pos.tflite"));
- OV_ASSERT_NO_THROW(inputModel = frontEnd->load(model_filename));
- ASSERT_NE(inputModel, nullptr);
- shared_ptr<ov::Model> model;
- ASSERT_THROW(model = frontEnd->convert(inputModel), std::exception);
+INSTANTIATE_TEST_SUITE_P(BadHeader,
+ MalformedModelConvertTest,
+ ::testing::Values("bad_header/zerolen.tflite",
+ "bad_header/wrong_len_3.tflite",
+ "bad_header/wrong_pos.tflite"));
+
+// Tests where load() itself throws an exception (malformed indices)
+class MalformedModelLoadTest : public ::testing::TestWithParam<std::string> {
+protected:
+ void SetUp() override {
+ FrontEndManager fem;
+ OV_ASSERT_NO_THROW(m_frontEnd = fem.load_by_framework(TF_LITE_FE));
+ ASSERT_NE(m_frontEnd, nullptr);
+ }
+ FrontEnd::Ptr m_frontEnd;
+};
+
+TEST_P(MalformedModelLoadTest, load_throws) {
+ auto model_filename = FrontEndTestUtils::make_model_path(string(TEST_TENSORFLOW_LITE_MODELS_DIRNAME) + GetParam());
+ ASSERT_THROW(m_frontEnd->load(model_filename), std::exception);
}
+
+INSTANTIATE_TEST_SUITE_P(OobIndices,
+ MalformedModelLoadTest,
+ ::testing::Values("malformed_indices/oob_output_tensor_index.tflite",
+ "malformed_indices/oob_input_tensor_index.tflite",
+ "malformed_indices/oob_opcode_index.tflite",
+ "malformed_indices/oob_graph_io_tensor_index.tflite",
+ "malformed_indices/oob_buffer_index.tflite"));
diff --git a/src/frontends/tensorflow_lite/tests/test_models/gen_scripts/generate_malformed_indices.py b/src/frontends/tensorflow_lite/tests/test_models/gen_scripts/generate_malformed_indices.py
new file mode 100644
index 00000000000..fc0be1f7fe2
--- /dev/null
+++ b/src/frontends/tensorflow_lite/tests/test_models/gen_scripts/generate_malformed_indices.py
@@ -0,0 +1,204 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+# Generate crafted .tflite model files with out-of-bounds tensor/buffer/opcode indices.
+# These models test that the TFLite frontend properly validates all FlatBuffer
+# vector indices before use, preventing CWE-125 (Out-of-bounds Read).
+#
+# Each model is a minimal valid TFLite structure with one intentionally invalid
+# index that would cause an out-of-bounds read without proper bounds checking.
+#
+# Models generated:
+# malformed_indices/oob_output_tensor_index.tflite - operator output index > tensors count
+# malformed_indices/oob_input_tensor_index.tflite - operator input index > tensors count
+# malformed_indices/oob_opcode_index.tflite - opcode index > operator_codes count
+# malformed_indices/oob_graph_io_tensor_index.tflite - graph I/O tensor index > tensors count
+# malformed_indices/oob_buffer_index.tflite - tensor buffer index > buffers count
+
+import os
+import sys
+
+import flatbuffers
+
+
+def build_minimal_tflite(output_tensor_indices=None,
+ input_tensor_indices=None,
+ num_tensors=2,
+ num_buffers=3,
+ opcode_index=0,
+ num_opcodes=1,
+ graph_input_ids=None,
+ graph_output_ids=None,
+ tensor_buffer_indices=None):
+ """
+ Build a minimal .tflite FlatBuffer model using flatbuffers.Builder.
+
+ Default valid model structure:
+ - 2 tensors (index 0 = input, index 1 = output)
+ - 3 buffers (0 = empty sentinel, 1 for tensor0, 2 for tensor1)
+ - 1 operator code (ADD)
+ - 1 operator: inputs=[0], outputs=[1], opcode_index=0
+ - SubGraph inputs=[0], outputs=[1]
+
+ Parameters allow overriding indices to produce malformed models.
+ """
+ builder = flatbuffers.Builder(1024)
+
+ # -- Buffers --
+ buffer_offsets = []
+ for _ in range(num_buffers):
+ builder.StartObject(3) # Buffer: data, offset, size
+ buf_offset = builder.EndObject()
+ buffer_offsets.append(buf_offset)
+
+ builder.StartVector(4, len(buffer_offsets), 4)
+ for off in reversed(buffer_offsets):
+ builder.PrependUOffsetTRelative(off)
+ buffers_vec = builder.EndVector()
+
+ # -- Operator Codes --
+ opcode_offsets = []
+ for _ in range(num_opcodes):
+ builder.StartObject(4) # OperatorCode: deprecated_builtin_code, custom_code, version, builtin_code
+ builder.PrependInt8Slot(0, 0, 0) # deprecated_builtin_code = ADD(0)
+ builder.PrependInt32Slot(3, 0, 0) # builtin_code = ADD(0)
+ builder.PrependInt32Slot(2, 1, 1) # version = 1
+ oc_offset = builder.EndObject()
+ opcode_offsets.append(oc_offset)
+
+ builder.StartVector(4, len(opcode_offsets), 4)
+ for off in reversed(opcode_offsets):
+ builder.PrependUOffsetTRelative(off)
+ opcodes_vec = builder.EndVector()
+
+ # -- Tensors --
+ tensor_names = []
+ for i in range(num_tensors):
+ tensor_names.append(builder.CreateString(f"tensor_{i}"))
+
+ shape_vecs = []
+ for _ in range(num_tensors):
+ builder.StartVector(4, 1, 4)
+ builder.PrependInt32(1)
+ shape_vecs.append(builder.EndVector())
+
+ tensor_offsets = []
+ for i in range(num_tensors):
+ buf_idx = i + 1 if i + 1 < num_buffers else 0
+ if tensor_buffer_indices is not None and i < len(tensor_buffer_indices):
+ buf_idx = tensor_buffer_indices[i]
+ builder.StartObject(11) # Tensor: shape, type, buffer, name, ...
+ builder.PrependUOffsetTRelativeSlot(0, shape_vecs[i], 0) # shape
+ builder.PrependInt8Slot(1, 0, 0) # type = FLOAT32
+ builder.PrependUint32Slot(2, buf_idx, 0) # buffer index
+ builder.PrependUOffsetTRelativeSlot(3, tensor_names[i], 0) # name
+ t_offset = builder.EndObject()
+ tensor_offsets.append(t_offset)
+
+ builder.StartVector(4, len(tensor_offsets), 4)
+ for off in reversed(tensor_offsets):
+ builder.PrependUOffsetTRelative(off)
+ tensors_vec = builder.EndVector()
+
+ # -- Operator --
+ op_inputs = input_tensor_indices if input_tensor_indices is not None else [0]
+ builder.StartVector(4, len(op_inputs), 4)
+ for idx in reversed(op_inputs):
+ builder.PrependInt32(idx)
+ op_inputs_vec = builder.EndVector()
+
+ op_outputs = output_tensor_indices if output_tensor_indices is not None else [1]
+ builder.StartVector(4, len(op_outputs), 4)
+ for idx in reversed(op_outputs):
+ builder.PrependInt32(idx)
+ op_outputs_vec = builder.EndVector()
+
+ builder.StartObject(11) # Operator: opcode_index, inputs, outputs, ...
+ builder.PrependUint32Slot(0, opcode_index, 0)
+ builder.PrependUOffsetTRelativeSlot(1, op_inputs_vec, 0)
+ builder.PrependUOffsetTRelativeSlot(2, op_outputs_vec, 0)
+ op_offset = builder.EndObject()
+
+ builder.StartVector(4, 1, 4)
+ builder.PrependUOffsetTRelative(op_offset)
+ operators_vec = builder.EndVector()
+
+ # -- SubGraph --
+ sg_inputs = graph_input_ids if graph_input_ids is not None else [0]
+ builder.StartVector(4, len(sg_inputs), 4)
+ for idx in reversed(sg_inputs):
+ builder.PrependInt32(idx)
+ sg_inputs_vec = builder.EndVector()
+
+ sg_outputs = graph_output_ids if graph_output_ids is not None else [1]
+ builder.StartVector(4, len(sg_outputs), 4)
+ for idx in reversed(sg_outputs):
+ builder.PrependInt32(idx)
+ sg_outputs_vec = builder.EndVector()
+
+ sg_name = builder.CreateString("main")
+
+ builder.StartObject(7) # SubGraph: tensors, inputs, outputs, operators, name, ...
+ builder.PrependUOffsetTRelativeSlot(0, tensors_vec, 0)
+ builder.PrependUOffsetTRelativeSlot(1, sg_inputs_vec, 0)
+ builder.PrependUOffsetTRelativeSlot(2, sg_outputs_vec, 0)
+ builder.PrependUOffsetTRelativeSlot(3, operators_vec, 0)
+ builder.PrependUOffsetTRelativeSlot(4, sg_name, 0)
+ sg_offset = builder.EndObject()
+
+ builder.StartVector(4, 1, 4)
+ builder.PrependUOffsetTRelative(sg_offset)
+ subgraphs_vec = builder.EndVector()
+
+ desc = builder.CreateString("malformed_test_model")
+
+ # -- Model --
+ builder.StartObject(8) # Model: version, operator_codes, subgraphs, description, buffers, ...
+ builder.PrependUint32Slot(0, 3, 0) # version = 3
+ builder.PrependUOffsetTRelativeSlot(1, opcodes_vec, 0)
+ builder.PrependUOffsetTRelativeSlot(2, subgraphs_vec, 0)
+ builder.PrependUOffsetTRelativeSlot(3, desc, 0)
+ builder.PrependUOffsetTRelativeSlot(4, buffers_vec, 0)
+ model_offset = builder.EndObject()
+
+ builder.Finish(model_offset, b"TFL3")
+ return bytes(builder.Output())
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print(f"Usage: {sys.argv[0]} <output_directory>")
+ sys.exit(1)
+
+ path_to_model_dir = os.path.join(sys.argv[1], "malformed_indices")
+ os.makedirs(path_to_model_dir, exist_ok=True)
+
+ # 1. Operator output tensor index out of bounds
+ # 2 tensors defined, operator output references index 9999
+ model = build_minimal_tflite(output_tensor_indices=[9999])
+ with open(os.path.join(path_to_model_dir, 'oob_output_tensor_index.tflite'), 'wb') as f:
+ f.write(model)
+
+ # 2. Operator input tensor index out of bounds
+ # 2 tensors defined, operator input references index 9999
+ model = build_minimal_tflite(input_tensor_indices=[9999])
+ with open(os.path.join(path_to_model_dir, 'oob_input_tensor_index.tflite'), 'wb') as f:
+ f.write(model)
+
+ # 3. Operator opcode index out of bounds
+ # 1 opcode defined, operator references opcode index 99
+ model = build_minimal_tflite(opcode_index=99)
+ with open(os.path.join(path_to_model_dir, 'oob_opcode_index.tflite'), 'wb') as f:
+ f.write(model)
+
+ # 4. Graph input/output tensor index out of bounds
+ # 2 tensors defined, graph inputs/outputs reference index 9999
+ model = build_minimal_tflite(graph_input_ids=[9999], graph_output_ids=[9999])
+ with open(os.path.join(path_to_model_dir, 'oob_graph_io_tensor_index.tflite'), 'wb') as f:
+ f.write(model)
+
+ # 5. Tensor buffer index out of bounds
+ # 3 buffers defined, tensor 1 references buffer index 9999
+ model = build_minimal_tflite(tensor_buffer_indices=[1, 9999])
+ with open(os.path.join(path_to_model_dir, 'oob_buffer_index.tflite'), 'wb') as f:
+ f.write(model)