Skip to content

resolvers: a handful of standalone binary formats - #1629

Open
corkamig wants to merge 4 commits into
google:mainfrom
corkamig:resolvers-expand-binary
Open

corkamig wants to merge 4 commits into
google:mainfrom
corkamig:resolvers-expand-binary

Conversation

@corkamig

Copy link
Copy Markdown
Collaborator

Summary

Expand Magika's native Rust format resolvers (rust/lib/src/resolvers/) with deterministic structural verifiers for 1,698 standalone binary formats (1,697 new content types plus existing catalog-only entry tfrecord), bringing resolver coverage from 310 → 2,008 content types (480 → 2,177 KB entries; 404 → 2,102 exposed labels).

ML model predictions (standard_v3_3), VETOS, existing resolvers, and PRONOM/LoC metadata are untouched.

What changed

  • Resolvers (rust/lib/src/resolvers/):
    • Added pure-Rust declarative byte helpers (hex2bin!, le/be*_bytes!, ebcdic_bytes!) and shared zlib / ASN.1 BER length helpers (zero new crate dependencies).
    • Added 1,486 Tier-1 (magic32.rs) and 62 Tier-2 (magic16.rs) O(1) prefix dispatch entries across 15 category modules (audio: 336, archive: 284, system: 275, document: 143, image: 121, database: 108, model3d: 98, storage: 80, executable: 68, bytecode: 50, serialization: 39, font: 38, video: 34, crypto: 16, network: 8).
    • Structured 223 non-zero-offset / headerless probes in offset_probes.rs as a 4-stage O(1) dispatch (prefix.len() >= 256 fixed-offset switches → >= 12 4-byte offset probes → >= 4 multi-byte probes → rare/headerless fallbacks gated by fast byte/size pre-filters).
    • Extended the 64 KiB prefix read check in resolvers.rs for multi-chunk Unreal Engine 2 .uz2 archives so chunk 2 is verified beyond PREFIX_LIMIT.
  • Fixtures (tests_data/resolvers/fixtures/):
    • Added 1,698 hollowed binary fixtures (310 → 2,008, 1:1 with in_resolvers content types).
  • KB & generated bindings:
    • Added the 1,697 entries to assets/content_types.yaml, updated scripts/sync_kb.py to wrap >100-column generated Rust match arms for rustfmt, and regenerated all KB, Rust, C FFI, Python, JS/TS, and website artifacts via scripts/sync_kb.py.

Review guide

The branch is split into 3 commits mirroring #1606:

  1. tests_data: 1,698 binary fixtures.
  2. rust/lib: hand-written resolver code, O(1) dispatch, and tests.
  3. chore: assets/content_types.yaml, scripts/sync_kb.py, and regenerated bindings/docs.

Verification

  • uv run scripts/sync_kb.py --self-test && uv run scripts/sync_kb.py --check (53/53, all 12 artifacts in sync, frozen snapshots unchanged)
  • cd rust/lib && ./test.sh on both stable and nightly (34/34 tests including all 2,008 fixtures and 15,169 regression cases, rustfmt, clippy --deny=warnings, nightly RUSTDOCFLAGS=--deny=warnings cargo doc)
  • cd rust/ffi && ./test.sh, cd rust/pyo3 && ./test.sh, cd rust/cli && ./test.sh
  • cd python && uv lock --check && uv run ruff check && uv run ruff format --check && uv run ty check && uv run pytest tests -m "not slow" + CLI/module quick tests (41 passed)
  • cd go && go test ./...
  • uv run scripts/check_copyright.py && uv run scripts/check_documentation.py

Add hollowed test fixtures covering all 1,698 newly supported standalone
binary formats across 15 category directories, bringing total resolver
fixture coverage from 310 to 2,008 (1:1 with in_resolvers content types).
Expand the native Rust cascade with structural verifiers for 1,698
standalone binary formats (1,697 new content types plus existing
catalog-only entry tfrecord), bringing resolver-backed content types
from 310 to 2,008:

- Add pure-Rust declarative byte-pattern macros (hex2bin!, le/be*_bytes!,
  ebcdic_bytes!) in magic/mod.rs and shared zlib/ASN.1 BER length helpers
  in magic/verifiers/mod.rs (zero new crate dependencies).
- Add 1,486 Tier-1 (magic32) and 62 Tier-2 (magic16) O(1) prefix dispatch
  entries across 15 category verifier modules.
- Organize 223 non-zero-offset and headerless probes in offset_probes.rs
  into a 4-stage O(1) prefix-length and fixed-offset switch dispatch with
  fast byte/size pre-filters before structural verification.
- Extend the 64 KiB prefix read condition in resolvers.rs for multi-chunk
  Unreal Engine 2 UZ2 archives so chunk 2 is verified past PREFIX_LIMIT.
- Update resolvers_identify_fixtures to assert all 2,008 fixtures.
- Add 1,697 standalone binary content types to assets/content_types.yaml
  (480 -> 2,177 KB entries; 404 -> 2,102 exposed labels including
  existing catalog entry tfrecord).
- Update scripts/sync_kb.py to wrap >100-column generated Rust match arms
  for rustfmt and type CompactContentTypeInfo's label slot as string to
  avoid TypeScript TS2590 union-complexity limits across 2,102 labels.
- Regenerate all KB artifacts, Rust/C/Python/JS bindings, and website
  content-type reference tables via scripts/sync_kb.py.
@corkamig
corkamig force-pushed the resolvers-expand-binary branch from 12b2b9c to 6e55015 Compare November 15, 2026 06:42
@corkamig
corkamig marked this pull request as ready for review November 15, 2026 07:04
- joda_tz: fix the @1/@2 poolSize overlap bug, dispatch both 'C'
  (CachedDateTimeZone) and 'P' (PrecalculatedZone), fully parse
  variable-width DateTimeZoneBuilder millis/UTF records plus optional
  DSTZone tail to exact EOF, and correct the KB description from
  ZoneInfoMap to Joda-Time Compiled Time Zone (DateTimeZone).
- kens_digital_kdm: cap nnotes at 8192 (MAXNOTES), validate trquant
  (1..=64) and non-silent track volumes, verify all visible nttime
  entries are monotonic, bounded, and non-zero, and validate visible
  nttrack/ntfreq/nt*eff byte arrays.
- clarion_mem: enforce Clarion DOS .mem block geometry (size == 6 +
  256*N, N >= 1), validate firstdel and every visible block's nxtblk
  pointer (in-range, no self-loops, no visible free-list cycles), and
  verify printable DOS text payload in block 1.
- Update the three resolver fixtures to full hollowed real samples and
  add unit tests for positive and negative cases.

@reyammer reyammer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: This is a review from yanickf@'s bot, and yanickf@ has reviewed and approved it.

Review Verdict: CONCERNS

1. Verdict, Recommendation & Risk Assessment

  • Verdict: CONCERNS (request changes before merging).
  • What the PR does: Adds deterministic structural verifiers for 1,698 standalone binary formats (1,697 new KB entries plus tfrecord), expanding resolver coverage from 310 → 2,008 content types across magic32.rs, magic16.rs, offset_probes.rs, and 15 verifiers/category/*.rs modules, alongside 1,698 fixtures (23.3 MB on disk) and regenerated Rust/C/Python/JS/website artifacts.
  • What works well:
    • Zero new crate dependencies; compile-time hex2bin!, le/be*_bytes!, and ebcdic_bytes! helpers in rust/lib/src/resolvers/magic/mod.rs are clean and readable, and commit 3d53eb00 nicely tightened joda_tz, kens_digital_kdm, and clarion_mem.
    • Non-matching hot-path latency remains very low (~4.1 µs per 4 KiB binary miss, ~5.5 µs per 4 KiB Python text miss in release builds).
    • sync_kb.py --self-test (53/53), sync_kb.py --check, check_copyright.py, check_documentation.py, cargo test (rust/lib), and go test ./... all pass.
  • Risk Assessment: High.
    1. False positives short-circuit ML inference: Any resolver hit immediately returns that ContentType without model evaluation. Empirical testing against the compiled libmagika reproduced false positives on ANSI-colored CLI/CI logs (cargo, git diff, ls), valid 2-space pretty-printed JSON, TSV files, SPICE netlists, UTF-32LE text, 54 UTF-8 prose prefixes, and 1 in ~40k random / 1 in ~7k sparse binary inputs.
    2. Debug panics & release wraparounds: Three u64 additions (verify_criware_cpk, verify_android_ota, verify_sff) panic in 64-bit debug builds and wrap modulo 2^64 into false positives in release builds; additional usize additions overflow on 32-bit wasm32.
    3. Irreversible API surface: assets/exposed_content_types.txt is append-only monotonic—every added label name is permanent public API across Rust, Python, and JS/TS.

2. Review Findings

1. [design] Permanent Monotonic API Naming, Uncurated PRONOM Batch Metadata, & Direct Conflicts with #1625 / #1630

  • Locations:
    • assets/content_types.yaml / assets/exposed_content_types.txt
    • rust/lib/src/resolvers/magic/verifiers/category/document.rs
    • rust/lib/src/resolvers/metadata.rs
  • Issue:
    1. Irreversible verbose slug names in exposed_content_types.txt: Because exposed_content_types.txt is append-only monotonic, all 1,697 labels become permanent enum variants across Rust (ContentType), Python (ContentTypeLabel), and TypeScript (ContentTypeLabel). Several dozen PRONOM-imported entries slugify full English titles (including redundant _file, _format, and duplicated extension words) instead of Magika's concise canonical style—e.g. chemstation_gas_chromatography_mass_ms, superscape_virtual_reality_format_svr, zoombrowser_ex_thumbnail_cache_info, dna_sequence_chromatogram_file_scf, blitz3d_file_format_b3d (vs b3d/blitz3d), haiku_vector_icon_format_hvif (vs hvif), ros_bag_format (vs rosbag), xar_image_format (vs xara), bim_metadata_file, yglf_file, zisofs_file.
    2. Batch misassignment to group: "document" & category/document.rs: group in assets/content_types.yaml was mapped 1:1 from the fixture/verifier directory, and ~35+ non-document PRONOM formats were placed into document.rs / group: "document"—even when their own mime_type is image/* (atari_mpp image/x-atari-mpp, g9b_bitmap image/x-g9b, gx2_bitmap image/x-gx2, leadtools_cmp image/x-leadtools-cmp, spritepad_spd image/x-spritepad-spd), or when they are audio (asylum_music_format_amf, interleaved_adx_audio_aix), 3D geometry (blitz3d_file_format_b3d, powervr_object_data_pod, superscape_virtual_reality_format_svr), archives/disk images (mar_archive_mac, advanced_forensic_format_aff), or databases (quicken_3_database_file_qst, infofile_flr, portable_database_pdb).
    3. PRONOM/LoC IDs baked into TypeInfo::description: 63 added entries append (..., PRONOM fmt/..., LoC fdd...) directly into description in assets/content_types.yaml (e.g. caf, cdx, ecw, mxmf, asksam, psf, sff, plus 50+ entries in document), whereas main has 0 such descriptions and tracks registry IDs in rust/lib/src/resolvers/metadata.rs (#1618 / #1624).
    4. Over-escaped backslashes in YAML descriptions: 12 entries quadruple-escaped backslashes in YAML (amd_microcode DMA\\\\0, git_pack_idx \\\\xFFtOc, gnunet_gnd, iwlwifi_ucode, kindle_drmion, nintendo_u8, openssh_krl, openzim_zim, quartus_pof, serpent_stone, shinmera_sf3, student_writing_center, zucchini_patch), rendering literal double-backslashes (DMA\\0, \\xFFtOc) in TypeInfo::description and website-ng/src/content/docs/content-types/main.md.
    5. Direct validation conflict with open PR #1625 (and merge overlap with #1630): wcx sets mime_type: "text/x-wildcat-wcx" with is_text: false, and 206 added entries use group: "database" (108) or group: "geometry" (98)—all of which #1625's updated scripts/sync_kb.py explicitly rejects (text/* requires is_text: true, and database/geometry are removed from VALID_GROUPS). #1630 also independently adds hex2bin! and overlapping 04 00 00 00 / 00 00 02 00 dispatch logic.
  • Two-Track Guidance:
    • Option A (Recommended Architectural Path): Rebase after #1625 and #1630 merge, curate the permanent label names and category/group assignments first, move the 63 PRONOM/LoC IDs from description into rust/lib/src/resolvers/metadata.rs, and split this 1,698-format expansion into smaller category- or tier-scoped PRs (with an automated Monte Carlo random/sparse/UTF-8 false-positive test in rust/lib) so human review can verify every permanent label and format spec.
    • Option B (If keeping a single batch PR): Before merging, audit and rename the verbose PRONOM-slugged labels while they are still pre-merge, move non-document formats out of document.rs / group: "document", strip PRONOM fmt/... from content_types.yaml descriptions (or move to metadata.rs), fix the 12 double-escaped descriptions, fix wcx (application/x-wildcat-wcx or is_text: true) + VALID_GROUPS alignment with #1625, and add automated random/UTF-8/sparse-binary false-positive tests in rust/lib.

2. [high] Unchecked 64-Bit u64 & 32-Bit (wasm32) usize Addition Overflows (Debug Panics + Release Wraparound False Positives)

  • Locations:
    • rust/lib/src/resolvers/magic/verifiers/category/archive.rs:1740 (verify_criware_cpk)
    • rust/lib/src/resolvers/magic/verifiers/category/storage.rs:516 (verify_android_ota)
    • rust/lib/src/resolvers/magic/verifiers/category/system.rs:4326 (verify_sff)
    • rust/lib/src/resolvers/magic/verifiers/category/archive.rs:5354-5357 (verify_unity_webdata)
    • rust/lib/src/resolvers/magic/verifiers/category/crypto.rs:359,363 & verifiers/mod.rs:39-52 (verify_kerberos_kirbi / parse_asn1_ber_len)
    • rust/lib/src/resolvers/magic/verifiers/category/system.rs:758 (verify_amd_cpu_microcode), archive.rs:3460 (verify_mpq), executable.rs:1974 (verify_playstation_psp_pbp)
  • Explanation & Verified Triggers:
    • 64-bit panics & release wraparound false positives (all three confirmed panicking with MAGIKA_STATUS_PANIC in debug builds and falsely matching in release builds):
      1. verify_criware_cpk (archive.rs:1740): utf_size = le64(prefix, 8)? -> 16 + utf_size <= size. Input b"CPK \x00\x00\x00\x00\xf0\xff\xff\xff\xff\xff\xff\xff@UTF" + [0; 44] (64 B) panics in debug and wraps 16 + 0xFFFF_FFFF_FFFF_FFF0 == 0 <= 64 -> Some(Label::Cpk) in release.
      2. verify_android_ota (storage.rs:516): manifest_size = be64(prefix, 12)? -> manifest_size + 20 <= size (also missing starts(prefix, b"CrAU")). Input b"CrAU\x00\x00\x00\x00\x00\x00\x00\x02\xff\xff\xff\xff\xff\xff\xff\xf0" + [0; 44] panics in debug and wraps to 4 <= 64 -> Some(Label::AndroidOta) in release.
      3. verify_sff (system.rs:4326): index_offset = be64(prefix, 8)? -> index_offset + index_length <= size. Setting index_offset = 0xFFFF_FFFF_FFFF_FFF0 and index_length = 16 on a 64-byte .sff header panics in debug and wraps to 0 <= 64 -> Some(Label::Sff) in release.
    • 32-bit (wasm32) usize overflows & broken guard:
      4. verify_unity_webdata (archive.rs:5354-5357): evaluates header_len >= name_start + first_name_len before (1..=256).contains(&first_name_len) (overflowing 32-bit usize when first_name_len >= 0xFFFF_FFE0), and || size <= 4096 on line 5357 disables the first_off + first_size <= size check on all files <= 4 KiB.
      5. verify_kerberos_kirbi (crypto.rs:359,363): parse_asn1_ber_len accepts 4-byte BER lengths (0x84, up to 0xFFFF_FFFFusize), so seq_off + app_content_len and seq_len_bytes + 1 + seq_content_len overflow 32-bit usize.
      6. verify_amd_cpu_microcode (system.rs:758, CONTAINER_HDR_LEN + eq_len + 8 when eq_len = 0xFFFF_FFF0), verify_mpq (archive.rs:3460, header_offset + 32 when size > 4 GiB), and verify_playstation_psp_pbp (executable.rs:1974, sfo_offset + 4 when size > 4 GiB) similarly overflow 32-bit usize.
  • Fix: Use checked_add on u64 (16u64.checked_add(utf_size).is_some_and(|e| e <= size), etc.), bound first_name_len / eq_len before adding constants (and drop || size <= 4096 in verify_unity_webdata), and return Option<(usize, u64)> from parse_asn1_ber_len.

3. [high] verify_ansi_csi_art Tautology Misclassifies Colored Terminal / CI Logs (cargo, git diff, ls) as Binary Image Art

  • Locations:
    • rust/lib/src/resolvers/magic/verifiers/category/image.rs:1551-1560
    • rust/lib/src/resolvers/magic/offset_probes.rs:346
    • rust/lib/src/resolvers/magic/mod.rs:451-453
  • Explanation & Verified Trigger:
    verify_ansi_csi_art checks starts(prefix, b"\x1b["), a second b"\x1b[" in prefix[2..64], and then calls require!(has_non_ascii_text_byte(prefix.get(..prefix.len().min(512))?)). Because has_non_ascii_text_byte returns true for any byte outside 0x20..=0x7E | \t | \n | \r—which includes 0x1B (ESC) at prefix[0]—that require! is 100% tautologically true.
    • Verified against libmagika:
      • b"\x1b[1m\x1b[32m Compiling\x1b[0m magika v2.0.0 (/home/user/magika)\n" -> ansi_csi_art (group: "image", is_text: false)!
      • b"\x1b[1mdiff --git a/foo.rs b/foo.rs\x1b[m\n\x1b[1mindex 1234567..89abcdef 100644\x1b[m\n" -> ansi_csi_art!
      • b"\x1b[0m\x1b[01;34msrc\x1b[0m\n\x1b[01;32mtest.sh\x1b[0m\nCargo.toml\nREADME.md\n" -> ansi_csi_art!
    • (Note: verify_perq_pos_seg at executable.rs:1943 has the same tautology because prefix[0..2] are < 0x20, and hundreds of other new verifiers call has_non_ascii_text_byte(prefix.get(..N)?) over a slice that already starts with NUL/binary magic bytes.)
  • Fix: Require genuine non-UTF-8 CP437 extended-ASCII block/box-drawing bytes (!is_utf8_text_header(prefix, prefix.len()) plus CP437 drawing bytes 0xB0..=0xDF / 0xFE, or a "SAUCE00" trailer in ctx.tail) rather than has_non_ascii_text_byte on \x1b[.

4. [high] Plain ASCII, JSON, TSV & Valid UTF-8 Text False Positives (miff, pfm, phm, graoumf_gt2, manuscript, and 54 Printable-ASCII magic32 Keys)

  • Locations:
    • rust/lib/src/resolvers/magic/magic32.rs:2074 & verifiers/category/image.rs:2653-2664 (verify_magick_miff)
    • rust/lib/src/resolvers/magic/verifiers/category/image.rs:2982-3108 (verify_pfm, verify_phm)
    • rust/lib/src/resolvers/magic/verifiers/category/audio.rs:2461-2469 (verify_graoumf_tracker_module)
    • rust/lib/src/resolvers/magic/verifiers/category/document.rs:1303-1313 (verify_lotus_manuscript)
    • 54 printable-ASCII magic32 keys guarded solely by has_non_ascii_text_byte (e.g. document.rs:1910 .scf, image.rs:2757 MSID/msid, archive.rs:2346 DGCA/GCA0, archive.rs:1923 drpm/DLT3, system.rs:5532 HDR2, executable.rs:857 MTLB, database.rs:2659 PWS3, audio.rs:3721 NED:, audio.rs:4354 Ptf /ptf , audio.rs:5360 TFMX/tfmx, etc.)
  • Explanation & Verified Triggers:
    1. 2-space JSON stolen by miff (magic32.rs:2074): &[0x7B, 0x0A, 0x20, 0x20] is b"{\n " (standard 2-space pretty-printed JSON, which resolvers.rs:54 also expands to 64 KiB!). Every 2-space JSON file now scans up to 64 KiB for b"id=ImageMagick" at Tier 1, and valid JSON {\n "html": "<p class=\"x\">",\n "sig": "id=ImageMagick"\n}\n is misclassified as miff instead of json.
    2. 100% printable ASCII text stolen by pfm, phm, graoumf_gt2, and manuscript (all verified live):
      • b"PF\n10 20 30\nPlain ASCII text table\n" -> pfm; b"PH\n 1 2 . Plain ASCII notes here\n" -> phm (scale parser accepts bare "." or "0" and never checks binary float raster payload or size == hdr + w * h * ch * {4,2}).
      • b"GTK\t3.24.41\tGNOME Toolkit cross-platform widget library for Linux desktops\n" -> graoumf_gt2 ((1..=9).contains(&u8_at(prefix, 3)) accepts 0x09 == '\t', matching TSV rows starting with GTK\t or GT2\t!).
      • b"*R1\r\nV1 1 0 DC 5\r\nR1 1 0 1k\r\n.END\r\n" (SPICE netlist / CRLF list) -> manuscript.
    3. Valid UTF-8 text/code stolen by has_non_ascii_text_byte across 54 ASCII magic32 keys: has_non_ascii_text_byte returns true on any byte >= 0x80, which includes every valid UTF-8 multibyte character (—, é, “, CJK). Thus CSS ".scf { /* — */ color: red; }" matches dna_sequence_chromatogram_file_scf, French prose "DGCA — résumé of French civil aviation guidelines (2026)\n" matches gca, "MSID — Mobile Station ID\n" matches sid (where || has_non_ascii_text_byte in image.rs:2769 bypasses the version check!), "HDR2 — ..." matches xiaomi_hdr, "NED: “I don’t think so...”" matches ned, etc.
  • Fix:
    • Remove b"{\n " from magic32.rs (or verify { ... } closes before id=ImageMagick and reject JSON "key": syntax).
    • Validate real binary header fields on pfm/phm (valid float + raster size/binary bytes), graoumf_gt2 (GT2/GTK header fields, where GT2 version is 1..=5, not \t), manuscript (\ directives), .scf (128B Staden header), MTLB (le64(16) == Some(size)), mrsid (drop || has_non_ascii_text_byte), etc., and use !is_utf8_text_header(prefix, prefix.len()) instead of has_non_ascii_text_byte whenever guarding printable-ASCII magics against text.

5. [high] High Random & Sparse-Binary False-Positive Rates in magic16.rs & Headerless offset_probes.rs (Plus cpio Spec Bug)

  • Locations:
    • magic16.rs + verifiers: executable.rs:2095 (verify_tds), archive.rs:3316 (verify_lzsa_compressed), archive.rs:4065 (verify_pea_archive), archive.rs:1690 (verify_cpio_binary), archive.rs:3231 (verify_lzf)
    • offset_probes.rs + verifiers: audio.rs:2363 (verify_game_music_creator), storage.rs:1498 (verify_simh_tape), system.rs:4036 (verify_realtek_wifi_firmware), audio.rs:730 (verify_ac1d_packer), executable.rs:1391 (verify_hp2100_abs), bytecode.rs:1364 (verify_v8_bytecode)
  • Empirical Evidence (1.3M-buffer Monte Carlo test on release libmagika):
    • On 1,000,000 uniform random buffers, newly added verifiers produced 25 false positives (tds: 18, lzsa: 6, lzf: 1):
      • verify_tds (executable.rs:2097): checks only the 2 bytes FB 52 + size >= 16 (87.2% conditional hit rate -> 1 in 75,000 random files!).
      • verify_lzsa_compressed (archive.rs:3323): when (flags & 0x18) == 0 && (flags & 0xE0) >= 0x20 (21.9% of bytes; LZSA only defines versions 1 and 2, i.e. 0x20 | 0x40), blk1_len and size are completely ignored (1 in ~300,000 random files!).
      • verify_pea_archive (archive.rs:4069): checks only EA 01 [00|01] + size >= 10 (21.8% of EA 01 inputs, including x86 16-bit JMP ptr16:16 stubs; ignores @3..10 header and "POD\0" at @10).
      • verify_lzf (archive.rs:3231): missing starts(prefix, b"ZV"), never checks chunk_end <= size (b"ZV\x00ABCD" of 7 B matches with us = 16,706 > 7!) or next "ZV" chunk header.
      • verify_cpio_binary (archive.rs:1692-1699): checks only C7 71 00 00 / 71 C7 00 00 (h_dev == 0), which both false-positives on 15.6% of sparse 71 C7/C7 71 buffers (and x86 mov [rcx+0], imm32) and falsely rejects almost all real Unix/Linux cpio -o -H bin archives where h_dev = st_dev != 0 (leaving magic16.rs:122-123 completely dead since magic32.rs already claims C7 71 00 00 / 71 C7 00 00)!
    • On 300,000 sparse binary structs, newly added offset_probes.rs verifiers produced 42 false positives (game_music_creator: 25, simh_tap: 11, realtek_wifi_fw: 3, hp2100_abs: 2, gt_game_systems_dux: 1):
      • verify_game_music_creator (audio.rs:2363): any >= 1,468 B zero-filled buffer with one non-zero u16 sample length and @243 in 1..=100 matches (0.is_multiple_of(1024) passes all zero pattern offsets; sample/pattern byte sum vs size is unchecked).
      • verify_simh_tape (storage.rs:1498): accepts [N, ..., N, 0] (SIMH_TAPE_MARK == 0), skips simh_record_end and len <= MAX_SIMH_RECORD_LEN when record 2 exceeds prefix.len(), and misclassifies 68-byte BOM-less UTF-32LE plain text " hello world!\n" as simh_tap!
      • verify_realtek_wifi_firmware (system.rs:4054, branch 1b): only ~37 bits of constraint (@32..36 == [0xFF, 1..=16, 0, 0], @9 in 1..=8, @5 <= 16) with no chip ID or section-size sum check.
      • verify_ac1d_packer (audio.rs:730): @0 < 0x20 (allowing 0, invalid in AC1D), @2..4 == 0xAC1D, and be32(4) < size (0 bits on zeroed @4..8 or any file >= 4 GiB -> 19 bits total!).
      • verify_v8_bytecode (bytecode.rs:1364): @1 in 1..=15, @2..4 == [0xDE, 0xC0] (20 bits) without checking V8's header_size + payload_length == size.
  • Fix: Tighten each verifier with its format's structural invariants (hdr_cpio mode/namesize/NUL-terminated path + filesize for cpio; TD16 symbol/pool header for tds; LZSA v1/v2 + bounded block chain + 00 00 00 EOD; PEA "POD\0" stream header; LibLZF chunk closure; GMC pattern+sample size accounting; multi-record + non-UTF-32LE + non-zero payload invariants for simh_tap; rtw89 chip ID + section lengths; AC1D sample/pattern pointer tables; V8 payload_length check).

6. [high] PREFIX_LIMIT = 4096 Truncation Bugs (verify_innodb_tablespace Dead on Real 16 KiB MySQL .ibd Files, Plus 5 Unreachable/Truncated Paths)

  • Locations:
    • rust/lib/src/resolvers/magic/verifiers/category/database.rs:2126 (verify_innodb_tablespace)
    • rust/lib/src/resolvers/magic/verifiers/category/system.rs:3070-3073 (verify_mediatek_signed_image)
    • rust/lib/src/resolvers/magic/verifiers/category/system.rs:3804-3812 (verify_qca_bt_tlv)
    • rust/lib/src/resolvers/magic/verifiers/category/document.rs:2616-2618 (verify_turbopower_tphelp2)
    • rust/lib/src/resolvers/magic/verifiers/category/crypto.rs:446 (verify_supp_510_pkg)
    • rust/lib/src/resolvers.rs:60 vs verifiers/category/archive.rs:5398 (verify_unreal_uz2)
  • Explanation & Verified Trigger:
    1. verify_innodb_tablespace (database.rs:2126): Default MySQL/MariaDB .ibd files use page_size = 16,384 bytes and start with a non-zero 4-byte page checksum (FIL_PAGE_SPACE_OR_CHKSUM at @0..4). Thus resolvers::identify caps prefix.len() at PREFIX_LIMIT = 4096, and line 2126 (be32(prefix, page_size - 4) == Some(lsn as u32) at @16380) always returns None.
      • Why the fixture test missed this: tests_data/resolvers/fixtures/database/innodb_tablespace.ibd (131,072 B) had @0..4 zeroed to 00 00 00 00 during hollowing, which accidentally triggered ISO-9660's size >= 0x8006 && p.starts_with(b"\0\0\0\0") 64 KiB read in resolvers.rs:55! Patching @0..4 of that fixture to DE AD BE EF immediately causes identify to return unknown (verified live).
    2. verify_mediatek_signed_image (system.rs:3070): Checks prefix.len() >= 0x4048 (16,456 > 4096) with no 64 KiB extension for b"BFBF" | b"SSSS" in resolvers.rs — dead branch.
    3. verify_qca_bt_tlv (system.rs:3805): require!(pos + 12 <= prefix.len()) inside the while pos < prefix.len() loop returns None instead of breaking when a >4 KiB NVM file has a tag straddling byte 4096.
    4. verify_turbopower_tphelp2 (document.rs:2616) & verify_supp_510_pkg (crypto.rs:446): Both allow table sizes that push rec_start / cert_off past 4096 (highest <= 4096, count <= 4096), then unconditionally fail when rec_start + 6 > prefix.len() or cert_off + 6 > prefix.len().
    5. verify_unreal_uz2 (resolvers.rs:60 vs archive.rs:5398): verify_unreal_uz2 accepts any valid zlib CMF (0x08..=0x78), whereas resolvers.rs:60 only extends prefix to 64 KiB when p[8] == 0x78.
  • Fix: Guard be32(prefix, page_size - 4) in verify_innodb_tablespace with page_size <= prefix.len() while checking page-0 invariants inside @0..112 (FIL_PAGE_PREV == 0xFFFF_FFFF at @8..12, FIL_PAGE_NEXT == 0xFFFF_FFFF at @12..16, @26..34 == [0; 8], FSP list base nodes); fix the 4096 boundary handling in the other 4 verifiers and align resolvers.rs:60 with is_valid_zlib_header.

7. [medium] Metaformat Precedence Violations (asn1, isobmff, ar) & < 256-Byte ASN.1 DER Bug

  • Locations:
    • rust/lib/src/resolvers/magic/verifiers/mod.rs:19-22 (policy)
    • network.rs:257-267 (verify_tls_session_net443) & system.rs:3553-3563 (verify_pkcs15_ky) + offset_probes.rs:446,448
    • crypto.rs:355-375 (verify_kerberos_kirbi), crypto.rs:323-334 (verify_jumbf_c2pa), video.rs:609-622 (verify_redcode_r3d_offset), archive.rs:5780-5797 (verify_zos_ebcdic_ar)
  • Explanation:
    verifiers/mod.rs:19-22 states that any subformat of ar, asn1, isobmff, etc. MUST live in verifiers/meta/<metaformat>.rs rather than category/. Placing verify_tls_session_net443 and verify_pkcs15_ky in category/ + offset_probes.rs (@4..8) forced both to hardcode u8_at(prefix, 1)? == 0x82 (2-byte DER length, valid in DER only for >= 256-byte payloads; both fixtures use illegal 30 82 00 00 headers!), rejecting valid < 260-byte 30 81 <len> / short-form DER SSL_SESSION tickets and PKCS#15 TokenInfo files. Additionally, verify_tls_session_net443 hardcodes TLS 0x0304 + cipher 0x1301 (TLS_AES_128_GCM_SHA256), rejecting TLS 1.2 and other TLS 1.3 cipher suites.
  • Fix: Move verify_tls_session_net443 and verify_pkcs15_ky into verifiers/meta/asn1.rs using read_tlv (broadening SSL_SESSION protocol/cipher validation and fixing the two 30 82 00 00 fixtures), and consolidate verify_jumbf_c2pa / verify_redcode_r3d_offset (meta/isobmff.rs) and verify_zos_ebcdic_ar (meta/ar.rs).

8. [medium] Unvalidated 4-Byte Magics, Discarded Checks, Dead/Missing Dispatch Arms, & >= 4 GiB Truncations

  • Locations & Details:
    1. Zero-check / discarded-field verifiers:
      • document.rs:973-975 (verify_dos_eps): checks 0 bytes of prefix (size >= 30 && prefix.len() >= 30), missing both starts(prefix, &[0xC5, 0xD0, 0xD3, 0xC6]) and DOS EPS offset/length validation (ps_off >= 30, ps_off + ps_len <= size).
      • image.rs:3751-3759 (verify_sunras): reads let _ = be32(prefix, 4/8/12/20)?; and discards all four fields without checking width/height (> 0), depth (1|4|8|16|24|32), or type (0..=5 | 0xFFFF).
      • document.rs:1000-1007 (verify_express_publisher bare 0xCAFEBEEF), document.rs:2388-2395 (verify_screenwriter "SCRI" + any NUL in 4..16), system.rs:2487-2496 (verify_java_webstart_idx 6-byte numeric check), plus bare 4-byte magics in archive.rs:1989 (ecm), archive.rs:5715 (yz1\x01), document.rs:872 (wpsplus), document.rs:1618 (evy), document.rs:2066 (MAR\x80), document.rs:2170 (CE 19 CE 19), document.rs:2238 (vips_image_v).
      • ~25 verifiers omit starts(prefix, MAGIC) inside verify_* (e.g. keepass, tensorstore_ocdbt, ruby_yarb, os2_help_inf, linux_psf1/psf2, cri_hca, mo3, godot_pck, valve_vpk, unreal_package, etc.), leaving @0..4 untracked by super::probe.
    2. Dead / mismatched dispatch arms:
      • magic16.rs:187 dispatches &[0x00, 0xFE] to verify_ms_works_dos_wps, which hardcodes u8_at(prefix, 0)? == 0x01 at document.rs:1528.
      • magic16.rs:194 dispatches b"S." to verify_palladix_pcs (audio.rs:3979-3993), which has no "S." branch and unconditionally returns None.
      • magic32.rs:1316-1317 dispatches b"JISO" | b"ZISO" to verify_cso_container (storage.rs:758), which hardcodes starts(prefix, b"CISO").
      • Conversely, implemented branches in system.rs:1430 (b"BIC "), image.rs:3213 / archive.rs:4664 (b"GBIX"), network.rs:241 (b"NETX"), database.rs:2664 (b"PWS2"), and archive.rs:5774 (b"\xFE\x07\x01") have no matching dispatch keys in magic32.rs / magic16.rs.
    3. size as u32 / size as usize truncations on >= 4 GiB files:
      • audio.rs:2224 (verify_fm_towns_euphony), audio.rs:5579-5580 (verify_voodoo_vss), bytecode.rs:1250 (verify_torquescript_dso), and font.rs:955 (verify_riscos_outlines) cast size as u32 (wrapping at 4 GiB on all platforms); storage.rs:1662 (verify_ucsd_vol) and magic/mod.rs:444,461 (is_utf8_text_header / is_mostly_printable_header) cast size as usize (wrapping on wasm32).

9. [medium] tests_data/resolvers/fixtures/ Adds 23.3 MB of Uncompressed Zero-Filled Files to Every Checkout

  • Locations: tests_data/resolvers/fixtures/ (29 files >= 64 KiB, including system/ps2_vmc.ps2 = 8,388,640 B [32 non-zero bytes], archive/cigames_dpk4.dpk = 3,669,996 B [10 non-zero bytes], storage/alto_dsk.dsk = 2,601,648 B [11 non-zero bytes], executable/hermes.hbc = 962,704 B, storage/c1581_d81.d81 = 819,200 B, serialization/unreal_usmap.usmap = 640,482 B, video/wink_wtp.wtp = 591,680 B, archive/sega_afs.afs = 524,320 B, bytecode/quake3_qvm.qvm = 467,116 B)
  • Explanation: Although zlib packs zero runs tightly in .git, every git checkout, worktree, CI job, and source archive materializes 23.29 MB of zero-padded files on disk (94× the existing 310 fixtures' 247 KB, and in sharp contrast to #1630's 8.5 KB total across 30 fixtures).
  • Fix: For formats where offsets/lengths are header fields (cigames_dpk4, hermes, unreal_usmap, wink_wtp, sega_afs, quake3_qvm, etc.), craft minimal < 4 KiB fixtures with small offsets; for fixed-disk-size formats (ps2_vmc, alto_dsk, c1581_d81, ibm_3740), either construct vec![0u8; EXACT_SIZE] in unit tests (as resolvers.rs:554 and 675 already do for Iso and ClarionMem) or store tiny run-length specs like tests_data/resolvers/regressions.json.

10. [nit] Commit Bisectability, PR Description Drift, & Minor offset_probes.rs Inline Pre-Guards

  • Commit order (dcdd6eb6 before 6e550153): Commit 2 (rust/lib) uses 1,697 ContentType::* variants that are not generated in rust/lib/src/content.rs until Commit 3 (chore), so dcdd6eb6 does not compile standalone during git bisect unless squash-merged.
  • PR description drift: Still mentions 3 commits (now 4 with 3d53eb00) and omits mentioning the CompactContentTypeInfo label-slot change (${ContentTypeLabel} -> string for TS2590) in scripts/sync_kb.py:2061.
  • Stage 4 pre-guards (offset_probes.rs:822,828): Adding size == 256_256 inline before verify_ibm_3740 (matching verify_xerox_alto_disk at line 646) and size >= 2739 && (size - 1587).is_multiple_of(1152) before verify_hsc_tracker avoids entering super::probe on every >= 1.5 KiB miss.

3. Questions / Things to Verify

  1. Corpus evaluation (MAGIKA_RULES_DATASET): Was cargo test --release --lib resolvers::tests::dataset -- --ignored --nocapture run against the full evaluation dataset manifest with all 2,008 resolvers active, and what were the validated hit / false-positive / unverified disagreement counts and mean scan latency?
  2. Staging & coordination with #1625 and #1630: Should #1625 (KB schema/group tightening) and #1630 (30 high-cardinality resolvers) merge first, followed by rebasing/splitting this PR to adopt #1625's 13-group taxonomy and curated label names before locking 1,697 labels into exposed_content_types.txt?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants