Repository navigation
feat(uefi): add pure-TypeScript UEFI firmware analysis tools - #12342
Conversation
…extract tools Add a dependency-free rea-uefi provider that maps AMI/Aptio flash images: - inspect_uefi_firmware: aligned _FVH discovery, volume-relative FFS walking, guided section/compression classification, conservative PSP-directory probing, embedded-volume rescan and leftover-region classification; incremental SHA-256 and explicit integrity notes. - extract_uefi_firmware: whole-image/volume/FFS-file/section extraction with LZMA-custom/LZMAF86 and AMD-zlib decoding, SafeOutputTree staging, derivations and extraction_gaps. - UefiArtifactReader + 'uefi' format wiring across inventory/domain/contracts so parsed volumes and extracted PE32/TE files hand off to deep-provider analysis (open_binary -> Ghidra).
Add a pure-TypeScript tool that maps the vendor AMI NVRAM variable stores
(factory-default "StdDefaults" and peers) inside a flash image:
- scan the raw image for NVAR entry chains ("NVAR" + u16 total size +
u32 attribute 0x8[23]FFFFFF + state + NUL-terminated name + data),
- recurse into a container entry whose data is itself an NVAR chain, so the
StdDefaults setup variables surface as depth/parent_offset rows,
- report attributes, state, data range, SHA-256 and trailing padding per entry.
Verified against B550 AORUS Elite V2 FId: one StdDefaults store at 0x37090 with
the 11 expected nested variables (Setup, PlatformLang, AMITSESetup, XhciDID,
GcSensorVarName, PCI_COMMON, SioSetupData, UsbSupport, NetworkStackVar,
SecureBootSetup, Setup). Exposed as MCP tool and inspect-uefi-nvram CLI command.
[Medium impact] The PR adds bounded local firmware analysis to REA's CLI, MCP, and artifact workflows. The repository's coverage requirement must be satisfied before merging: unused LZMA carrier bytes need explicit accounting. Findings
Fix with agent prompt### Issue 1
src/uefi/UefiLzmaWorker.ts:125-127
`UefiLzmaWorker` never checks how many input bytes `decompressFile` used. Appending bytes to a valid LZMA or LZMAF86 stream leaves the decoder's reads unchanged, so it returns the same successful output. If that output contains a complete section chain, inspection and extraction can report `complete` without a gap for the unused suffix. The derivation also names the entire carrier as consumed input.
This violates the repository requirement to preserve omissions and derive completeness from examined bytes. Before merging, retain format-aware consumed-input facts and report unexplained trailing bytes, as the zlib path does.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryAdds local UEFI inspection, extraction, and AMI NVAR tools through CLI and MCP, plus FV/FFS artifact inventory.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[CLI or MCP request] --> B[Shared UEFI service]
B --> C[Serialized provider operation]
C --> D[Bounded image read]
D --> E{Operation}
E -->|NVAR| F[Bounded variable scan]
E -->|Firmware| G[FV / FFS / section scan]
G --> H{Decode handler}
H -->|LZMA or LZMAF86| I[Owned worker]
H -->|AMD zlib| J[Bounded Node decoder]
I --> G
J --> G
G --> K{Inspect or extract}
K -->|Inspect| L[Inventory and coverage]
K -->|Extract| M[Select bytes and gaps]
M --> N[SafeOutputTree staging]
N --> O[Validate receipts and commit]
F --> P[Evidence]
L --> P
O --> P
Reviews (22) · Last reviewed commit: "fix(uefi): preserve nested NVAR chains a..." · Reviewed by Greptile |
… NVRAM bounds - FFS file checksum: verify the two's-complement invariant (payload sum + stored byte == 0 mod 256) instead of comparing sums, and encode the correct complement in the fixture builder. - Compression sections (type 0x01): use the 9-byte header and classify EFI standard compression instead of 'none', so extraction reports a gap rather than publishing compressed bytes as a raw section. - GUID-defined sections: derive GUID/data-offset/attributes from the parsed common header size (compact or extended) and reject out-of-range payload offsets. - AMI NVRAM: bound recursive chains to the enclosing container's data end and report partial coverage when a valid nested chain is cut by max_depth.
…e, mark truncation - LZMA worker: enforce max_output_bytes while decoding through a bounded output sink, so an oversized stream is rejected during expansion instead of after a full decompression plus a second Buffer copy. - Provider: serialize admitted operations (the promised single decode-worker lane must not become one worker per overlapping call) and apply one whole-request deadline that covers every decode stage, not a fresh per-stream timer. close() drains the queue and the resource scope. - Scan: track truncated sections of known type and report coverage partial instead of complete when a section declares more bytes than are present.
…der omissions - Queue: check the caller signal before enqueue and when a job reaches the head, and race the queued promise against abort so a cancelled wait returns immediately instead of blocking behind the active request. - Deadline: track the internal deadline and return AnalysisTimeoutError instead of the AnalysisCancelledError that runOwnedCommand reports for any external abort, preserving the real failure reason for CLI/MCP callers. - CapabilityInventory: treat inspect_uefi_nvram like the other bundled rea-uefi tools so discovery does not demand Unblob for it. - UefiArtifactReader: report image truncation through onOmission so inventory coverage reflects the unread suffix even when no volume was found.
…meout cleanup - #raceWithAbort only returns early for jobs that have not started; once a request is running, await it so worker cleanup and completed output are preserved instead of being discarded by a bare cancellation. - Reclassify a deadline-induced cancellation as AnalysisTimeoutError while keeping its cause and cleanup observations, and never override a different primary failure.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d353107119
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6c2024b5c1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 83662cd1da
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7ec2d90fe2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 75fd32b7cb
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e8316a9bb1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
# Conflicts: # src/artifacts/inventory/classify.ts
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a95a9b6168
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
🎉🎉🎉 |
| ); | ||
| const decoded = output.getBuffer(); | ||
| if (declaredOutput !== null && BigInt(decoded.length) !== declaredOutput) { |
There was a problem hiding this comment.
UefiLzmaWorker never checks how many input bytes decompressFile used. Appending bytes to a valid LZMA or LZMAF86 stream leaves the decoder's reads unchanged, so it returns the same successful output. If that output contains a complete section chain, inspection and extraction can report complete without a gap for the unused suffix. The derivation also names the entire carrier as consumed input.
This violates the repository requirement to preserve omissions and derive completeness from examined bytes. Before merging, retain format-aware consumed-input facts and report unexplained trailing bytes, as the zlib path does.
Context Used: AGENTS.md (source)
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/uefi/UefiLzmaWorker.ts
Line: 125-127
Comment:
**LZMA trailing bytes disappear**
`UefiLzmaWorker` never checks how many input bytes `decompressFile` used. Appending bytes to a valid LZMA or LZMAF86 stream leaves the decoder's reads unchanged, so it returns the same successful output. If that output contains a complete section chain, inspection and extraction can report `complete` without a gap for the unused suffix. The derivation also names the entire carrier as consumed input.
This violates the repository requirement to preserve omissions and derive completeness from examined bytes. Before merging, retain format-aware consumed-input facts and report unexplained trailing bytes, as the zlib path does.
**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Summary
Add a bundled UEFI firmware provider to REA:
inspect_uefi_firmware,extract_uefi_firmware, andinspect_uefi_nvram, with FV/FFS artifact inventory and a separateopen_binarystep for extracted, supported executable payloads.Problem and expected behavior
Vendor UEFI flash images (for example AMI Aptio on AM4 boards) need firmware-volume / FFS / section cartography, byte-extraction with provenance, and reading of the vendor NVRAM setup store — without depending on external tools that only carve generic blobs (Binwalk/Unblob) and do not understand UEFI structures. REA had no native UEFI parser.
Expected: map the FV/FFS/section tree with explicit limits and integrity notes, extract selected bytes with digests/ranges/derivations and explicit decode gaps, and parse AMI
NVARvariable stores as observations.Change and scope
src/uefi/: firmware volumes, FFS files, section chains, GUID/section typing, embedded-volume rescan, conservative PSP-directory probing,UefiGuid,UefiImageScan, an ownedUefiLzmaWorker(pinnedlzma-purejs) plusnode:zlibfor AMD-zlib, and an AMI NVRAM (NVAR) parser.inspect_uefi_firmware,extract_uefi_firmware,inspect_uefi_nvram; CLIinspect-uefi-firmware,extract-uefi-firmware,inspect-uefi-nvram.UefiArtifactReaderand'uefi'format wiring across inventory/domain/contracts so parsed PE32/TE files hand off toopen_binary.src/uefi/*.test.ts,tests/boundary/uefi/,tests/acceptance/uefiFirmware.test.ts,tests/fixtures/uefiImage.ts.Intentionally not included: no target execution or emulation, no writes into the source image, no vendor-specific proprietary decompressors beyond recognized-with-gaps classification, and no extraction of code that requires keys/signatures to be bypassed.
Contract and boundary impact
node:zlib.extraction_gaps. Original image ranges are present for flash-backed bytes and null for decoded bytes; runtime addresses staynullbecause they are not statically proven.package.jsonaddslzma-purejsand refreshes the verified runtime notices. Catalogs and skills are generated.Expected effects (check known effects; use documentation-only on its own):
Evidence and regression coverage
src/uefi/unit tests (FFS, sections, volume, GUID, image scan, provider, NVRAM, artifact reader),tests/boundary/uefi/,tests/acceptance/uefiFirmware.test.ts, synthetic fixtures intests/fixtures/uefiImage.ts.FIdimage):inspect_uefi_firmware— 11/11 firmware volumes,coverage: complete,entry_basis: amd-psp-first, 5 PSP tables, 0 integrity issues.inspect_uefi_nvram— oneStdDefaultsstore at0x37090with the 11 nested setup variables (Setup, PlatformLang, AMITSESetup, XhciDID, GcSensorVarName, PCI_COMMON, SioSetupData, UsbSupport, NetworkStackVar, SecureBootSetup, Setup).[ {"name":"Setup","next":18,"attributes":131,"guid_index":3,"data_offset":17,"data_length":1}, {"name":null,"next":16777215,"attributes":136,"guid_index":null,"data_offset":28,"data_length":2} ]Validation performed
The review follow-up adds a shared structural budget, stream-relative scan and extraction evidence, portable output names, PI/PSP layout fixes, and retryable provider, reader and publication cleanup. LZMAF86 now restores the complete decoded stream with inverse x86 BCJ before mapping child sections.
82 focused tests passed, including CLI/MCP acceptance, EDK II-generated LZMAF86 extraction, malformed section coverage, pre-commit receipt validation, and ordered descriptor and workspace cleanup retry. The three new regressions reproduced the publication and cleanup defects at
87b24aac4d.In the earlier review revision, 64 streams generated by pinned EDK II BaseTools recovered byte for byte.
At
6c2024b5c1, 159 focused tests passed on macOS, including packaged CLI and MCP extraction with matching selection and digests. The review regressions cover FFS and NV-data siblings, preservation of opaque bodies and uncovered ranges, scoped extraction, and images with no mapped volumes. All three regressions failed atae11bb43a3.check:fastanddocs:checkpassed at6c2024b5c1. The dependency inventory passedlicenses:checkafter mergingmain. The advertised-schema check matched the committed summaries, validated all 259 distinct schemas with the Rust and Python validators, and compiled all 31 patterns with each required engine.At
5f40a6765b, 161 focused tests,check:fast, anddocs:checkpassed on macOS. Both inventory regressions failed at6c2024b5c1. The fixed reader reports unknown coverage at the structural record limit and when a later volume extends past EOF, while retaining earlier completed volume entries.At
90b682239d, 165 focused tests,check:fast,docs:check, and full advertised MCP schema validation passed on macOS. The NVAR prefix and FFS suffix regressions both failed at5f40a6765b. The packaged MCP test checks the linked records, exact byte ranges, and payload SHA-256 digests.At
4bc6afd797, 168 focused tests,check:fast, anddocs:checkpassed on macOS. The audit covered scoped FFS and section suffixes, depth limits, and structural and file budget omissions. Both suffix regressions failed at90b682239d. The extraction tests verify complete coverage for intact siblings and exact gap ranges for affected selections.At
83662cd1da, 1,204 focused tests passed on macOS, including the provider lifecycle inventory, provider capability conformance, and contract-backed CLI parity tests that failed in GitHub Actions.check:fastanddocs:checkpassed. The packaged CLI retained its offset selection flags and rejected incompatible selector combinations.At
7ec2d90fe2, 1,271 focused tests,check:fast, anddocs:checkpassed on macOS. This includes CLI decimal admission and schema parity, readable FFS prefixes with unknown traversal coverage, and independent extraction of a PE32 sibling beside an embedded FV in a decoded stream. Both firmware regressions failed at83662cd1da.At
eb136fe737, 1,270 focused tests,check:fast, anddocs:checkpassed on macOS. Both real decoder limit cases and the unknown-first section chain fixture failed at7ec2d90fe2. The fixed provider reports partial coverage at decode limits and preserves selectable siblings and byte ranges in decoded streams.At
75fd32b7cb, 1,272 focused tests,check:fast, anddocs:checkpassed on macOS. Two synthetic AMD-zlib regressions failed oneb136fe737and now verify that malformed GUID and compression metadata produce exact section gaps while later PE32 sections remain independently extractable with verified digests.At
e8316a9bb1, 1,393 focused tests passed with one existing skip, pluscheck:fastanddocs:checkon macOS. Synthetic regressions cover bounded FV/FFS extents and checksums, NVAR siblings, checksum-gated PSP provenance, guided and typed leaf payload ranges, exact alignment and decode gaps, and native ELF/PE admission through target resolution and packaged CLI inventory. This run included the compiled LZMA worker and packaged firmware CLI/MCP acceptance.At
a95a9b6168, 1,401 focused tests passed on macOS with one existing skip.check:fastanddocs:checkpassed. The tests cover signed guided sections remaining opaque, recovery of active NVAR children after an inactive prefix, the compiled LZMA worker, production zlib paths using shared reply validation, and packaged CLI/MCP acceptance after mergingmain.Compatibility, safety, and release
next,guid_index, and inlineguidinstead of the previous draft fieldstate. Theattributesvalue is the observed 8-bit field.lzma-purejsdependency.Author readiness
Human owner: @bartman081523
Before merge
type(scope): outcome.