Skip to content

Commit 0cc39b9

Browse files
Merge pull request #123123 from cybrdude:fuzz/tflite-interp-overflow-target
PiperOrigin-RevId: 999903734
2 parents 857d3a4 + c1be76e commit 0cc39b9

4 files changed

Lines changed: 232 additions & 16 deletions

File tree

‎tensorflow/lite/core/interpreter_builder.cc‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -374,20 +374,23 @@ TfLiteStatus InterpreterBuilder::ParseNodes(
374374
if (op->custom_options()) {
375375
init_data = reinterpret_cast<const char*>(op->custom_options()->data());
376376
init_data_size = op->custom_options()->size();
377-
} else if (op->large_custom_options_offset() > 1 && allocation_) {
378-
if (op->large_custom_options_offset() +
379-
op->large_custom_options_size() >
380-
allocation_->bytes()) {
381-
TF_LITE_REPORT_ERROR(
382-
error_reporter_,
383-
"Custom Option Offset for opcode_index %d is out of bound\n",
384-
index);
385-
return kTfLiteError;
377+
} else if (allocation_) {
378+
const uint64_t offset = op->large_custom_options_offset();
379+
if (offset > 1) {
380+
const size_t alloc_bytes = allocation_->bytes();
381+
const uint64_t size = op->large_custom_options_size();
382+
if (offset > alloc_bytes || size > alloc_bytes - offset) {
383+
TF_LITE_REPORT_ERROR(
384+
error_reporter_,
385+
"Custom Option Offset for opcode_index %d is out of bound\n",
386+
index);
387+
return kTfLiteError;
388+
}
389+
// If the custom op is storing payloads outside of flatbuffers
390+
init_data =
391+
reinterpret_cast<const char*>(allocation_->base()) + offset;
392+
init_data_size = size;
386393
}
387-
// If the custom op is storing payloads outside of flatbuffers
388-
init_data = reinterpret_cast<const char*>(allocation_->base()) +
389-
op->large_custom_options_offset();
390-
init_data_size = op->large_custom_options_size();
391394
}
392395
} else {
393396
MallocDataAllocator malloc_allocator;
@@ -811,14 +814,16 @@ TfLiteStatus InterpreterBuilder::ParseTensors(
811814
*buffer_data = reinterpret_cast<const char*>(array->data());
812815
return kTfLiteOk;
813816
} else if (offset > 1 && allocation_) {
814-
if (offset + buffer->size() > allocation_->bytes()) {
817+
const size_t alloc_bytes = allocation_->bytes();
818+
const uint64_t size = buffer->size();
819+
if (offset > alloc_bytes || size > alloc_bytes - offset) {
815820
TF_LITE_REPORT_ERROR(
816821
error_reporter_,
817822
"Constant buffer %d specified an out of range offset.\n",
818823
tensor->buffer());
819824
return kTfLiteError;
820825
}
821-
*buffer_size = buffer->size();
826+
*buffer_size = size;
822827
*buffer_data =
823828
reinterpret_cast<const char*>(allocation_->base()) + offset;
824829
return kTfLiteOk;
@@ -827,7 +832,7 @@ TfLiteStatus InterpreterBuilder::ParseTensors(
827832
return kTfLiteOk;
828833
};
829834
size_t buffer_size = 0;
830-
const char* buffer_ptr;
835+
const char* buffer_ptr = nullptr;
831836
TF_LITE_ENSURE_STATUS(get_readonly_data(&buffer_ptr, &buffer_size));
832837

833838
const auto* src_quantization = tensor->quantization();

‎tensorflow/lite/core/model_test.cc‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ limitations under the License.
1818
#include <stdlib.h>
1919
#include <string.h>
2020

21+
#include <limits>
2122
#include <map>
2223
#include <memory>
2324
#include <string>
@@ -511,6 +512,89 @@ TEST(BasicFlatBufferModel, TestInvalidBlockwiseQuantizationDetails) {
511512
kTfLiteError);
512513
}
513514

515+
// A constant tensor whose Buffer lives outside the flatbuffer, addressed by an
516+
// (offset, size) pair chosen so that offset + size wraps around uint64 to a
517+
// small value. The model is loaded without the verifier on purpose, so the
518+
// bounds check in InterpreterBuilder::ParseTensors is what has to reject it.
519+
TEST(BasicFlatBufferModel, TestRejectsWrappingExternalBufferOffset) {
520+
flatbuffers::FlatBufferBuilder builder;
521+
const uint64_t offset = std::numeric_limits<uint64_t>::max() - 10;
522+
const uint64_t size = 20; // offset + size wraps to 9.
523+
std::vector<int32_t> shape = {5}; // 5 x float32 == 20 bytes == size.
524+
auto tensor =
525+
::tflite::CreateTensorDirect(builder, &shape, tflite::TensorType_FLOAT32,
526+
/*buffer=*/1, "weights");
527+
std::vector<flatbuffers::Offset<::tflite::Tensor>> tensors = {tensor};
528+
auto subgraph = ::tflite::CreateSubGraphDirect(
529+
builder, &tensors, /*inputs=*/nullptr, /*outputs=*/nullptr,
530+
/*operators=*/nullptr, "subgraph");
531+
std::vector<flatbuffers::Offset<::tflite::SubGraph>> subgraphs = {subgraph};
532+
std::vector<flatbuffers::Offset<::tflite::Buffer>> buffers = {
533+
::tflite::CreateBuffer(builder),
534+
::tflite::CreateBuffer(builder, /*data=*/0, offset, size)};
535+
auto model = ::tflite::CreateModelDirect(builder, TFLITE_SCHEMA_VERSION,
536+
/*operator_codes=*/nullptr,
537+
&subgraphs, "model", &buffers);
538+
::tflite::FinishModelBuffer(builder, model);
539+
auto fb_model = FlatBufferModel::BuildFromBuffer(
540+
reinterpret_cast<const char*>(builder.GetBufferPointer()),
541+
builder.GetSize());
542+
ASSERT_TRUE(fb_model);
543+
std::unique_ptr<Interpreter> interpreter;
544+
TrivialResolver resolver;
545+
EXPECT_NE(InterpreterBuilder(*fb_model, resolver)(&interpreter), kTfLiteOk);
546+
}
547+
548+
// The same wrapping pair on a custom op's large_custom_options, which is the
549+
// InterpreterBuilder::ParseNodes side of the check.
550+
TEST(BasicFlatBufferModel, TestRejectsWrappingLargeCustomOptionsOffset) {
551+
flatbuffers::FlatBufferBuilder builder;
552+
const uint64_t offset = std::numeric_limits<uint64_t>::max() - 10;
553+
const uint64_t size = 20; // offset + size wraps to 9.
554+
std::vector<int32_t> shape = {1};
555+
auto tensor =
556+
::tflite::CreateTensorDirect(builder, &shape, tflite::TensorType_FLOAT32,
557+
/*buffer=*/0, "t");
558+
std::vector<flatbuffers::Offset<::tflite::Tensor>> tensors = {tensor};
559+
std::vector<int32_t> inputs = {0};
560+
std::vector<int32_t> outputs = {0};
561+
auto inputs_vector = builder.CreateVector(inputs);
562+
auto outputs_vector = builder.CreateVector(outputs);
563+
::tflite::OperatorBuilder op(builder);
564+
op.add_opcode_index(0);
565+
op.add_inputs(inputs_vector);
566+
op.add_outputs(outputs_vector);
567+
op.add_large_custom_options_offset(offset);
568+
op.add_large_custom_options_size(size);
569+
std::vector<flatbuffers::Offset<::tflite::Operator>> operators = {
570+
op.Finish()};
571+
auto subgraph = ::tflite::CreateSubGraphDirect(
572+
builder, &tensors, &inputs, &outputs, &operators, "subgraph");
573+
std::vector<flatbuffers::Offset<::tflite::SubGraph>> subgraphs = {subgraph};
574+
std::vector<flatbuffers::Offset<::tflite::OperatorCode>> operator_codes = {
575+
::tflite::CreateOperatorCodeDirect(
576+
builder, /*deprecated_builtin_code=*/tflite::BuiltinOperator_CUSTOM,
577+
"WRAP", /*version=*/1, tflite::BuiltinOperator_CUSTOM)};
578+
std::vector<flatbuffers::Offset<::tflite::Buffer>> buffers = {
579+
::tflite::CreateBuffer(builder)};
580+
auto model = ::tflite::CreateModelDirect(builder, TFLITE_SCHEMA_VERSION,
581+
&operator_codes, &subgraphs, "model",
582+
&buffers);
583+
::tflite::FinishModelBuffer(builder, model);
584+
auto fb_model = FlatBufferModel::BuildFromBuffer(
585+
reinterpret_cast<const char*>(builder.GetBufferPointer()),
586+
builder.GetSize());
587+
ASSERT_TRUE(fb_model);
588+
std::unique_ptr<Interpreter> interpreter;
589+
// ParseNodes keys off registration->builtin_code, so the resolved
590+
// registration itself must be marked CUSTOM.
591+
TfLiteRegistration custom_reg = dummy_reg;
592+
custom_reg.builtin_code = tflite::BuiltinOperator_CUSTOM;
593+
custom_reg.custom_name = "WRAP";
594+
TrivialResolver resolver(&custom_reg);
595+
EXPECT_NE(InterpreterBuilder(*fb_model, resolver)(&interpreter), kTfLiteOk);
596+
}
597+
514598
TEST(BasicFlatBufferModel, TestWithNumThreads) {
515599
TestErrorReporter reporter;
516600
auto model = FlatBufferModel::BuildFromFile(

‎tensorflow/security/fuzzing/cc/BUILD‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,3 +268,15 @@ tf_cc_fuzz_test(
268268
"@xla//xla/tsl/platform:env",
269269
],
270270
)
271+
272+
tf_cc_fuzz_test(
273+
name = "tflite_interp_overflow_fuzz",
274+
srcs = ["tflite_interp_overflow_fuzz.cc"],
275+
data = ["//tensorflow/lite:testdata/add.bin"],
276+
deps = [
277+
"//tensorflow/core/platform:resource_loader",
278+
"//tensorflow/lite:framework",
279+
"//tensorflow/lite/c:common",
280+
"//tensorflow/lite/kernels:builtin_ops",
281+
],
282+
)
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/* Copyright 2026 The TensorFlow Authors. All Rights Reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
==============================================================================*/
15+
16+
// FuzzTest coverage for TFLite model load, interpreter build, and invoke.
17+
// Models enter through FlatBufferModel::VerifyAndBuildFromBuffer, so inputs
18+
// that fail the flatbuffers structural check are rejected at ingress, as they
19+
// would be in a deployment that verifies models. That check does not cover the
20+
// uint64 external-offset fields (Buffer.offset/size and
21+
// Operator.large_custom_options_offset/size), which point past the flatbuffer
22+
// into the appended data, so the bounds checks on them in
23+
// InterpreterBuilder::ParseNodes and ParseTensors are exercised directly. The
24+
// OSS-Fuzz tensorflow build has no TFLite target that reaches this path.
25+
26+
#include <cstdarg>
27+
#include <cstring>
28+
#include <fstream>
29+
#include <iterator>
30+
#include <memory>
31+
#include <string>
32+
#include <tuple>
33+
#include <utility>
34+
#include <vector>
35+
36+
#include "fuzztest/fuzztest.h"
37+
#include "tensorflow/core/platform/resource_loader.h"
38+
#include "tensorflow/lite/c/common.h"
39+
#include "tensorflow/lite/error_reporter.h"
40+
#include "tensorflow/lite/interpreter.h"
41+
#include "tensorflow/lite/interpreter_builder.h"
42+
#include "tensorflow/lite/kernels/register.h"
43+
#include "tensorflow/lite/model_builder.h"
44+
45+
namespace {
46+
47+
// Nearly every fuzz input is malformed, and the default reporter writes each
48+
// rejection to stderr, which would dominate the run. The model and, through
49+
// the model, the interpreter builder report into this instead.
50+
class NullErrorReporter : public tflite::ErrorReporter {
51+
public:
52+
int Report(const char* /*format*/, va_list /*args*/) override { return 0; }
53+
};
54+
55+
// A valid model to start from, so the fuzzer does not have to rediscover the
56+
// flatbuffer framing before it reaches InterpreterBuilder and Invoke.
57+
std::vector<std::tuple<std::string>> SeedModels() {
58+
std::ifstream file(
59+
tensorflow::GetDataDependencyFilepath("tensorflow/lite/testdata/add.bin"),
60+
std::ios::binary);
61+
std::string bytes((std::istreambuf_iterator<char>(file)),
62+
std::istreambuf_iterator<char>());
63+
if (bytes.empty()) return {};
64+
return {std::make_tuple(std::move(bytes))};
65+
}
66+
67+
// Whether `tensor` is a runtime input that is safe and useful to zero.
68+
bool IsZeroableInput(const TfLiteTensor* tensor) {
69+
if (tensor == nullptr || tensor->data.raw == nullptr || tensor->bytes == 0) {
70+
return false;
71+
}
72+
// A constant input aliases the read-only model mapping, and a persistent
73+
// read-only one is owned and filled by the planner; neither is
74+
// uninitialized, and writing to the mapping would fault.
75+
if (tensor->allocation_type == kTfLiteMmapRo ||
76+
tensor->allocation_type == kTfLitePersistentRo) {
77+
return false;
78+
}
79+
// These are not plain byte buffers of `bytes` length.
80+
if (tensor->type == kTfLiteString || tensor->type == kTfLiteResource ||
81+
tensor->type == kTfLiteVariant) {
82+
return false;
83+
}
84+
return true;
85+
}
86+
87+
void FuzzModelBuildAndInvoke(const std::string& model_bytes) {
88+
NullErrorReporter error_reporter;
89+
auto model = tflite::FlatBufferModel::VerifyAndBuildFromBuffer(
90+
model_bytes.data(), model_bytes.size(), /*extra_verifier=*/nullptr,
91+
&error_reporter);
92+
if (model == nullptr) return;
93+
94+
tflite::ops::builtin::BuiltinOpResolver resolver;
95+
std::unique_ptr<tflite::Interpreter> interpreter;
96+
if (tflite::InterpreterBuilder(*model, resolver)(&interpreter) != kTfLiteOk) {
97+
return;
98+
}
99+
if (interpreter == nullptr) return;
100+
if (interpreter->AllocateTensors() != kTfLiteOk) return;
101+
102+
// Zero-initialize runtime inputs so MSan does not flag uninitialized reads.
103+
for (int input_index : interpreter->inputs()) {
104+
TfLiteTensor* tensor = interpreter->tensor(input_index);
105+
if (IsZeroableInput(tensor)) {
106+
std::memset(tensor->data.raw, 0, tensor->bytes);
107+
}
108+
}
109+
110+
interpreter->Invoke();
111+
}
112+
FUZZ_TEST(TfliteInterpreterBuilder, FuzzModelBuildAndInvoke)
113+
.WithSeeds(SeedModels());
114+
115+
} // namespace

0 commit comments

Comments
 (0)