Skip to content

About

tessera - recover the skeleton of an unknown binary container format from a single sample, prove it against permutation controls, and emit a parser. Zero dependencies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Development Experiment 055 — tessera

Recover the skeleton of an unknown binary container format from a single sample, prove it against permutation controls, and emit a parser for it.

Offline. No dependencies — Python 3.11+ standard library only. No model, no network, no corpus.

$ python main.py mystery.bin --ksy recovered.ksy --python recovered.py --extract members/

Thesis

Every tool for exploring unknown binary formats — ImHex, 010 Editor, Kaitai Struct, QuickBMS — is a transcription tool. You work out the layout by hand; the tool renders it or compiles it. The one piece of real automation in the field, BinaryInferno (NDSS 2026), needs a corpus of messages sharing a format and returns a statistical guess about flat fields.

But a container file already contains its own layout. An offset table is a set of integers that are the coordinates of the file they are stored in. A chunk chain is a set of lengths that sum, exactly, to the file's own size. Those are not statistical regularities to be estimated from many samples — they are arithmetic facts that can be checked against one.

So tessera inverts the usual method. Instead of learning what fields look like, it searches for readings of the file under which the file's own numbers turn out to be a partition of the file: extents in bounds, none overlapping, no unexplained gaps, the last one landing exactly on the end. A random file does not do this. The smallest thing that proves the idea is a tool that is handed one PNG, one WAV, one tar, one ICO and one Doom WAD, is told nothing about any of them, and comes back with the layout the specification describes — and is handed compressed data, noise and prose, and comes back with nothing.

Lane: reverse engineering / digital archaeology — untouched by experiments 001–054. Difference from the recent streak: entries 049–054 all parse a known artefact and reason over a fixed rule corpus or arithmetic model. This one has no rule corpus and no known artefact; it searches a hypothesis space for a geometric proof and emits a runnable grammar. It is synthesis, where the streak was audit.


Sample run

Given a PNG and no knowledge of PNG:

$ python main.py samples/png.bin

tessera: samples/png.bin
  1,198 bytes, sha256 ef270d99efdcfb0d...

------------------------------------------------------------------------
[1] PROVEN  chain of 7 records, u32be length at +0
------------------------------------------------------------------------

  Layout    records begin at 0x8; each declares a u32be length at +0 and occupies 12 + length bytes
  Verdict   no control produced any structure at all
  Evidence  P <= 4.2e-20 (raw 5.4e-26 x 768512 hypotheses, -2.77 per unit)
              - 6 in-bounds hops
              - landing on the final byte exactly
              - 7 records sharing a printable 4-byte tag
  Coverage  1,190 of 1,198 bytes (99.3%) in 7 extents
              plus 8 bytes of header and table, for 100.0% of the file accounted for
              no gaps: the extents tile the region exactly
  Ends      exact
  Tags      4-byte ASCII at +4: 'IDAT', 'IEND', 'IHDR', 'tEXt'

  Extents:
       0  0x00000008 .. 0x00000021         25  IHDR
       1  0x00000021 .. 0x0000004D         44  tEXt
       2  0x0000004D .. 0x000001BA        365  IDAT
       3  0x000001BA .. 0x00000327        365  IDAT
       4  0x00000327 .. 0x00000494        365  IDAT
       5  0x00000494 .. 0x000004A2         14  IDAT
       6  0x000004A2 .. 0x000004AE         12  IEND

  Controls
            block    4: 2 block-permuted controls yielded no structure at all
            block  512: 2 block-permuted controls yielded no structure at all

  Search
            chain: 768,512 hypotheses in the space, 587,136 walked
            table: 458,856,762 hypotheses in the space, 0 strided runs examined
            chain encodings skipped as unprovable at this file size: u8
            offset encodings skipped, coordinates too common to be informative:
              u8 (1166 of 1198 positions, 97.3%)
            plausible file coordinates found: u16be=35, u16le=32, u32be=11, u32le=8, u64be=0, u64le=0, u8=1,166

The 8-byte signature, the big-endian length at +0, the 12 bytes of overhead (4 length + 4 type + 4 CRC), and the four-character chunk codes were all recovered from the bytes. --extract writes 0000_IHDR.bin, 0001_tEXt.bin, … 0006_IEND.bin.

A tar archive, with no knowledge of tar, yields the ASCII-octal size field at +124, the 512-byte block structure, the NUL end-of-archive marker — and the archived filenames, recovered as the per-record tag:

[1] PROVEN  chain of 4 records, oct-ascii12 length at +124
  Layout    records begin at 0x0; each declares a oct-ascii12 length at +124
            and occupies 512 + length bytes, padded up to a multiple of 512
  Ends      zero-tail after a 2308-byte NUL tail
  Tags      4-byte ASCII at +0: 'alph', 'beta', 'eps.', 'gamm'

And 60 KB of noise yields NO STRUCTURE FOUND, exit code 3.


How to run

Nothing to install. Python 3.11 or newer.

python main.py FILE                      # analyse and report
python main.py FILE --ksy out.ksy        # emit a Kaitai Struct grammar
python main.py FILE --python out.py      # emit a standalone parser
python main.py FILE --extract members/   # carve the members out
python main.py FILE --json out.json      # machine-readable everything
python main.py FILE --control-rounds 0   # faster, and says so in the report

make test        # 106 tests, ~60 seconds
make samples     # build the example files into samples/
make run FILE=…  # analyse one file

The emitted parser imports nothing and runs on its own:

$ python out.py mystery.bin
   0  entry0           0x0000000C         64
   1  entry1           0x0000004C        201
   …
12 members, 9810 bytes accounted for

Exit codes. 0 structure found · 3 no structure found (an answer, not a failure — the right result for compressed or encrypted data, and distinguishable when sweeping a directory) · 2 the tool could not do its job.


Architecture

                    ┌──────────────┐
   one file ───────▶│   numeric    │  how an integer might be spelled:
                    │              │  u8/u16/u32/u64 × le/be, ASCII octal
                    └──────┬───────┘
                           │
              ┌────────────┴────────────┐
              ▼                         ▼
      ┌───────────────┐        ┌────────────────┐
      │     chain     │        │   directory    │
      │  walk lengths │        │ strided runs   │
      │  RIFF PNG tar │        │ WAD ICO ELF    │
      └───────┬───────┘        └───────┬────────┘
              └────────────┬───────────┘
                           ▼
                    ┌──────────────┐     ┌──────────────┐
                    │    tiling    │◀───▶│ distribution │
                    │ do the       │     │ the file's   │
                    │ extents      │     │ own value    │
                    │ partition?   │     │ histogram    │
                    └──────┬───────┘     └──────┬───────┘
                           ▼                    ▼
                    ┌───────────────────────────────┐
                    │          nullmodel            │
                    │  uniform ∨ empirical, then    │
                    │  Bonferroni over the space    │
                    └──────────────┬────────────────┘
                                   ▼
                    ┌───────────────────────────────┐
                    │   control  +  reproduce       │
                    │  re-run the search on block-  │
                    │  permuted copies; a control   │
                    │  only votes if it destroyed   │
                    │  the finding                  │
                    └──────────────┬────────────────┘
                                   ▼
                    ┌───────────────────────────────┐
                    │  report · emit · extract      │
                    └───────────────────────────────┘

The two skeletons

Chain (chain.py) — each record stores the distance to the next. RIFF/WAV, PNG, IFF, ISO-BMFF, POSIX tar. Four parameters: where the length lives, how it is spelled, the fixed overhead around it, the alignment of the next record. The search enumerates them and walks; almost every walk dies at the first hop. A chain is only accepted when it lands exactly on the end of the file or on a NUL tail.

Directory (directory.py) — the members' coordinates live in one strided table. Doom WAD, ICO, ELF sections, TrueType, most game archives. The hook is a counting argument: in the 60 KB noise fixture there is exactly one position where a u32le reads as a plausible file offset. Finding several at a constant stride, strictly ascending, whose extents then tile the file, is not something byte noise does.

Deciding what to believe

This is where most of the work went, and where the first two designs were wrong.

  1. Uniform null. Charge each constraint at its probability under random bytes, then multiply by the size of the hypothesis space (Bonferroni — a search that tries 768,512 hypotheses has 768,512 chances to be lucky, and quoting the winner's raw p-value would be dishonest). The space size is computed combinatorially, independent of the file, so pruning never flatters a result.

  2. Empirical null (distribution.py). Uniform is wrong for real files. A tar archive is mostly NUL padding, so a two-byte length read anywhere in it is probably zero — and a walk that reads zero and advances by a fixed overhead will march the whole file and land exactly on the terminator. Under the uniform model that is a 1-in-10²⁰⁰ miracle; under the file's own histogram it is the only thing that could have happened. So every term is charged at the larger of its uniform and empirical probability — the weaker claim. Estimates are Laplace-smoothed: with n samples the smallest probability claimed is 1/(n+1), because observing nothing in a bucket is evidence that it is rare, not proof that it is impossible.

  3. Permutation controls (control.py). Both parametric models still overstate, because they assume independence and real bytes are correlated — NULs come in runs. So tessera stops modelling and measures: it builds control files by permuting the original in blocks, and re-runs the identical search on them. A block permutation preserves everything local (histogram, run lengths, entropy, padding, ASCII headers) and destroys exactly one thing: whether a number stored in one part of the file is the true coordinate of another part. Length is preserved and any trailing NUL run is left in place, so the control has the same targets to hit.

  4. Evidence density, not total. A control that produces a long weak structure and a file that produces a short strong one are not comparable on totals — and inflating the total by finding more pieces is exactly the spurious chain's trick. Findings are compared per record.

  5. Admissibility (reproduce.py). A control is only a null hypothesis if it destroyed the thing under test. A 512-byte shuffle demolishes a chunk chain but does almost nothing to a directory: relocating a contiguous table of ascending offsets leaves them contiguous and ascending, and whether the extents tile is arithmetic on the numbers, not a fact about the bytes they point at. A permuted file that still contains the structure is not evidence that the structure is a coincidence — it is a copy of it. So before a control may testify, the finding's own hypothesis is replayed against it; if it still validates, that control's opinion is discarded. Chains end up judged against the coarse permutation, directories against a 4-byte one, and the report names which applied.

A finding must beat the strongest admissible control by six orders of magnitude to be called PROVEN, three to be called LIKELY, and is otherwise discarded.

Two approaches considered, and the trade-off

Rejected: learn field semantics from a corpus — the BinaryInferno approach. Entropy boundaries, type detectors, a ranked guess. It handles formats tessera cannot (flat records with no self-reference) and degrades gracefully. But it needs many samples of the same format, which is precisely what you do not have when you are handed one file out of an archive; and its output is a score, not a proof, so a wrong answer looks exactly like a right one.

Chosen: prove a partition from one sample. Much narrower — it only sees containers whose members are addressed by stored coordinates — but within that range the answer is checkable rather than plausible, it works on a single file, and it fails loudly on everything else. For reverse-engineering work that trade is worth making: a false positive costs a day of chasing a field that is not there, and a tool that says nothing is far cheaper than a tool that says something wrong.

The cost is CPU, not memory: under a second for a small file, ~9 s for the tar fixture, with a default of four extra full searches for the controls. The search is kept affordable by a prune that is derived rather than tuned — the null model is asked, up front, whether an encoding could clear the threshold for a file this size. A one-byte length field in a 60 KB file constrains nothing, so no chain read through it could ever be believed, and it is never walked. Nothing is discarded that could have been reported.


Assumptions and limitations

Stated plainly, because a reverse-engineering tool that overstates its reach is worse than no tool.

Validated against synthetic-but-genuine fixtures, not a corpus of real-world files. The PNG, WAV, tar, ICO and WAD in tests/fixtures.py are real files in real formats, built by the standard library (wave, tarfile, zlib) — the WAV plays, the tar extracts with tar -xf. But they are small and clean. No proprietary game archive, no damaged file and no real-world ELF was available to this offline run, and the tool has not been tried on one.

Only two shapes are modelled. Forward-linked chains and strided offset tables. Not modelled: variable-length directory records (ZIP's central directory, whose entries are 46 bytes plus a filename, is invisible to both engines), relative or sector-scaled offsets, nested containers, bitfield-packed headers, compressed directories, and anything whose members are found by scanning rather than by address.

Absolute offsets only. A table whose values are relative to the table, or in 512-byte sectors, is not found. This is a real gap for CD images and several archive families; the search space was kept narrow deliberately, since each extra degree of freedom multiplies the Bonferroni correction and weakens every verdict in the file.

Narrow length fields cannot be proven. A one-byte length — or a two-byte one in a file larger than 64 KB — carries no in-bounds information, so a chain read through it is unprovable in principle, not merely unfound. The report names every encoding skipped for this reason so a clean negative can be told from a blind spot.

Dense encodings are declined. If more than 5% of scanned positions read as plausible coordinates under some encoding, that encoding is abandoned and named in the report. The counting argument does not hold there, so there is nothing to find — but a directory with very many entries relative to file size could in principle fall foul of this. --max-pointer-density adjusts it.

Tables are looked for in the first and last 4 MB. Enough for every realistic layout, but a table buried in the middle of a very large file is missed.

The controls are a sample, not a distribution. Two permutations per block size by default. More rounds is strictly better evidence and strictly more wall-clock; --control-rounds sets it. At 0 the verdict rests on the parametric bound alone, and the report says so in those words.

Recovered field names are positional. Where a four-character printable tag was found it is used, and the tar run shows why that is worth having. Everything else is entry[3]. The emitted grammar says, in its own header, that it was inferred from one file rather than read from a specification.

--extract writes whatever the layout says. If the layout is wrong the carved files are wrong. That is the point of carving: it is the check a human can make in a second, and it is why the tool offers it.


Layout

file what it does
tessera/numeric.py integer and ASCII-numeric encodings; the fast plausible-coordinate scan
tessera/tiling.py extents, overlaps, gaps — the tiling test
tessera/distribution.py the file's own value histogram, as a second null model
tessera/nullmodel.py probability bounds, Bonferroni correction, the feasibility prune
tessera/chain.py forward-linked chunk chains
tessera/directory.py strided offset tables
tessera/control.py block permutation and adjudication
tessera/reproduce.py whether a control actually destroyed a finding
tessera/analysis.py running both engines and pooling the verdicts
tessera/report.py · emit.py · extract.py text report, .ksy / Python / JSON, carving
tessera/cli.py · main.py command line
tests/ 106 tests: rediscovery, negative controls, components, emitters, CLI

Tests

$ python -m unittest discover -s tests -t . 
Ran 106 tests in 62.213s
OK

The suite is built around two claims that pull against each other:

  • Rediscovery — each real format is recovered with the parameters its specification gives. The assertions name them (len_offset == 124, align == 512, overhead == 12), so a regression says which part of tar or PNG the tool stopped being able to see.
  • Refusal — noise, real compressor output, prose, a flat byte run, an all-NUL file and a compressed WAD all yield nothing. A tool that searches three quarters of a billion hypotheses will find a tiling in anything if it is allowed to.

Plus: the verdict must move with the evidence (a 3-entry ICO is reported LIKELY, an 8-entry one PROVEN); the emitted parser is written out, run in a fresh interpreter, and checked to reproduce the analysis byte-for-byte for all five formats; and two runs over the same bytes must produce identical probabilities.


License

MIT — see LICENSE.

About

tessera - recover the skeleton of an unknown binary container format from a single sample, prove it against permutation controls, and emit a parser. Zero dependencies.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages