Skip to content
Memory corruption Write-up Advanced

18 Bytes, tiny but killing: Hunting a Memory-Corruption Bug in Tesseract

The dictionary loader in Tesseract trusts a file-supplied edge count and walks the edge array without any upper bound, so a crafted trained-data file with a single zero edge makes the loop read past the end of the heap allocation. An attacker who can supply or influence a trained-data file could crash the process at model-load time, before any image is processed.

AREX Follow

Published on arex-godofwar.medium.com

Cybersecurity

AREX, on arex-godofwar.medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 10 min read.

Context: what the target, product and feature are, and what the feature normally does

Tesseract is the most widely used open source OCR engine. It has more than 70,000 GitHub stars, ships in Linux distributions, and sits behind a large number of "extract text from this image" features. It has also been fuzzed continuously for years by Google's OSS-Fuzz, which is why the obvious memory-corruption bugs were expected to have been found long ago.

The bug described here is not in the image-decode path. It lives in the loader for .traineddata files, the model bundle passed to the engine. A trained-data file contains the LSTM network, the unicharset, and several dictionaries encoded as DAWGs (Directed Acyclic Word Graphs). The dictionaries are normally treated as inert configuration, but they are binary blobs full of length fields, counts and offsets that get deserialised. The defect is a heap out-of-bounds read (CWE-125) in that dictionary loader, triggered by an 18-byte file.

Affected versions are Tesseract 5.5.2 and earlier. The fix landed in 5.5.3 via PR #4581. The issue was assigned CVE-2026-73067; severity was Moderate.

Setup: accounts, roles, tools, versions and preconditions

The analysis was done against Tesseract 5.5.2, commit 6e1d56a8. The relevant source files are src/dict/dawg.cpp and src/dict/dawg.h.

The reproduction uses a small C++ driver that runs the real loader over bytes read from a file, the same construction Tesseract's internal DawgLoader uses, but fed a hand-crafted blob instead of a component extracted from a .traineddata. Tesseract is compiled with -fsanitize=address,undefined and the harness is linked against it. No accounts, roles or network access are involved: the precondition is simply the ability to make a process load an attacker-influenced trained-data file.

Finding it: what the researcher noticed and why it looked wrong

The starting observation is about coverage rather than about code. Pointing a fuzzer at Tesseract's front door, the image-decode path, is a bad bet for a novel finding, because image decoding routes through Leptonica and that whole surface has been under continuous OSS-Fuzz coverage for years. A crash there would almost certainly already be a closed issue.

Star count measures popularity, not audit coverage. The productive question is therefore not "what is the biggest input?" but "where has the automated tooling not been?"

Tesseract has a second, quieter class of untrusted input: the .traineddata file itself. The OSS-Fuzz harness fuzzes image bytes against a fixed, valid trained-data file, so the deserializer that parses the trained-data was, in practice, not being fuzzed at all. That is the seam: length and count fields read from a file, feeding allocations and array indexing, on a code path nobody was hammering.

The DAWG format

Tesseract stores each dictionary as a SquishedDawg, a flat array of 64-bit edge records. On disk, as a component inside the .traineddata, the format read by SquishedDawg::read_squished_dawg is:

Text
int16   magic            // must equal kDawgMagicNumber (42)
int32   unicharset_size   // used to compute the edge bit-field layout
int32   num_edges         // how many edge records follow
uint64  edges[num_edges]  // the edge records themselves

Each 64-bit edge record packs several fields into bit ranges: a unichar ID, a "next node" reference (an index back into the same edges_ array), and three flag bits, among them a direction bit (forward/backward) and a last-edge bit that marks the final edge of a node's edge list. Graph traversal means starting at a node (an index into edges_) and walking forward through consecutive records until one with the last-edge bit set is reached.

That sentence, "walk forward until you hit the last-edge bit", is the whole bug.

Exploitation: step by step

Step 1: the loader trusts the file

The loader in src/dict/dawg.cpp reads the count and the edges as follows:

Text
if (!file->DeSerialize(&num_edges_)) {
     return false;
}
ASSERT_HOST(num_edges_ > 0);

Dawg::init(unicharset_size);
edges_ = new EDGE_RECORD[num_edges_];

if (!file->DeSerialize(&edges_[0], num_edges_)) {
  return false;
}

num_edges_ is attacker-controlled and the only validation is that it is greater than zero. That matters later for the allocation, but the memory bug is one step further on.

Step 2: node 0 is walked immediately after the read

Immediately after a successful read, SquishedDawg::Load walks node 0:

Text
num_forward_edges_in_node0 = num_forward_edges(0);

Step 3: the walk has no floor

num_forward_edges is where the floor drops out:

Text
int32_t SquishedDawg::num_forward_edges(NODE_REF node) const {
  EDGE_REF edge = node;
  int32_t num = 0;
  if (forward_edge(edge)) {
    do {
      num++;
    } while (!last_edge(edge++));
  }
  return num;
}

The loop increments edge and keeps going until last_edge returns true. And last_edge (src/dict/dawg.h:543) indexes the array with no bound whatsoever:

Text
inline bool last_edge(EDGE_REF edge_ref) const {
  return (edges_[edge_ref] & (MARKER_FLAG << flag_start_bit_)) != 0;
}

If edge 0 is a forward edge and no record in [0, num_edges_) has the last-edge marker set, the loop reads edges_[0], edges_[1], and so on up to edges_[num_edges_ - 1], then keeps going: edges_[num_edges_], edges_[num_edges_ + 1], reading eight bytes past the end of the allocation on every iteration, until it lands on a qword in adjacent heap memory that has the marker bit set, or wanders into an unmapped page and takes a SIGSEGV.

Step 4: a single zero edge is enough

The minimal trigger is one edge record set to zero. Walking through what 0 means to the traversal predicates:

  • edge_occupied(0) evaluates edges_[0] != next_node_mask_. next_node_mask_ is a nonzero bitmask, so 0 != mask and the edge counts as occupied.
  • The direction flag bit in 0 is clear, so the edge is a forward edge, forward_edge(0) is true, and the loop is entered.
  • last_edge(0) sees the marker bit in 0 clear, so this edge is not the last edge.

An all-zero edge is, to Tesseract, "an occupied, forward, non-terminal edge". The loop enters, never finds a terminator, and walks off a one-element array on the very next iteration. No lookup, no image, no OCR: this fires at model-load time, the instant the dictionary is parsed.

Step 5: the 18-byte proof of concept

The header is 10 bytes (magic, unicharset_size, num_edges) and exactly one 8-byte edge record is needed, giving a minimal file of 18 bytes:

Text
offset  bytes                     field                      value
------  ------------------------  -------------------------  -----------------------
0x00    2a 00                     int16  magic               42  (kDawgMagicNumber)
0x02    01 00 00 00               int32  unicharset_size     1
0x06    01 00 00 00               int32  num_edges           1
0x0a    00 00 00 00 00 00 00 00   uint64 edges[0]            0   (forward, not-last)

18 bytes is the true minimum, and this is provable by perturbation:

  • 17 bytes, with the edge truncated by one byte: the edge DeSerialize fails, read_squished_dawg returns false, no crash.
  • A wrong magic byte: early return, no crash.
  • edges[0] = 2, with the last-edge bit set for this layout: the loop terminates at edge 0 and the file loads cleanly.
  • edges[0] = next_node_mask: the edge reads as unoccupied, forward_edge(0) is false, and the loop is never entered.

Only the exact 18-byte layout with a zero edge reaches the sink. Every neighbour is benign, which is why this is a genuine boundary bug and not a fuzzer flake.

Step 6: reproduce with a harness and AddressSanitizer

The reproduction is a tiny driver that runs the real loader over bytes from a file:

Text
#include "dawg.h"
#include "serialis.h"

using namespace tesseract;

int main(int argc, char** argv) {
  std::vector<char> buf = slurp(argv[1]);
  TFile fp;
  fp.Open(buf.data(), buf.size());
  SquishedDawg dawg(DAWG_TYPE_WORD, "eng", SYSTEM_DAWG_PERM, 0);
  bool ok = dawg.Load(&fp);
  fprintf(stderr, "Load returned %d\n", ok);
  return ok ? 0 : 1;
}

Compiling Tesseract with -fsanitize=address,undefined, linking the harness and running it against the 18-byte file produces:

Text
==ERROR: AddressSanitizer: heap-buffer-overflow ... READ of size 8
    #0 SquishedDawg::last_edge(long) const          src/dict/dawg.h:543
    #1 SquishedDawg::num_forward_edges(long) const   src/dict/dawg.cpp
    #2 SquishedDawg::Load(TFile*)                     src/dict/dawg.h
0x... is located 0 bytes after 8-byte region [...,...)
allocated by thread T0 here:
    #1 SquishedDawg::read_squished_dawg(TFile*)       src/dict/dawg.cpp

"READ of size 8" and "0 bytes after 8-byte region" describe a one-past-the-end read of edges_[1] on a one-element array, exactly where the analysis said it would be.

Step 7: the full taint path from untrusted input to sink

The harness proves the sink; the reachability argument proves it matters. The path from a public API that every consumer touches down to the overread is:

Text
TessBaseAPI::Init(<malicious .traineddata>)
        -> Dict::Load(lang, TessdataManager*)
  -> DawgCache::GetSquishedDawg(TESSDATA_SYSTEM_DAWG, ...)
        // also PUNC / NUMBER / FREQ / BIGRAM / UNAMBIG and the LSTM_* dawgs
  -> DawgLoader::Load()
  -> SquishedDawg::Load(TFile over attacker bytes)
  -> read_squished_dawg()        // trusts num_edges_
  -> num_forward_edges(0)        // unbounded walk
  -> last_edge(edge)             // OOB READ

The DAWG components are dictionary data inside every language pack. The threat model is therefore a process that loads an attacker-influenced .traineddata: a downloaded or third-party language pack, a user-supplied --tessdata-dir, or any application that accepts uploaded model data. Such a process crashes on load, before it ever looks at an image.

Root cause: the mistake in the code or design, and why existing defences did not stop it

The loader treats the edge count and the edge contents as trusted. num_edges_ is checked only for being greater than zero, and last_edge indexes edges_ without any comparison against num_edges_. The traversal loop in num_forward_edges relies entirely on finding a terminator bit inside the array, and nothing guarantees that such a bit exists. A single zero edge satisfies the predicates that enter the loop while never satisfying the one that leaves it, so the walk continues into adjacent heap memory.

The existing defence, continuous OSS-Fuzz coverage, did not reach this code because the harness fuzzes image bytes against a fixed, valid trained-data file. The trained-data deserializer was effectively unfuzzed, so the missing bound was never exercised by the automated tooling.

Impact: what an attacker could do, to whom, under which conditions

The net impact is availability-only denial of service, locally reachable. The CVSS 3.1 vector is AV:L/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H, giving 6.2, Medium. The rating would be higher only if an application fetches or accepts trained-data over the network.

An attacker who can supply or influence a .traineddata file, through a downloaded or third-party language pack, a user-supplied --tessdata-dir, or an application that accepts uploaded model data, can crash the process at load time. The read continues until it hits a marked qword in adjacent heap memory or an unmapped page, so the outcome is either a heap out-of-bounds read that AddressSanitizer reports or a SIGSEGV.

Fix: what was changed

PR #4581 hardens the whole traversal and the allocation rather than patching the single crash. Three changes matter.

  1. Every edge-traversal loop is bounded. Each while (!last_edge(edge++)) in the file becomes:
Text
if (last_edge(edge)) break;
++edge;
} while (edge < num_edges_);

The walk can no longer run past the array. num_edges_ is also changed from int32_t to uint32_t, since a negative edge count is meaningless.

  1. The allocation is bounded. Because num_edges_ was only checked for being greater than zero, a crafted num_edges = 0x7FFFFFFF would request a roughly 17 GB allocation, an uncontrolled-allocation DoS on memory-limited hosts. The fix rejects any count that cannot be backed by the data actually present:
Text
if (num_edges_ > file->RemainingBytes() / sizeof(EDGE_RECORD)) {
  return false;
}
  1. The loaded structure is validated. After reading the edges, a one-time pass rejects malformed graphs, any edge whose next_node points outside [0, num_edges_), and any forward-edge run that is not terminated within bounds:
Text
NODE_REF next = next_node_from_edge_rec(edges_[i]);
if (next != 0 && static_cast<uint32_t>(next) >= num_edges_) {
  return false;
}

Variants to test

The transferable lesson is about where to spend attention on a mature target.

  1. Popularity is not coverage. A high star count says many people use the project; it says nothing about which internal surface has been fuzzed. Look for the gap between heavily used and heavily audited.
  2. Follow the fuzzer, then go where it is not. OSS-Fuzz drives the obvious entry points such as image bytes and network parsers. The neglected corners are the config, model and serialised-blob loaders that everyone assumes are trusted. They are full of file-controlled lengths, counts and offsets feeding allocations and indexing.
  3. Trace the number, not the feature. Walk every attacker-controlled length, count or offset forward to its allocation, memcpy, resize and index sinks. The bug is almost always a missing bound between a value from a file and its use as a size or index.
  4. Clear a real bar. A finding needs a sanitizer-confirmed crash, a minimised input, a root cause at file:line and a taint path from untrusted input to sink. Anything short of that is a lead, not a finding.

Coordinated disclosure

The repository had no SECURITY.md and no private vulnerability reporting enabled, a common dead-end. The path that works in that situation, and the one GitHub itself recommends, is to open a public issue with no technical details and let the maintainer open the door. That is what happened: the maintainer responded within hours over a weekend, pointed to a private channel and opened a GitHub Security Advisory. The full report, root cause, taint path, ASan trace and the 18-byte PoC then went through the private advisory. No public PoC was published, and the issue was assigned CVE-2026-73067.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 25 min read.

What happened, in plain words

Tesseract is a free program that reads text out of pictures. You give it a photo of a page, a screenshot, a scanned receipt, and it hands back the words it can see. This process is called OCR, short for optical character recognition. Tesseract is one of the most widely used OCR engines in the world: it is built into many Linux systems and sits behind a large number of "pull the text out of this image" features in other software.

Because so many people use it, many people have also tried to break it. For years, Google has run an automated testing service called OSS-Fuzz that throws huge numbers of deliberately malformed files at open source projects, including Tesseract, looking for crashes. The expectation was that the easy memory bugs in Tesseract had all been found and fixed long ago.

They had not. This article is about a small mistake in a part of Tesseract that the automated testing never really touched. The mistake lets a tiny 18-byte file make the program read past the end of a block of memory it was given. That kind of mistake is called a heap out-of-bounds read, and it can crash the program. The bug was reported through a private advisory and given the identifier CVE-2026-73067.

Affected versions are Tesseract 5.5.2 and earlier. The fix arrived in 5.5.3 through pull request #4581. The severity was rated Moderate.

Some background you need first

Before the details make sense, a few ideas need explaining from scratch.

Memory and the heap. When a program runs, it keeps its working data in memory. Part of that memory is called the heap: a big pool the program borrows from at runtime. When the program needs space for, say, a list of numbers, it asks the operating system for a chunk of the heap of a certain size. That request is called an allocation. The program is then expected to stay inside the chunk it was given. Reading or writing even one byte past the end of the chunk is a bug, because the neighbouring memory belongs to something else.

Out-of-bounds read. If a program reads past the end of its chunk, that is an out-of-bounds read. The value it gets back is whatever happens to sit next door, which is meaningless to it. Sometimes the read lands on memory that does not exist at all, and the operating system stops the program immediately. That forced stop is called a segmentation fault, or SIGSEGV. This class of bug is known as CWE-125.

Fuzzing. Fuzzing means feeding a program enormous numbers of random or semi-random inputs and watching for crashes. It is a cheap way to find memory bugs, and it works well on code that parses files. OSS-Fuzz is Google's large, continuously running fuzzing service.

A fuzzing harness. A harness is the small piece of glue code that tells the fuzzer how to call the program. It decides what gets varied (the input being fuzzed) and what stays fixed (everything else).

OCR and trained data. Tesseract does not contain a hard-coded understanding of letters. It learns from a model file, called a .traineddata file, which you point the engine at. That file holds the neural network, a list of characters, and several dictionaries. A dictionary here is not a book; it is a compact data structure that lets the engine quickly check whether a string of letters is a real word.

DAWG. Those dictionaries are stored in a format called a DAWG, a Directed Acyclic Word Graph. You can picture it as a set of stepping stones with arrows between them, where you hop from stone to stone following the arrows to spell out a word. In the file, the stones are stored one after another in a flat list, and each stone is a 64-bit number called an edge record. A 64-bit number is a number that takes 8 bytes of storage.

Bits and bit fields. A byte is eight bits, each a 0 or a 1. A 64-bit number is 64 bits. Programmers often pack several small pieces of information into one number by giving each piece its own range of bits, called a bit field. One bit can act as a flag: set to 1 means yes, 0 means no.

Deserialisation. When a program saves its data to a file and later reads it back, the reading-back step is called deserialisation. The program trusts that the file follows the expected layout. If an attacker controls the file, that trust is dangerous, because the attacker can put any numbers they like into the length and count fields.

A proof of concept (PoC). A small file or script that reliably demonstrates a bug. It is the difference between "I think there is a problem" and "here, watch it happen".

AddressSanitizer. A tool that watches a program while it runs and shouts the moment it reads or writes outside its allocated memory. It turns a silent, mysterious misbehaviour into a precise error message with a file and line number.

CVE. A CVE is a public catalogue number for a known security flaw, so that everyone can refer to the same bug by the same name.

CVSS. A scoring system for how serious a vulnerability is, from 0 to 10. It looks at things like whether an attacker needs to be on the same machine, whether they need an account, and whether the impact is on confidentiality, integrity or availability.

The target and the feature

Tesseract has more than 70,000 stars on GitHub. A star is GitHub's "like" button; it is a rough measure of popularity. It ships in Linux distributions and sits behind a large number of "extract text from this image" features.

It has also been fuzzed continuously for years by OSS-Fuzz. That is why the obvious memory-corruption bugs were expected to have been found long ago.

The bug described here is not in the image-decode path. The image-decode path is the part that opens a PNG or TIFF and turns it into a grid of pixels. That path is the obvious front door, and it is heavily fuzzed.

The bug lives instead in the loader for .traineddata files, the model bundle passed to the engine. A trained-data file contains the LSTM network (the machine-learning model itself), the unicharset (the list of characters the model knows), and several dictionaries encoded as DAWGs. The dictionaries are normally treated as inert configuration, like a settings file. But they are binary blobs full of length fields, counts and offsets that get deserialised. The defect is a heap out-of-bounds read (CWE-125) in that dictionary loader, triggered by an 18-byte file.

The fix landed in 5.5.3 via PR #4581. The issue was assigned CVE-2026-73067 and rated Moderate.

Setup: what was needed to investigate

The analysis was done against Tesseract 5.5.2, at a specific point in the project's history identified by the commit hash 6e1d56a8. A commit hash is a unique fingerprint for one saved version of the source code, so anyone can check out exactly the same code.

The relevant source files are src/dict/dawg.cpp and src/dict/dawg.h. Source code is organised into files; the .cpp file holds the implementation and the .h file holds declarations and small inline functions.

The reproduction uses a small C++ driver that runs the real loader over bytes read from a file. It is the same construction Tesseract's internal DawgLoader uses, but fed a hand-crafted blob instead of a component extracted from a .traineddata. Tesseract is compiled with -fsanitize=address,undefined and the harness is linked against it. That compiler flag switches on AddressSanitizer and UndefinedBehaviorSanitizer, two runtime checkers that report memory and arithmetic mistakes as they happen.

No accounts, roles or network access are involved. The precondition is simply the ability to make a process load an attacker-influenced trained-data file.

Finding it: what the researcher noticed and why it looked wrong

The starting observation is about coverage rather than about code. Pointing a fuzzer at Tesseract's front door, the image-decode path, is a bad bet for a novel finding, because image decoding routes through a separate library called Leptonica, and that whole surface has been under continuous OSS-Fuzz coverage for years. A crash there would almost certainly already be a closed issue.

Star count measures popularity, not audit coverage. The productive question is therefore not "what is the biggest input?" but "where has the automated tooling not been?"

Tesseract has a second, quieter class of untrusted input: the .traineddata file itself. The OSS-Fuzz harness fuzzes image bytes against a fixed, valid trained-data file. In other words, the fuzzer varies the picture but always hands the engine the same trusted model. So the deserializer that parses the trained-data was, in practice, not being fuzzed at all.

That is the seam: length and count fields read from a file, feeding allocations and array indexing, on a code path nobody was hammering. A seam here means a gap between two things that each look well covered.

The DAWG format

Tesseract stores each dictionary as a SquishedDawg, a flat array of 64-bit edge records. On disk, as a component inside the .traineddata, the format read by SquishedDawg::read_squished_dawg is:

Text
int16   magic            // must equal kDawgMagicNumber (42)
int32   unicharset_size   // used to compute the edge bit-field layout
int32   num_edges         // how many edge records follow
uint64  edges[num_edges]  // the edge records themselves

Line by line:

  • int16 magic is a 2-byte number that must equal 42. It is a fixed value that must equal 42.
  • int32 unicharset_size is a 4-byte number saying how many characters the dictionary knows about. The loader uses it to work out how the bits inside each edge record are divided up.
  • int32 num_edges is a 4-byte number saying how many edge records follow. This is the field the attacker controls.
  • uint64 edges[num_edges] is the list of edge records itself, each 8 bytes long.

Each 64-bit edge record packs several fields into bit ranges: a unichar ID (which character this step represents), a "next node" reference (an index back into the same edges_ array, meaning "jump to this stone next"), and three flag bits. Among those flags are a direction bit (forward or backward) and a last-edge bit that marks the final edge of a node's edge list.

Graph traversal means starting at a node (an index into edges_) and walking forward through consecutive records until one with the last-edge bit set is reached. Think of reading a shopping list where each line ends with the word "stop" on the last item; you keep reading lines until you see "stop".

That sentence, "walk forward until you hit the last-edge bit", is the whole bug. The code assumes a "stop" always exists. Nothing checks that it does.

Exploitation: step by step

Step 1: the loader trusts the file

The loader in src/dict/dawg.cpp reads the count and the edges as follows:

Text
if (!file->DeSerialize(&num_edges_)) {
     return false;
}
ASSERT_HOST(num_edges_ > 0);

Dawg::init(unicharset_size);
edges_ = new EDGE_RECORD[num_edges_];

if (!file->DeSerialize(&edges_[0], num_edges_)) {
  return false;
}

Line by line:

  • if (!file->DeSerialize(&num_edges_)) asks the file object to read the edge count into the variable num_edges_. If that read fails, the ! flips the result and the function returns false, meaning "loading failed".
  • ASSERT_HOST(num_edges_ > 0); is a sanity check that the count is greater than zero. That is the only validation applied to it.
  • Dawg::init(unicharset_size); sets up the bit layout using the character count from the file.
  • edges_ = new EDGE_RECORD[num_edges_]; asks the heap for space for num_edges_ edge records. This is the allocation.
  • if (!file->DeSerialize(&edges_[0], num_edges_)) reads that many edge records into the freshly allocated space. If the file is too short, this fails and the function returns false.

num_edges_ is attacker-controlled and the only validation is that it is greater than zero. That matters later for the allocation, but the memory bug is one step further on.

Step 2: node 0 is walked immediately after the read

Immediately after a successful read, SquishedDawg::Load walks node 0:

Text
num_forward_edges_in_node0 = num_forward_edges(0);

This line calls a function that counts how many forward edges sit at the start of the graph. Node 0 is the first stone. The important part is that this happens automatically, as part of loading, before the engine ever looks at an image.

Step 3: the walk has no floor

num_forward_edges is where the floor drops out:

Text
int32_t SquishedDawg::num_forward_edges(NODE_REF node) const {
  EDGE_REF edge = node;
  int32_t num = 0;
  if (forward_edge(edge)) {
    do {
      num++;
    } while (!last_edge(edge++));
  }
  return num;
}

Line by line:

  • int32_t SquishedDawg::num_forward_edges(NODE_REF node) const { declares the function. It takes a node reference and returns a 32-bit integer count.
  • EDGE_REF edge = node; sets a cursor called edge to the starting stone.
  • int32_t num = 0; starts the counter at zero.
  • if (forward_edge(edge)) { checks whether the starting stone is a forward edge. If it is not, the loop is skipped entirely.
  • do { num++; } while (!last_edge(edge++)); is the loop. Each pass adds one to the counter, then asks last_edge whether the current stone is the final one. The edge++ means "use the current value, then move the cursor to the next stone". The ! means "keep looping while this is not the last edge".
  • return num; hands back the count.

The loop increments edge and keeps going until last_edge returns true. And last_edge (src/dict/dawg.h:543) indexes the array with no bound whatsoever:

Text
inline bool last_edge(EDGE_REF edge_ref) const {
  return (edges_[edge_ref] & (MARKER_FLAG << flag_start_bit_)) != 0;
}

Line by line:

  • inline bool last_edge(EDGE_REF edge_ref) const { declares a small function that takes a position and answers yes or no.
  • return (edges_[edge_ref] & (MARKER_FLAG << flag_start_bit_)) != 0; looks up the edge record at that position, uses a bitwise AND (&) to isolate the marker bit, and checks whether the result is nonzero. If it is, this is the last edge.

The problem is edges_[edge_ref]: there is no check that edge_ref is smaller than num_edges_. The function will happily look up any position it is given, even one past the end of the array.

If edge 0 is a forward edge and no record in [0, num_edges_) has the last-edge marker set, the loop reads edges_[0], edges_[1], and so on up to edges_[num_edges_ - 1], then keeps going: edges_[num_edges_], edges_[num_edges_ + 1], reading eight bytes past the end of the allocation on every iteration. It continues until it lands on a qword in adjacent heap memory that happens to have the marker bit set, or wanders into an unmapped page and takes a SIGSEGV. A qword is simply an 8-byte chunk of memory.

Step 4: a single zero edge is enough

The minimal trigger is one edge record set to zero. Walking through what 0 means to the traversal predicates:

  • edge_occupied(0) evaluates edges_[0] != next_node_mask_. next_node_mask_ is a nonzero bitmask, so 0 != mask and the edge counts as occupied.
  • The direction flag bit in 0 is clear, so the edge is a forward edge, forward_edge(0) is true, and the loop is entered.
  • last_edge(0) sees the marker bit in 0 clear, so this edge is not the last edge.

In plain words: a number made entirely of zeros has every flag switched off. To Tesseract, that reads as "an occupied, forward, non-terminal edge". The loop enters, never finds a terminator, and walks off a one-element array on the very next iteration. No lookup, no image, no OCR: this fires at model-load time, the instant the dictionary is parsed.

Step 5: the 18-byte proof of concept

The header is 10 bytes (magic, unicharset_size, num_edges) and exactly one 8-byte edge record is needed, giving a minimal file of 18 bytes:

Text
offset  bytes                     field                      value
------  ------------------------  -------------------------  -----------------------
0x00    2a 00                     int16  magic               42  (kDawgMagicNumber)
0x02    01 00 00 00               int32  unicharset_size     1
0x06    01 00 00 00               int32  num_edges           1
0x0a    00 00 00 00 00 00 00 00   uint64 edges[0]            0   (forward, not-last)

Reading the table:

  • The offset column is the position in the file, counted in bytes from the start, written in hexadecimal (base 16). 0x00 is the first byte.
  • The bytes column shows the actual bytes, again in hex. 2a 00 is the number 42 stored in two bytes.
  • The field column names what those bytes mean.
  • The value column gives the human-readable meaning.

So the file is: a 2-byte signature saying "this is a DAWG", a 4-byte character count of 1, a 4-byte edge count of 1, and one 8-byte edge record that is all zeros. Ten plus eight is eighteen.

18 bytes is the true minimum, and this is provable by perturbation. Perturbation means changing one thing at a time and checking that the bug disappears, which proves the exact combination is required:

  • 17 bytes, with the edge truncated by one byte: the edge DeSerialize fails, read_squished_dawg returns false, no crash.
  • A wrong magic byte: early return, no crash.
  • edges[0] = 2, with the last-edge bit set for this layout: the loop terminates at edge 0 and the file loads cleanly.
  • edges[0] = next_node_mask: the edge reads as unoccupied, forward_edge(0) is false, and the loop is never entered.

Only the exact 18-byte layout with a zero edge reaches the sink. The sink is the dangerous line of code where the bad read finally happens. Every neighbour is benign, which is why this is a genuine boundary bug and not a fuzzer flake. A flake is a crash that comes and goes for unrelated reasons.

Step 6: reproduce with a harness and AddressSanitizer

The reproduction is a tiny driver that runs the real loader over bytes from a file:

Text
#include "dawg.h"
#include "serialis.h"

using namespace tesseract;

int main(int argc, char** argv) {
  std::vector<char> buf = slurp(argv[1]);
  TFile fp;
  fp.Open(buf.data(), buf.size());
  SquishedDawg dawg(DAWG_TYPE_WORD, "eng", SYSTEM_DAWG_PERM, 0);
  bool ok = dawg.Load(&fp);
  fprintf(stderr, "Load returned %d\n", ok);
  return ok ? 0 : 1;
}

Line by line:

  • #include "dawg.h" and #include "serialis.h" pull in the declarations for the dictionary code and the file-reading code.
  • using namespace tesseract; lets the code refer to Tesseract's names without typing the prefix every time.
  • int main(int argc, char** argv) { is the entry point. argv[1] is the path of the file given on the command line.
  • std::vector<char> buf = slurp(argv[1]); reads the whole file into memory as a list of bytes. slurp is a helper that does the reading.
  • TFile fp; creates a file object that Tesseract's loader understands.
  • fp.Open(buf.data(), buf.size()); points that object at the bytes already in memory, rather than at a file on disk.
  • SquishedDawg dawg(DAWG_TYPE_WORD, "eng", SYSTEM_DAWG_PERM, 0); creates a dictionary object of the word type, for English, with the system dictionary permission.
  • bool ok = dawg.Load(&fp); runs the real loader on our bytes. This is the line that triggers the bug.
  • fprintf(stderr, "Load returned %d\n", ok); prints whether loading succeeded.
  • return ok ? 0 : 1; exits with a success or failure code.

Compiling Tesseract with -fsanitize=address,undefined, linking the harness and running it against the 18-byte file produces:

Text
==ERROR: AddressSanitizer: heap-buffer-overflow ... READ of size 8
    #0 SquishedDawg::last_edge(long) const          src/dict/dawg.h:543
    #1 SquishedDawg::num_forward_edges(long) const   src/dict/dawg.cpp
    #2 SquishedDawg::Load(TFile*)                     src/dict/dawg.h
0x... is located 0 bytes after 8-byte region [...,...)
allocated by thread T0 here:
    #1 SquishedDawg::read_squished_dawg(TFile*)       src/dict/dawg.cpp

Reading the report:

  • heap-buffer-overflow ... READ of size 8 says the program read 8 bytes outside the chunk it was given.
  • The numbered lines are the call stack, the chain of function calls that led there. #0 is where it happened: last_edge at src/dict/dawg.h:543. #1 is the caller, num_forward_edges. #2 is the caller above that, Load.
  • 0x... is located 0 bytes after 8-byte region says the bad address sits immediately after an 8-byte chunk. That chunk is the single edge record.
  • allocated by thread T0 here points back to where the chunk was created, in read_squished_dawg.

"READ of size 8" and "0 bytes after 8-byte region" describe a one-past-the-end read of edges_[1] on a one-element array, exactly where the analysis said it would be. The fault is deterministic across runs, with the same faulting offset every time. Deterministic means it happens every single time, not occasionally.

Step 7: the full taint path from untrusted input to sink

The harness proves the sink; the reachability argument proves it matters. Reachability means showing that a real user of the library can actually get to the buggy line. A taint path is the trail from where untrusted data enters the program to where it causes harm.

The path from a public API that every consumer touches down to the overread is:

Text
TessBaseAPI::Init(<malicious .traineddata>)
        -> Dict::Load(lang, TessdataManager*)
  -> DawgCache::GetSquishedDawg(TESSDATA_SYSTEM_DAWG, ...)
        // also PUNC / NUMBER / FREQ / BIGRAM / UNAMBIG and the LSTM_* dawgs
  -> DawgLoader::Load()
  -> SquishedDawg::Load(TFile over attacker bytes)
  -> read_squished_dawg()        // trusts num_edges_
  -> num_forward_edges(0)        // unbounded walk
  -> last_edge(edge)             // OOB READ

Reading it top to bottom:

  • TessBaseAPI::Init is the public function an application calls to start the engine with a given model file. If that file is malicious, the trouble starts here.
  • Dict::Load loads the dictionaries for a language.
  • DawgCache::GetSquishedDawg fetches a particular dictionary. The comment lists several other dictionary types that also go through this path.
  • DawgLoader::Load is the internal loader.
  • SquishedDawg::Load runs over the attacker's bytes.
  • read_squished_dawg reads the count and trusts it.
  • num_forward_edges(0) starts the unbounded walk.
  • last_edge(edge) performs the out-of-bounds read.

The DAWG components are dictionary data inside every language pack. The threat model is therefore a process that loads an attacker-influenced .traineddata: a downloaded or third-party language pack, a user-supplied --tessdata-dir (a command-line option telling Tesseract where to find its model files), or any application that accepts uploaded model data. Such a process crashes on load, before it ever looks at an image.

Root cause: the mistake in the code or design, and why existing defences did not stop it

The loader treats the edge count and the edge contents as trusted. num_edges_ is checked only for being greater than zero, and last_edge indexes edges_ without any comparison against num_edges_. The traversal loop in num_forward_edges relies entirely on finding a terminator bit inside the array, and nothing guarantees that such a bit exists. A single zero edge satisfies the predicates that enter the loop while never satisfying the one that leaves it, so the walk continues into adjacent heap memory.

The existing defence, continuous OSS-Fuzz coverage, did not reach this code because the harness fuzzes image bytes against a fixed, valid trained-data file. The trained-data deserializer was effectively unfuzzed, so the missing bound was never exercised by the automated tooling.

Impact: what an attacker could do, to whom, under which conditions

The net impact is availability-only denial of service, locally reachable. Availability means the program is up and working; denial of service means an attacker can make it stop working. Locally reachable means the attacker needs to get the file onto the machine or into the application, rather than being able to trigger it remotely over the internet by itself.

The CVSS 3.1 vector is AV:L/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H, giving 6.2, Medium. Decoding the vector:

  • AV:L means the attack vector is local.
  • AC:L means the attack complexity is low.
  • PR:N means no privileges are required.
  • UI:N means no user interaction is required beyond the file being loaded.
  • S:U means the impact stays within the vulnerable component.
  • C:N and I:N mean no impact on confidentiality or integrity: no data is stolen or altered.
  • A:H means high impact on availability: the program goes down.

The rating would be higher only if an application fetches or accepts trained-data over the network.

An attacker who can supply or influence a .traineddata file, through a downloaded or third-party language pack, a user-supplied --tessdata-dir, or an application that accepts uploaded model data, can crash the process at load time. The read continues until it hits a marked qword in adjacent heap memory or an unmapped page, so the outcome is either a heap out-of-bounds read that AddressSanitizer reports or a SIGSEGV.

Fix: what was changed

PR #4581 hardens the whole traversal and the allocation rather than patching the single crash. Three changes matter.

  1. Every edge-traversal loop is bounded. Each while (!last_edge(edge++)) in the file becomes:
Text
if (last_edge(edge)) break;
++edge;
} while (edge < num_edges_);

Line by line:

  • if (last_edge(edge)) break; checks the current stone first. If it is the last one, leave the loop immediately.
  • ++edge; moves the cursor to the next stone.
  • } while (edge < num_edges_); is the loop condition. It keeps going only while the cursor is still inside the array. This is the missing floor: the walk can no longer run past the array.

num_edges_ is also changed from int32_t to uint32_t, since a negative edge count is meaningless. An int32_t is a signed 32-bit number, which can be negative; a uint32_t is unsigned, so it can only be zero or positive.

  1. The allocation is bounded. Because num_edges_ was only checked for being greater than zero, a crafted num_edges = 0x7FFFFFFF would request a roughly 17 GB allocation, an uncontrolled-allocation DoS on memory-limited hosts. 0x7FFFFFFF is the largest positive value a signed 32-bit number can hold. The fix rejects any count that cannot be backed by the data actually present:
Text
if (num_edges_ > file->RemainingBytes() / sizeof(EDGE_RECORD)) {
  return false;
}

Line by line:

  • file->RemainingBytes() asks how many bytes are left in the file.
  • sizeof(EDGE_RECORD) is the size of one edge record, 8 bytes.
  • Dividing one by the other gives the maximum number of edges the file could possibly contain.
  • If the claimed count is larger than that, the file is lying, and the loader returns false without allocating anything.
  1. The loaded structure is validated. After reading the edges, a one-time pass rejects malformed graphs, any edge whose next_node points outside [0, num_edges_), and any forward-edge run that is not terminated within bounds:
Text
NODE_REF next = next_node_from_edge_rec(edges_[i]);
if (next != 0 && static_cast<uint32_t>(next) >= num_edges_) {
  return false;
}

Line by line:

  • NODE_REF next = next_node_from_edge_rec(edges_[i]); extracts the "next node" reference from edge number i.
  • if (next != 0 && static_cast<uint32_t>(next) >= num_edges_) checks whether that reference points outside the array. Zero is allowed as a special case; anything at or beyond the edge count is not.
  • return false; rejects the file.

Variants to test

The transferable lesson is about where to spend attention on a mature target.

  1. Popularity is not coverage. A high star count says many people use the project; it says nothing about which internal surface has been fuzzed. Look for the gap between heavily used and heavily audited.
  2. Follow the fuzzer, then go where it is not. OSS-Fuzz drives the obvious entry points such as image bytes and network parsers. The neglected corners are the config, model and serialised-blob loaders that everyone assumes are trusted. They are full of file-controlled lengths, counts and offsets feeding allocations and indexing.
  3. Trace the number, not the feature. Walk every attacker-controlled length, count or offset forward to its allocation, memcpy, resize and index sinks. The bug is almost always a missing bound between a value from a file and its use as a size or index.
  4. Clear a real bar. A finding needs a sanitizer-confirmed crash, a minimised input, a root cause at file:line and a taint path from untrusted input to sink. Anything short of that is a lead, not a finding.

Coordinated disclosure

Coordinated disclosure is the practice of telling the maintainer privately first, giving them time to fix the problem, and only then talking about it publicly. It protects users, who get a fix before attackers learn the details.

The repository had no SECURITY.md (a file that explains how to report security problems) and no private vulnerability reporting enabled, a common dead-end. The path that works in that situation, and the one GitHub itself recommends, is to open a public issue with no technical details and let the maintainer open the door. That is what happened: the maintainer responded within hours over a weekend, pointed to a private channel and opened a GitHub Security Advisory.

The full report, root cause, taint path, ASan trace and the 18-byte PoC then went through the private advisory. No public PoC was published, and the issue was assigned CVE-2026-73067.

Glossary

  • AddressSanitizer: a runtime tool that detects reads and writes outside allocated memory and reports them with a file and line number.
  • Allocation: a request to the operating system for a chunk of memory of a given size.
  • API: an application programming interface, the set of functions a library offers to the programs that use it.
  • Availability: whether a system is up and working; a denial of service attacks availability.
  • Bit: a single 0 or 1, the smallest unit of data.
  • Bit field: several small values packed into different ranges of bits inside one number.
  • Bitwise AND: an operation that compares two numbers bit by bit and keeps a 1 only where both have a 1, used here to isolate one flag bit.
  • Byte: eight bits.
  • Commit hash: a unique fingerprint identifying one saved version of source code.
  • Coordinated disclosure: reporting a vulnerability privately to the maintainer first, then publishing after a fix is available.
  • CVE: a public catalogue number for a known security vulnerability.
  • CVSS: a scoring system from 0 to 10 for the severity of a vulnerability.
  • CWE-125: the catalogue code for an out-of-bounds read.
  • DAWG: Directed Acyclic Word Graph, a compact data structure for storing a dictionary as a graph of edges.
  • Denial of service: making a program or service stop working for its legitimate users.
  • Deserialisation: reading saved data back from a file into a program's memory.
  • Deterministic: happening the same way every time, not intermittently.
  • Edge record: one 64-bit entry in a DAWG, packing a character, a next-node reference and flag bits.
  • Fuzzing: feeding a program large numbers of random or malformed inputs to find crashes.
  • Harness: the small piece of code that connects a fuzzer to the program under test.
  • Heap: the pool of memory a program borrows from at runtime for data whose size is decided while it runs.
  • Heap out-of-bounds read: reading memory past the end of an allocated chunk on the heap.
  • LSTM: long short-term memory, the type of neural network Tesseract uses for recognition.
  • Magic number: a fixed value at the start of a file that identifies its format.
  • OCR: optical character recognition, turning an image of text into actual text.
  • OSS-Fuzz: Google's continuously running fuzzing service for open source projects.
  • Out-of-bounds read: reading memory outside the region a program was given.
  • Proof of concept (PoC): a small input or script that reliably demonstrates a bug.
  • Pull request (PR): a proposed change to a codebase, reviewed before it is merged.
  • Qword: an 8-byte (64-bit) chunk of memory.
  • Reachability: whether an attacker can actually get from an entry point to the buggy code.
  • Segmentation fault (SIGSEGV): the operating system stopping a program because it touched memory it does not own.
  • Sink: the dangerous line of code where untrusted data finally causes harm.
  • Source code: the human-readable instructions that make up a program.
  • Taint path: the trail from where untrusted data enters a program to where it is used dangerously.
  • Trained data: the model file (.traineddata) that Tesseract loads to know a language.
  • Unicharset: the list of characters a Tesseract model knows about.
  • Unsigned integer: a whole number that cannot be negative.
  • Vulnerability: a flaw in software that can be abused to cause harm.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.