diff --git a/.agents/skills/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md index abfbf7334f0..c8085d3d0df 100644 --- a/.agents/skills/reverse-engineer-anything/SKILL.md +++ b/.agents/skills/reverse-engineer-anything/SKILL.md @@ -371,6 +371,27 @@ before abandoning deep analysis or repeating the same cold import. The default `update_analysis_settings` using `ghidra.startup_timeout_ms`. Changing the server's launch environment instead requires a new REA process. +## Continue when no route recognizes the file + +A `file_format_rejected` refusal means no REA format route reads the file, not +that it cannot be analyzed. Keep working and keep the facts attributable: + +1. Start from `details.file_bytes` and `details.leading_bytes`, and identify + the magic from published specifications where you can. +2. Run `inspect_byte_entropy` for the SHA-256 and its high- and low-entropy + ranges, as places to inspect. Entropy measures byte distribution only: it + does not establish plaintext, compression or encryption. + Use `inspect_yara_matches` when rules apply. Open with `raw-binary` only for + headerless machine code with a known architecture and entry point. +3. When REA has no tool for the next step, continue with read-only local + means, such as a hex dump, `strings` or a short script that reads the file. + Never run the target. Compare several samples and any known inputs, such as + sources or build settings, before naming a field. +4. Cite offsets and the SHA-256, and label each fact observed, derived or + inferred. Do not present a guessed layout as parsed. +5. Offer a format request with the leading bytes, the layout found and where + samples come from, without attaching private samples. + ## Work summary-first Start with the default result and use its inline Evidence and graph context. diff --git a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md index abfbf7334f0..c8085d3d0df 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md @@ -371,6 +371,27 @@ before abandoning deep analysis or repeating the same cold import. The default `update_analysis_settings` using `ghidra.startup_timeout_ms`. Changing the server's launch environment instead requires a new REA process. +## Continue when no route recognizes the file + +A `file_format_rejected` refusal means no REA format route reads the file, not +that it cannot be analyzed. Keep working and keep the facts attributable: + +1. Start from `details.file_bytes` and `details.leading_bytes`, and identify + the magic from published specifications where you can. +2. Run `inspect_byte_entropy` for the SHA-256 and its high- and low-entropy + ranges, as places to inspect. Entropy measures byte distribution only: it + does not establish plaintext, compression or encryption. + Use `inspect_yara_matches` when rules apply. Open with `raw-binary` only for + headerless machine code with a known architecture and entry point. +3. When REA has no tool for the next step, continue with read-only local + means, such as a hex dump, `strings` or a short script that reads the file. + Never run the target. Compare several samples and any known inputs, such as + sources or build settings, before naming a field. +4. Cite offsets and the SHA-256, and label each fact observed, derived or + inferred. Do not present a guessed layout as parsed. +5. Offer a format request with the leading bytes, the layout found and where + samples come from, without attaching private samples. + ## Work summary-first Start with the default result and use its inline Evidence and graph context. diff --git a/docs/development/tool-design.md b/docs/development/tool-design.md index 88c75154d52..1da1744cdef 100644 --- a/docs/development/tool-design.md +++ b/docs/development/tool-design.md @@ -181,6 +181,15 @@ target or operation. A selector that resolves to the wrong kind of object, such as an import slot passed where a procedure is expected, reports what it resolved to and names the operations that answer it on that provider. +A fallback named in recovery must fit what the refusal observed and must +accept the refused input. Name operations that accept any input of that kind, +and qualify one that only suits some cases. For example, a raw machine-code +load fits headerless firmware, not an unrecognized data container. Report the +facts the refusal already read, such as size and leading bytes, so the +fallback starts from them. Test that each named fallback accepts the refused +input. When no tool can take the next step, say so rather than naming the +closest one. + For prerequisite failures, identify what the requested operation actually needs. A missing executable, a wrong path, an incompatible host or version, denied permission, and a download timeout need different repairs. Preserve the observed diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index 0f4a0e897a1..9a883269ba0 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -1456,6 +1456,13 @@ constraint, and `details.path` names that file. A `.dext`, `.kext`, resource root reports its `layout` as `contents`, `root`, `versioned-framework` or `flattened-framework`. +When no format route recognizes a file's content, `open_binary` and +`inspect_artifact` report `target_unavailable` with `details.constraint` +`file_format_rejected`, `details.file_bytes`, and `details.leading_bytes`, the +first 16 bytes or fewer in hex. The remediation names `inspect_byte_entropy` and +`inspect_yara_matches`, which accept any file, and the explicit `raw-binary` +load for headerless machine code. + When the caller opens a directory, `inspect_macho` and `inspect_signature` include `normalized_result.bundle_provenance`. It records the canonical bundle directory, selected layout, lookup path and SHA-256 of the Info.plist bytes diff --git a/scripts/verify-real-ghidra-mips.mjs b/scripts/verify-real-ghidra-mips.mjs index b7d44fd527c..0914646adce 100644 --- a/scripts/verify-real-ghidra-mips.mjs +++ b/scripts/verify-real-ghidra-mips.mjs @@ -856,7 +856,7 @@ try { { timeout: 60000 }, ), ); - assertMipsCarvedTargetRefusal(carvedError, openedPath, carve.reason); + assertMipsCarvedTargetRefusal(carvedError, openedPath, carve); let carvedCliError; try { await commands.exec( @@ -887,7 +887,7 @@ try { assertMipsCarvedTargetRefusal( JSON.parse(carvedOutput.stdout), openedPath, - carve.reason, + carve, ); assert.deepEqual(await readFile(carvedPath), carve.bytes); carved = { diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index fa9ea051fec..7425b0044d1 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -108,6 +108,10 @@ import { localPathStringSchema } from "../domain/localPath.js"; import { errorMessage } from "../kernel/errorMessage.js"; const XML_PLIST_PROBE_CHUNK_BYTES = 64 * 1024; +/** Leading bytes reported with a format refusal: enough for common magics. */ +const UNRECOGNIZED_LEADING_BYTES = 16; +const UNRECOGNIZED_FORMAT_REMEDIATION = + 'No supported format recognizes this file; details.leading_bytes holds its first bytes in hex. inspect_byte_entropy accepts any file and reports its SHA-256 and entropy, and inspect_yara_matches scans it with caller-supplied rules. Open it with format "raw-binary", architecture and entry_point only when it is headerless machine code, such as a firmware or memory image.'; /** Options for resolving a local binary target and its stable identity. */ export interface BinaryTargetResolverOptions { @@ -567,10 +571,18 @@ const readOpenedBinaryTarget = async ( new BinaryTargetError(path, reason, { constraint: "file_format_rejected", ...(diagnostics === undefined ? {} : { diagnostics }), - // inspect_artifact shares this detection, so only the explicit - // raw-binary load admits a file whose header no route recognizes. - remediationAction: - 'Select a supported, well-formed target. To analyze a headerless firmware or memory image, open it with format "raw-binary", architecture and entry_point.', + observedContent: { + fileBytes: metadata.size, + leadingBytes: await readLeadingBytes( + handle, + Math.min(metadata.size, UNRECOGNIZED_LEADING_BYTES), + path, + signal, + ), + }, + // open_binary, inspect_artifact and extract_artifact share this + // detection, so the recovery must hold for each of them. + remediationAction: UNRECOGNIZED_FORMAT_REMEDIATION, }), ); } diff --git a/src/domain/analysisErrorProjection.ts b/src/domain/analysisErrorProjection.ts index a03c72f9f92..0eb5e30654a 100644 --- a/src/domain/analysisErrorProjection.ts +++ b/src/domain/analysisErrorProjection.ts @@ -960,6 +960,14 @@ const lifecycleErrorDetails = ( ...(error.probedPaths === undefined ? {} : { probed_paths: [...error.probedPaths] }), + ...(error.observedContent === undefined + ? {} + : { + file_bytes: error.observedContent.fileBytes, + leading_bytes: Buffer.from( + error.observedContent.leadingBytes, + ).toString("hex"), + }), ...(error.systemCode === undefined ? {} : { system_code: error.systemCode, boundary: "filesystem-read" }), diff --git a/src/domain/configurationErrors.ts b/src/domain/configurationErrors.ts index fd715899d70..37dc4642ade 100644 --- a/src/domain/configurationErrors.ts +++ b/src/domain/configurationErrors.ts @@ -87,9 +87,17 @@ export interface BinaryTargetErrorOptions extends AnalysisErrorOptions { readonly infoPlist?: string; /** Bundle paths examined before resolution failed. */ readonly probedPaths?: readonly string[]; + /** Size and leading bytes read before no format recognized the content. */ + readonly observedContent?: BinaryTargetObservedContent; readonly remediationAction?: string; } +/** Content facts a format refusal observed, for triage of an unrecognized file. */ +export interface BinaryTargetObservedContent { + readonly fileBytes: number; + readonly leadingBytes: Uint8Array; +} + /** A supplied target path could not be safely opened as a supported app or binary. */ export class BinaryTargetError extends AnalysisError { readonly _tag = "BinaryTargetError"; @@ -97,6 +105,7 @@ export class BinaryTargetError extends AnalysisError { readonly field: BinaryTargetErrorOptions["field"]; readonly infoPlist: string | undefined; readonly probedPaths: readonly string[] | undefined; + readonly observedContent: BinaryTargetObservedContent | undefined; readonly remediationAction: string | undefined; /** The OS read-permission code of the cause, when the host denied access. */ readonly systemCode: "EACCES" | "EPERM" | undefined; @@ -110,6 +119,7 @@ export class BinaryTargetError extends AnalysisError { this.field = options?.field; this.infoPlist = options?.infoPlist; this.probedPaths = options?.probedPaths; + this.observedContent = options?.observedContent; this.remediationAction = options?.remediationAction; this.systemCode = readPermissionCode(options?.cause); } diff --git a/tests/boundary/filesystem/mipsAbiFlags.test.ts b/tests/boundary/filesystem/mipsAbiFlags.test.ts index 1fbc97bf9f0..139bfd16ee6 100644 --- a/tests/boundary/filesystem/mipsAbiFlags.test.ts +++ b/tests/boundary/filesystem/mipsAbiFlags.test.ts @@ -381,7 +381,7 @@ for (const little of [true, false]) { assertMipsCarvedTargetRefusal( projectAnalysisError(error), await realpath(path), - carve.reason, + carve, ); assert.deepEqual(await readFile(path), carve.bytes); }); diff --git a/tests/boundary/mcp/openBinaryUnrecognizedFormat.test.ts b/tests/boundary/mcp/openBinaryUnrecognizedFormat.test.ts index 9b65da52323..d2e348d5370 100644 --- a/tests/boundary/mcp/openBinaryUnrecognizedFormat.test.ts +++ b/tests/boundary/mcp/openBinaryUnrecognizedFormat.test.ts @@ -5,23 +5,33 @@ import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -it("names the raw-binary load when no route recognizes a file's header", async () => { +it("reports an unrecognized file's leading bytes and the tools that accept any file", async () => { const root = await createTestTempDirectory("rea-open-unrecognized-"); const path = join(root, "image.bin"); - await writeFile(path, "plain text, not an executable\n"); + const content = "plain text, not an executable\n"; + await writeFile(path, content); const { call } = await connectLocalToolsMcp(); for (const name of ["open_binary", "inspect_artifact"]) { const refused = parseMcpToolError(await call(name, { path })); expect(refused.error, name).toMatchObject({ - details: { path, constraint: "file_format_rejected" }, + details: { + path, + constraint: "file_format_rejected", + file_bytes: content.length, + leading_bytes: Buffer.from(content.slice(0, 16)).toString("hex"), + }, remediation: { action: - 'Select a supported, well-formed target. To analyze a headerless firmware or memory image, open it with format "raw-binary", architecture and entry_point.', + 'No supported format recognizes this file; details.leading_bytes holds its first bytes in hex. inspect_byte_entropy accepts any file and reports its SHA-256 and entropy, and inspect_yara_matches scans it with caller-supplied rules. Open it with format "raw-binary", architecture and entry_point only when it is headerless machine code, such as a firmware or memory image.', }, }); } + // The named fallback accepts the file the format routes refused. + const entropy = await call("inspect_byte_entropy", { path }); + expect(entropy.isError, JSON.stringify(entropy.content)).not.toBe(true); + const raw = await call("open_binary", { path, format: "raw-binary", diff --git a/tests/conformance/ghidra/mips-checks.d.mts b/tests/conformance/ghidra/mips-checks.d.mts index 8be53ddd940..a66c789bb4a 100644 --- a/tests/conformance/ghidra/mips-checks.d.mts +++ b/tests/conformance/ghidra/mips-checks.d.mts @@ -52,7 +52,7 @@ export function carveMipsElfBeforeSectionTable( export function assertMipsCarvedTargetRefusal( error: unknown, path: string, - reason: string, + carve: { bytes: Buffer; reason: string }, ): void; export function assertMipsSoftFloatStorage( boundaries: Record, diff --git a/tests/conformance/ghidra/mips-checks.mjs b/tests/conformance/ghidra/mips-checks.mjs index 69b8b294cee..db9527e89b5 100644 --- a/tests/conformance/ghidra/mips-checks.mjs +++ b/tests/conformance/ghidra/mips-checks.mjs @@ -412,16 +412,24 @@ export function carveMipsElfBeforeSectionTable(bytes, byteOrder) { }; } +/** Leading bytes a format refusal reports, matching the resolver's limit. */ +const MIPS_REFUSAL_LEADING_BYTES = 16; + /** * Opening the carved copy fails before provider selection, naming the declared - * range and the captured size; it is not admitted as a smaller program. + * range and the captured size; it is not admitted as a smaller program. The + * refusal also reports the carved copy's size and leading bytes. */ -export function assertMipsCarvedTargetRefusal(error, path, reason) { +export function assertMipsCarvedTargetRefusal(error, path, carve) { assert.equal(error.code, "target_unavailable"); assert.deepEqual(error.details, { path, - reason, + reason: carve.reason, constraint: "file_format_rejected", + file_bytes: carve.bytes.length, + leading_bytes: carve.bytes + .subarray(0, MIPS_REFUSAL_LEADING_BYTES) + .toString("hex"), }); } diff --git a/tests/conformance/ghidra/mips-checks.test.ts b/tests/conformance/ghidra/mips-checks.test.ts index e15672b2f15..eea7bd92925 100644 --- a/tests/conformance/ghidra/mips-checks.test.ts +++ b/tests/conformance/ghidra/mips-checks.test.ts @@ -363,14 +363,27 @@ describe("MIPS real-verifier carved-copy expectations", () => { it("accepts only a target-opening refusal of the carved copy", () => { const path = "/work/little-hard-carved.elf"; - const reason = - "truncated ELF section header table: declared file range 2620..3580 exceeds the 2619-byte file"; - const refusal = { - code: "target_unavailable", - details: { path, reason, constraint: "file_format_rejected" }, + const carve = { + bytes: Buffer.concat([ + Buffer.from("7f454c46010101000000000000000000", "hex"), + Buffer.alloc(2603, 1), + ]), + reason: + "truncated ELF section header table: declared file range 2620..3580 exceeds the 2619-byte file", }; - assertMipsCarvedTargetRefusal(refusal, path, reason); + const { reason } = carve; + const details = { + path, + reason, + constraint: "file_format_rejected", + file_bytes: 2619, + leading_bytes: "7f454c46010101000000000000000000", + }; + const refusal = { code: "target_unavailable", details }; + assertMipsCarvedTargetRefusal(refusal, path, carve); const otherReason = reason.replace("2619", "2620"); + const { file_bytes: _size, ...withoutSize } = details; + const { leading_bytes: _lead, ...withoutLead } = details; for (const [observed, failure] of [ // Superseded: a resolved copy refused later by Ghidra admission. [ @@ -390,19 +403,22 @@ describe("MIPS real-verifier carved-copy expectations", () => { mismatch("capability_unavailable", "target_unavailable"), ], [ - { - ...refusal, - details: { ...refusal.details, reason: otherReason }, - }, - mismatch({ ...refusal.details, reason: otherReason }, refusal.details), + { ...refusal, details: { ...details, reason: otherReason } }, + mismatch({ ...details, reason: otherReason }, details), ], [ { ...refusal, details: { path, reason } }, - mismatch({ path, reason }, refusal.details), + mismatch({ path, reason }, details), + ], + [{ ...refusal, details: withoutSize }, mismatch(withoutSize, details)], + [{ ...refusal, details: withoutLead }, mismatch(withoutLead, details)], + [ + { ...refusal, details: { ...details, file_bytes: 2620 } }, + mismatch({ ...details, file_bytes: 2620 }, details), ], ] as const) expect(() => - assertMipsCarvedTargetRefusal(observed, path, reason), + assertMipsCarvedTargetRefusal(observed, path, carve), ).toThrow(failure); }); });