Files
reverse-engineering-anything/src/cli.ts
T
bartman081523andmorluto d380dc2409 feat(uefi): add pure-TypeScript UEFI firmware analysis tools (#12342)
* feat(uefi): add pure-TS UEFI firmware volume/FFS parser with inspect/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).

* feat(uefi): add inspect_uefi_nvram for AMI NVRAM variable stores

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.

* fix(uefi): address review on checksums, compression, guided sections, 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.

* fix(uefi): bound decode memory, serialize operations, enforce deadline, 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.

* fix(uefi): cancellable queue, timeout surfacing, availability and reader 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.

* fix(uefi): limit early cancellation to unstarted jobs and preserve timeout 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.

* docs(licenses): record UEFI decoder dependency notices

* fix(uefi): preserve stream provenance and bound firmware analysis

* feat(uefi): decode LZMAF86 guided sections

* fix(uefi): validate publication before commit and order decoder cleanup

* fix(uefi): preserve unsupported volumes and extraction gaps

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-19 21:19:35 +00:00

163 lines
7.0 KiB
TypeScript

import type { FridaInstrumentationPort } from "./ports/frida/FridaInstrumentationPort.js";
import {
CURRENT_ENTRYPOINT_PATH,
isDirectEntrypoint,
} from "./process/CurrentEntrypointPath.js";
import {
CLI_COMMAND_REGISTRATIONS,
CLI_REGISTRATION_ORDER,
type CliCommandModules,
} from "./cli/cliCommandRegistrations.js";
import type { CliResultOutput } from "./cli/cliResultOutput.js";
import { createCliShell } from "./cli/cliShell.js";
import type { CliInstance } from "./cli/types.js";
import { createDirectAnalysis } from "./composition/directAnalysis.js";
import * as setupModule from "./cli/setupCommands.js";
import * as coreAnalysisModule from "./cli/coreAnalysisCommands.js";
import * as reverseEngineeringModule from "./cli/reverseEngineeringCommands.js";
import * as cutterModule from "./cli/cutterCommands.js";
import * as utilityModule from "./cli/utilityCommands.js";
import * as binaryDiagnosticsModule from "./cli/binaryDiagnosticsCommands.js";
import * as wasmModule from "./cli/wasmCommands.js";
import * as apkSignatureModule from "./cli/apkSignatureCommands.js";
import * as captureModule from "./cli/captureCommands.js";
import * as signalModule from "./cli/signalCommands.js";
import * as evmModule from "./cli/evmCommands.js";
import * as desktopApplicationModule from "./cli/desktopApplicationCommands.js";
import * as releaseExposureModule from "./cli/releaseExposureCommands.js";
import * as goModule from "./cli/goCommands.js";
import * as il2cppModule from "./cli/il2cppCommands.js";
import * as modelModule from "./cli/modelCommands.js";
import * as gpuModule from "./cli/gpuCommands.js";
import * as rustModule from "./cli/rustCommands.js";
import * as pythonPycModule from "./cli/pythonPycCommands.js";
import * as nugetNupkgModule from "./cli/nugetNupkgCommands.js";
import * as erlangModule from "./cli/erlangCommands.js";
import * as v8CodeCacheModule from "./cli/v8CodeCacheCommands.js";
import * as mavenGradleMetadataModule from "./cli/mavenGradleMetadataCommands.js";
import * as sqliteModule from "./cli/sqliteCommands.js";
import * as artifactModule from "./cli/artifactCommands.js";
import * as managedModule from "./cli/managedCommands.js";
import * as firmwareModule from "./cli/firmwareCommands.js";
import * as uefiModule from "./cli/uefiCommands.js";
import * as androidModule from "./cli/androidCommands.js";
import * as pcapModule from "./cli/pcapCommands.js";
import * as flutterModule from "./cli/flutterCommands.js";
import * as fridaModule from "./cli/fridaCommands.js";
import * as apktoolModule from "./cli/apktoolCommands.js";
import * as jebModule from "./cli/jebCommands.js";
import * as adbModule from "./cli/adbCommands.js";
import * as browserModule from "./cli/browserCommands.js";
import * as webRuntimeModule from "./cli/webRuntimeCommands.js";
import * as webNetworkCaptureModule from "./cli/webNetworkCaptureCommands.js";
import * as advancedBrowserModule from "./cli/browserAdvancedCommands.js";
import * as browserScenarioModule from "./cliBrowserScenarioCommands.js";
import * as electronModule from "./cli/electronCommands.js";
import * as javaScriptRuntimeObservationModule from "./cli/javascriptRuntimeCommands.js";
import * as guidanceModule from "./cli/guidanceCommands.js";
import * as guidedWorkflowModule from "./cli/guidedWorkflowCommands.js";
import * as analysisViewModule from "./cli/analysisViewCommands.js";
import * as evidenceModule from "./cliEvidenceCommands.js";
import * as environmentModule from "./cli/environmentCommands.js";
import * as processModule from "./cli/processCommands.js";
import * as desktopCaptureModule from "./cli/desktopCaptureCommands.js";
import * as javaScriptRecoveryModule from "./cli/javascriptRecoveryCommands.js";
import * as webScriptModule from "./cli/webScriptCommands.js";
import * as webModuleModule from "./cli/webModuleCommands.js";
import * as webSourceLocationModule from "./cli/webSourceLocationCommands.js";
import * as applicationModule from "./cli/applicationCommands.js";
import * as nativeFunctionMatchingModule from "./cli/nativeFunctionMatchingCommands.js";
export { closeCliResources } from "./cli/cliResources.js";
const CLI_COMMAND_MODULES: CliCommandModules = {
setup: setupModule,
coreAnalysis: coreAnalysisModule,
reverseEngineering: reverseEngineeringModule,
cutter: cutterModule,
utility: utilityModule,
binaryDiagnostics: binaryDiagnosticsModule,
wasm: wasmModule,
apkSignature: apkSignatureModule,
capture: captureModule,
signal: signalModule,
evm: evmModule,
desktopApplication: desktopApplicationModule,
releaseExposure: releaseExposureModule,
go: goModule,
il2cpp: il2cppModule,
model: modelModule,
gpu: gpuModule,
rust: rustModule,
pythonPyc: pythonPycModule,
nugetNupkg: nugetNupkgModule,
erlang: erlangModule,
v8CodeCache: v8CodeCacheModule,
mavenGradleMetadata: mavenGradleMetadataModule,
sqlite: sqliteModule,
artifact: artifactModule,
managed: managedModule,
firmware: firmwareModule,
uefi: uefiModule,
android: androidModule,
pcap: pcapModule,
flutter: flutterModule,
frida: fridaModule,
apktool: apktoolModule,
jeb: jebModule,
adb: adbModule,
browser: browserModule,
webRuntime: webRuntimeModule,
webNetworkCapture: webNetworkCaptureModule,
advancedBrowser: advancedBrowserModule,
browserScenario: browserScenarioModule,
electron: electronModule,
javaScriptRuntimeObservation: javaScriptRuntimeObservationModule,
guidance: guidanceModule,
guidedWorkflow: guidedWorkflowModule,
analysisView: analysisViewModule,
evidence: evidenceModule,
environment: environmentModule,
process: processModule,
desktopCapture: desktopCaptureModule,
javaScriptRecovery: javaScriptRecoveryModule,
webScript: webScriptModule,
webModule: webModuleModule,
webSourceLocation: webSourceLocationModule,
application: applicationModule,
nativeFunctionMatching: nativeFunctionMatchingModule,
};
/**
* Build the complete one-shot Incur CLI without starting Hopper at import time.
* Analysis commands acquire and close their own sessions; bare `mcp` and
* `--mcp` are intercepted by the executable dispatcher before this module loads.
* One-shot commands load only their own registrars; see `cli/cliLoader.ts`.
*/
export const createCli = (
selectedEnvironment: Readonly<
Record<string, string | undefined>
> = process.env,
resultOutput?: CliResultOutput,
fridaInstrumentation?: FridaInstrumentationPort,
): CliInstance =>
createCliShell({
selectedEnvironment,
resultOutput,
fridaInstrumentation,
createAnalysis: createDirectAnalysis,
registrations: CLI_REGISTRATION_ORDER.map((id) => ({
registration: CLI_COMMAND_REGISTRATIONS[id],
module: CLI_COMMAND_MODULES[id],
})),
});
// Direct execution needs a visible failure pointing to the dispatcher. Imports
// only expose the registry. A normal exit lets piped stderr drain completely.
if (isDirectEntrypoint(CURRENT_ENTRYPOINT_PATH, import.meta.url)) {
process.stderr.write(
"dist/cli.js is the command registry, not the CLI entry point. Run `rea` (scripts/rea.mjs) instead.\n",
);
process.exitCode = 1;
}