← Back to Pull requests

feat(apple): inspect Image4 (IMG4, IM4P, IM4M) firmware containers offline #14907

Closed
unknown closed this pull request without merging on Nov 28, 2026 01:01 UTC
View on GitHub
unknown unknown commented on Nov 27, 2026 14:15 UTC
Author

Summary

Apple ships boot chain components, kernel caches and coprocessor firmware wrapped in Image4: a DER IM4P payload, an IM4M signed manifest, and an IMG4 that bundles both with optional IM4R restore info. REA does not recognize these files today, so inspect-artifact reports a .im4p or .img4 as unknown bytes and there is no offline way to see the payload type, whether it is encrypted, or what the manifest declares.

This adds an apple-img4 artifact format. inspect-artifact and extract-artifact recognize the container from its content (a DER SEQUENCE whose first element is the IA5String IMG4, IM4P or IM4M), report its structure, and expose the payload, manifest and restore info as entries. Nothing is decrypted, decompressed, executed or signature-checked. Discussed in #14934. It is a read-only format-inspection addition within the supported contribution scope.

Problem and expected behavior

Use case: given kernelcache.im4p or a personalized .img4 from a restore bundle, find out what the payload is, whether it is encrypted or compressed, and which chip, board and objects the manifest names, then pull the stored payload out for the Mach-O tools.

Observable outcome:

  • Root format_metadata has kind apple-img4 and magic (IMG4, IM4P or IM4M).

  • payload reports type (such as krnl, ibot), description, the stored offset and length, compression (none, an LZFSE block magic, or complzss), uncompressed_size, payload_magic, encrypted, keybag_count and keybag_types. Keybag IVs and keys are never copied into metadata, limitations or errors.

  • manifest reports version, body properties (CHIP, BORD, ECID, CPRO, SDOM and others), per-object properties with DGST as hex, signature_size and certificate_chain_size.

  • restore_info lists properties_present with values: "redacted".

  • Entries are payload, manifest.der (the IM4M SEQUENCE without the [0] wrapper) and restore-info.der. An encrypted payload is listed and open refuses it. Compressed payloads are returned as stored with compressedSize equal to the stored length.

  • Indefinite or non-minimal lengths, constructed strings, trailing bytes, unknown tags, oversize octet strings or integers, and tag numbers that do not match their entry name are limitations, and coverage is unknown whenever one is present. A truncated value fails the read.

  • Four fixed allowances refuse excessive DER depth (32 levels), element count (4096), retained properties (256) and retained string length (4096 bytes).
  • Change and scope

  • src/domain/apple/image4.ts: the Image4 parser. It walks DER by header, loads nested values up to 256 KiB and walks wider ones by header so a large payload is ranged, not read. It decodes IM4P, IM4M and IM4R, keybags, compression and the four allowances.

  • src/artifacts/Image4ArtifactReader.ts: the positional reader that serves the three entries and refuses an encrypted payload on open.

  • src/domain/asn1Ber.ts: the shared BER header decoding moves into an exported readAsn1BerHeader, which also decodes high-tag-number form (needed for the PRIVATE-class MANB, MANP and BNCN tags) with a 5-octet cap and rejects non-minimal forms. Asn1BerFailure gains a truncated flag set by every failure that means the input ended early. Image4 uses that flag to fail truncated reads instead of matching message text.

  • Format registration: artifactFormats.ts, artifactFormatRecognition.ts, artifactFormatMetadata.ts, firmwareMetadata.ts, targetFormats.ts, artifactGraph.ts, artifactInventoryView.ts, ArtifactReader.ts and the PE overlay format list.

  • Docs: new docs/guides/apple/image4-containers.md, CLI examples in docs/getting-started/cli.md, docs/reference/limits-and-recovery.md, docs/reference/supported-targets.md, the docs index and sidebar, and the skill references under .agents/skills/reverse-engineer-anything/ and .cursor-plugin/. The four allowances are registered in scripts/verify/fixed-ceiling-registry.json, and scripts/ci/scopes.mjs maps the new files.
  • Not included: decryption, LZFSE or LZSS expansion, signature or certificate validation, and decoding IM4R values.

    Contract and boundary impact

  • Semantic owner and earliest changed stage: image4.ts interprets the DER once at recognition; the reader, metadata and inventory view consume its parsed facts.

  • Contribution scope fit and linked maintainer decision: read-only inspection of a local file; not applicable (no target execution, injection, mutation, or protection recovery). Encrypted payloads are refused, not decrypted.

  • CLI and MCP/tool-catalog contract: no new tool or command. inspect-artifact and extract-artifact gain one format, apple-img4.

  • Provider, bridge, target-format, or platform compatibility: one new target format. Existing BER callers (APK v1 signatures, PE certificates) now get a decoded high tag number where they previously failed on high-tag form; their own tag checks are unchanged and their tests pass.

  • Evidence, artifact, provenance, or reconstruction contract: new apple-img4 metadata and entry metadata (decoded: false, unpacked: false).

  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.

  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): none committed; authored skill references updated under .agents/skills/reverse-engineer-anything/ and .cursor-plugin/.
  • Expected effects (check known effects; use documentation-only on its own).
    Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.

  • Launch or attach to a process.

  • Inject instrumentation or run scripts/code.

  • Change process memory, registers, files, or configuration.

  • Contact network services.

  • Recover protected code or work around protections.

  • Documentation or usability only; no target interaction.

  • Not sure yet; investigation or maintainer guidance needed.
  • Evidence and regression coverage

  • Tests added or updated: src/domain/apple/image4.test.ts (21 tests: IM4P, IM4M and IMG4 structure, keybags with and without a decodable layout, compression agreement and disagreement, complzss headers, oversize octet strings and integers, tag-name mismatches, indefinite and non-minimal lengths, trailing bytes, truncation, the four allowances), src/artifacts/Image4ArtifactReader.test.ts and src/artifacts/Image4ArtifactReader.boundaries.test.ts (the three entries per container type, encrypted refusal on open, stored LZFSE and LZVN bytes returned undecoded, truncation, a malformed high tag, each of the four allowances, and indefinite values that are not bounded), src/domain/asn1Ber.test.ts (5 tests: low and high tags, header lengths, malformed high tags, the truncated flag), plus entries in artifactFormatRecognition.test.ts, TargetFormatVocabularies.test.ts and tests/boundary/providers/native/artifactProvider.standaloneFormats.test.ts. Fixtures are built in src/domain/apple/image4.fixture.ts.

  • Base reproduction or other evidence: before this change inspect-artifact does not recognize these files. The CLI output below is executed against this branch.

  • User-visible CLI/MCP output (if applicable): executed on synthetic files built with the fixture helpers (no Apple firmware used).
  • rea inspect-artifact sample.img4 --json on an IMG4 holding an LZFSE krnl IM4P, an IM4M and an IM4R:

    kind: apple-img4, magic: IMG4
    payload: type "krnl", description "KernelCacheBuilder", compression "bvx2", uncompressed_size 4096, encrypted false, keybag_count 0
    manifest: version "0", CHIP "32816", BORD "4", ECID "9007199254740993", CPRO true, SDOM "1", object ibot with DGST, signature_size 15, certificate_chain_size 12
    restore_info: properties_present ["BNCN"], values "redacted"
    entries: manifest.der 247, payload 32 (bvx2), restore-info.der 51; coverage complete
    

    rea extract-artifact sample.img4 --json wrote manifest.der (247 bytes), payload (32) and restore-info.der (51) with containment_verified: true and coverage complete.

    rea inspect-artifact encrypted.im4p --json on an ibot IM4P with two keybags reported encrypted: true, keybag_count: 2, keybag_types: [1, 2]. The JSON contains none of the fixture IV or key bytes. rea extract-artifact encrypted.im4p --json refused with unsupported_target: "Archive entry payload is encrypted; REA does not decrypt archive entries, so the archive cannot be extracted completely".

    rea inspect-artifact deep.im4m --json on an IM4M with 40 nested SEQUENCEs refused with "Image4 DER nesting exceeds 32 levels. This release has no runtime override." and { allowance: "The Image4 DER depth allowance", limit: 32, unit: "levels" }.

  • Remaining proof gaps: no shipped Apple Image4 file was used; all inputs are fixture-built. LZFSE and complzss handling is shown on synthetic headers.
  • Not a boundary fix. The new reader's boundary tests cover truncation, a malformed high tag, the four allowances, and indefinite or trailing data kept as limitations.

    For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.

  • Artifact identity, source provenance, and failed attempts remain preserved.

  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.
  • Validation performed

  • npx vitest run on the seven test files above: 7 files, 143 tests passed.

  • npm run lint: exit 0, including the fixed-ceilings verification.

  • node scripts/rea.mjs inspect-artifact and extract-artifact on the fixture-built files: output as shown above.
  • Compatibility, safety, and release

  • Breaking changes or migration steps: none. readAsn1BerHeader and the truncated flag are additions. In the shared reader, a high-tag-number form is now decoded instead of refused; existing callers match on low tags and are unaffected.

  • Real Hopper/Ghidra, browser, or OS coverage: not applicable. The Image4 reader never calls a decompiler or the OS loader; the tests and CLI runs above used Node 24 on an Apple silicon Mac.

  • Package or release metadata impact: one new artifact format.

  • Security, privacy, process, or containment review: reads a local file through bounded positional reads. Keybag key material and IM4R values are never surfaced. Encrypted payloads are refused on open. DER depth, element count, retained properties and string length are bounded before any per-element work.
  • AI was used for assistance.

    Author readiness

    Human owner: @mvanhorn

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.

  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.

  • I declare this PR ready for initial maintainer review.
  • Author checklist (completed by the PR author before requesting review)

  • This PR addresses a concrete problem or an agreed enhancement.

  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.

  • The PR has one focused outcome and the title follows type(scope): outcome.

  • Related issue is linked, or the reason for not linking one is stated above.

  • Tests cover changed observable behavior and meaningful failure paths.

  • Owning docs, contracts, and generated metadata are updated where needed.

  • User-visible CLI/MCP changes include representative output.

  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

  • I ran every test, build, or measurement needed to validate this change, reported a browser, GPU, or environment gap only when that runtime or hardware is unavailable, and reported the checks I ran and their results without presenting inferred correctness or speedups as measured.

  • Comments explain constraints or non-obvious decisions; task history and conversations stay out of code and docs.

  • Documentation is concise and factual, without punchy slogans or promotional language.

  • This change fixes the root cause and follows the engineering rules in AGENTS.md.

  • Formatted input is interpreted once at the owning boundary, and consumers use the owner's parsed facts. See Interpret boundary facts once.

  • Combined failures preserve partial observations, remaining resources, and cleanup facts. See Own the lifecycle.

  • A hardcoded limit is an REA_ runtime setting with a default, floor, and maximum, unless a fixed ceiling has a stated reason. See Adding a runtime setting.
  • Demo


    !demo
    <video src="https://mvanhorn.github.io/pr-demo-assets/rea/2026-11-27-802-feat-apple-image4-containers/out.mp4" controls width="720"></video>

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: mvanhorn Review duration: 646m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #14907"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%
    Repository