Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(native): verify signature snapshots and frame unsigned diagnostics
morlutoeb7acc70bf06
diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.tsindex 97e859b06..145c3d43a 100644--- a/src/native/NativeMacOSProvider.ts+++ b/src/native/NativeMacOSProvider.ts@@ -627,8 +627,14 @@ class NativeMacOSClient implements AnalysisClient {signal,);if (!display.ok) return display;- const unsigned = isNonzeroUnsignedObservation(display.value);- const displayFailure = codeSignCaptureFailure(display.value);+ const unsigned = isNonzeroUnsignedObservation(+ display.value,+ binding.snapshotPath,+ );+ const displayFailure = codeSignCaptureFailure(+ display.value,+ binding.snapshotPath,+ );if (displayFailure !== null) return err(displayFailure);const requirements = await this.#captureSignature(binding,@@ -636,7 +642,10 @@ class NativeMacOSClient implements AnalysisClient {signal,);if (!requirements.ok) return requirements;- const requirementsFailure = codeSignCaptureFailure(requirements.value);+ const requirementsFailure = codeSignCaptureFailure(+ requirements.value,+ binding.snapshotPath,+ );if (requirementsFailure !== null) return err(requirementsFailure);const entitlements = await this.#captureSignature(binding,@@ -644,7 +653,10 @@ class NativeMacOSClient implements AnalysisClient {signal,);if (!entitlements.ok) return entitlements;- const entitlementsFailure = codeSignCaptureFailure(entitlements.value);+ const entitlementsFailure = codeSignCaptureFailure(+ entitlements.value,+ binding.snapshotPath,+ );if (entitlementsFailure !== null) return err(entitlementsFailure);// codesign echoes the resolved executable path in its diagnostics.const parsed = parseCodeSignature(display.value.stderr, unsigned, [@@ -669,8 +681,8 @@ class NativeMacOSClient implements AnalysisClient {];const mixedSigning =!unsigned &&- (isNonzeroUnsignedObservation(requirements.value) ||- isNonzeroUnsignedObservation(entitlements.value));+ (isNonzeroUnsignedObservation(requirements.value, binding.snapshotPath) ||+ isNonzeroUnsignedObservation(entitlements.value, binding.snapshotPath));if (mixedSigning) {const slices = await this.#inspectMixedSignatureSlices(binding,@@ -721,7 +733,7 @@ class NativeMacOSClient implements AnalysisClient {if (!slice.ok) return slice;captures.push(slice.value);if (slice.value.exitCode === 0) continue;- if (isNonzeroUnsignedObservation(slice.value))+ if (isNonzeroUnsignedObservation(slice.value, binding.snapshotPath))unsigned.push(architecture);else unclassified.push(architecture);}@@ -1239,17 +1251,28 @@ const translateCodeSignExitFailure = (),);-const commandOutput = (capture: NativeCommandCapture): string =>- `${capture.stdout}\n${capture.stderr}`;-/**- * A signed artifact exits zero; its diagnostics can still contain this text- * through the echoed path or identifier.+ * Accept only codesign's exact unsigned diagnostic for the bound snapshot.+ * The operand is framed byte-for-byte so caller-controlled path text cannot+ * supply the phrase that determines signature state.*/-const isNonzeroUnsignedObservation = (capture: NativeCommandCapture): boolean =>- capture.exitCode !== null &&- capture.exitCode !== 0 &&- /not signed at all|code object is not signed/iu.test(commandOutput(capture));+const isNonzeroUnsignedObservation = (+ capture: NativeCommandCapture,+ snapshotPath: string,+): boolean => {+ if (+ capture.exitCode === null ||+ capture.exitCode === 0 ||+ capture.signal !== null ||+ capture.arguments.at(-1) !== snapshotPath ||+ capture.stdout !== ""+ )+ return false;+ const diagnostic = `${snapshotPath}: code object is not signed at all`;+ return [diagnostic, `${diagnostic}\n`, `${diagnostic}\r\n`].includes(+ capture.stderr,+ );+};const canonicalPath = async (path: string): Promise<string[]> => {try {@@ -1261,8 +1284,9 @@ const canonicalPath = async (path: string): Promise<string[]> => {const codeSignCaptureFailure = (capture: NativeCommandCapture,+ snapshotPath: string,): AnalysisError | null =>- capture.exitCode === 0 || isNonzeroUnsignedObservation(capture)+ capture.exitCode === 0 || isNonzeroUnsignedObservation(capture, snapshotPath)? null: translateCodeSignExitFailure(capture);diff --git a/src/native/SignatureTargetBinding.test.ts b/src/native/SignatureTargetBinding.test.tsindex ed019fafc..f361ebf90 100644--- a/src/native/SignatureTargetBinding.test.ts+++ b/src/native/SignatureTargetBinding.test.ts@@ -1,7 +1,9 @@import { createHash } from "node:crypto";import {+ chmod,mkdtemp,rm,+ readFile,stat,writeFile,open,@@ -18,7 +20,10 @@ import { ok, err } from "../domain/result.js";import type { NativeCommandRunner } from "./CommandRunner.js";import type { NativeCallTracer } from "./LldbCallTracer.js";import { NativeMacOSProvider } from "./NativeMacOSProvider.js";-import { withSignatureTarget } from "./SignatureTargetBinding.js";+import {+ verifySignatureTarget,+ withSignatureTarget,+} from "./SignatureTargetBinding.js";import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";import { resolvedAnalysisError } from "../domain/analysisErrorBase.js";import { ProviderCleanupError } from "../domain/providerCleanupError.js";@@ -115,6 +120,42 @@ it("retains a snapshot root after cleanup fails alongside a digest mismatch", asawait expect(stat(roots[0]!)).rejects.toMatchObject({ code: "ENOENT" });});+it("retains and retries snapshot cleanup after snapshot identity drift", async () => {+ const target = await createTarget("registered bytes");+ const resources = new ArtifactResourceScope();+ const result = await withSignatureTarget(+ target,+ resources,+ async (binding) => {+ await chmod(binding.snapshotPath, 0o600);+ await writeFile(binding.snapshotPath, "replacement snapshot bytes");+ const verified = await verifySignatureTarget(target, binding);+ return verified.ok ? ok(signatureInspectionFixture()) : verified;+ },+ undefined,+ () => createRoot(1),+ );++ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(projectAnalysisError(result.error)).toMatchObject({+ details: {+ diagnostics: {+ primary_error: { code: "artifact_changed" },+ },+ },+ });++ await resources.close();+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(resolvedAnalysisError(result.error)._tag).toBe(+ "AnalysisArtifactChangedError",+ );+ expect(await readFile(target.path, "utf8")).toBe("registered bytes");+ await expect(stat(roots[0]!)).rejects.toMatchObject({ code: "ENOENT" });+});+it("returns a retained cleanup failure when the next call cannot retry its root", async () => {const target = await createTarget("observed", "expected");const resources = new ArtifactResourceScope();diff --git a/src/native/SignatureTargetBinding.ts b/src/native/SignatureTargetBinding.tsindex b16b2203d..8d7b4d633 100644--- a/src/native/SignatureTargetBinding.ts+++ b/src/native/SignatureTargetBinding.ts@@ -44,6 +44,7 @@ type SignatureOwner = Extract<export interface SignatureTargetBinding {readonly identity: string;readonly snapshotPath: string;+ readonly snapshotIdentity: string;}const identity = (stat: BigIntStats): string =>@@ -380,7 +381,23 @@ const bindSignatureTarget = async (`Signature target changed while establishing its version: ${target.path}`,);await snapshotIO(target, "seal", () => snapshot.chmod(0o400));- return ok({ identity: identity(opened), snapshotPath });+ const snapshotOpened = await snapshot.stat({ bigint: true });+ const snapshotAtPath = await lstat(snapshotPath, { bigint: true });+ if (+ !snapshotOpened.isFile() ||+ !snapshotAtPath.isFile() ||+ snapshotAtPath.isSymbolicLink() ||+ identity(snapshotOpened) !== identity(snapshotAtPath)+ )+ return changedTarget(+ target,+ `Digest-verified signature snapshot changed while binding: ${target.path}`,+ );+ return ok({+ identity: identity(opened),+ snapshotPath,+ snapshotIdentity: identity(snapshotOpened),+ });} catch (cause: unknown) {return err(signatureReadFailure(target, cause));}@@ -438,11 +455,32 @@ export const verifySignatureTarget = async (assertRegularFileActive(signal);const current = await lstat(target.path, { bigint: true });assertRegularFileActive(signal);- return current.isFile() && identity(current) === binding.identity+ if (!current.isFile() || identity(current) !== binding.identity)+ return changedTarget(+ target,+ `Signature target changed during inspection: ${target.path}`,+ );+ let snapshot: BigIntStats;+ try {+ snapshot = await lstat(binding.snapshotPath, { bigint: true });+ } catch (cause: unknown) {+ const code =+ cause instanceof Error && "code" in cause ? cause.code : undefined;+ if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP")+ return changedTarget(+ target,+ `Digest-verified signature snapshot is unavailable during inspection: ${target.path}`,+ );+ return err(signatureReadFailure(target, cause));+ }+ assertRegularFileActive(signal);+ return snapshot.isFile() &&+ !snapshot.isSymbolicLink() &&+ identity(snapshot) === binding.snapshotIdentity? ok(undefined): changedTarget(target,- `Signature target changed during inspection: ${target.path}`,+ `Digest-verified signature snapshot changed during inspection: ${target.path}`,);} catch (cause: unknown) {return err(signatureReadFailure(target, cause));diff --git a/tests/boundary/providers/native/nativeInventory.golden.test.ts b/tests/boundary/providers/native/nativeInventory.golden.test.tsindex fcb5bc104..5e1824e80 100644--- a/tests/boundary/providers/native/nativeInventory.golden.test.ts+++ b/tests/boundary/providers/native/nativeInventory.golden.test.ts@@ -46,14 +46,29 @@ const signatureTarget = async (it("distinguishes a codesign execution failure from an observed unsigned artifact", async () => {for (const kind of ["missing", "unsigned"] as const) {+ const fixtureOutput = await fixture(`dyld-inventory/codesign-${kind}.txt`);const client = new NativeMacOSProvider({},- new FixtureRunner(- {- codesign: await fixture(`dyld-inventory/codesign-${kind}.txt`),+ {+ async run(tool, arguments_) {+ const output =+ kind === "unsigned"+ ? `${arguments_.at(-1)}: code object is not signed at all\n`+ : fixtureOutput;+ const capture = await new FixtureRunner({ codesign: output }, 1).run(+ tool,+ arguments_,+ );+ if (!capture.ok || kind !== "unsigned") return capture;+ return ok({+ ...capture.value,+ stdout: "",+ stderr: output,+ stdoutBytes: 0,+ stderrBytes: Buffer.byteLength(output),+ });},- 1,- ),+ },"darwin",).createClient(await signatureTarget());const execution = await client.execute("inspect_signature", {});@@ -397,13 +412,21 @@ const signatureRunner = (outputs: {const architectureIndex = arguments_.indexOf("-a");const architecture =architectureIndex < 0 ? null : arguments_[architectureIndex + 1];- const response = arguments_.includes("-r-")+ const selectedResponse = arguments_.includes("-r-")? { output: outputs.unsigned, exitCode: 1 }: arguments_.includes("--entitlements")? { output: outputs.entitlements, exitCode: 0 }: architecture === "x86_64"? { output: outputs.unsigned, exitCode: 1 }: { output: outputs.signed, exitCode: 0 };+ const response =+ selectedResponse.exitCode !== 0 &&+ selectedResponse.output.includes("code object is not signed at all")+ ? {+ ...selectedResponse,+ output: `${arguments_.at(-1)}: code object is not signed at all\n`,+ }+ : selectedResponse;const capture: NativeCommandCapture = {tool,executable: `/usr/bin/${tool}`,@@ -412,7 +435,7 @@ const signatureRunner = (outputs: {versionReason: "fixture",arguments: [...arguments_],// Entitlements XML is printed to stdout; diagnostics to stderr.- ...(arguments_.includes("--entitlements")+ ...(response.exitCode === 0 && arguments_.includes("--entitlements")? {stdout: response.output,stderr: "",diff --git a/tests/boundary/providers/native/nativeSignatureTargetBinding.test.ts b/tests/boundary/providers/native/nativeSignatureTargetBinding.test.tsindex 66f00104e..56e3c43b7 100644--- a/tests/boundary/providers/native/nativeSignatureTargetBinding.test.ts+++ b/tests/boundary/providers/native/nativeSignatureTargetBinding.test.ts@@ -37,6 +37,7 @@ import {import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";const CONTENT = "registered executable bytes";+const runFile = promisify(execFile);const fixture = async () => {const directory = await createTestTempDirectory("rea-signature-binding-");const path = join(directory, "program");@@ -228,10 +229,23 @@ it.each([async (stage, failure) => {const { path, target } = await fixture();const replay = new NativeFixtureRunner();- const unsigned = new NativeFixtureRunner(- { codesign: "code object is not signed at all\n" },- 1,- );+ const unsigned: NativeCommandRunner = {+ async run(tool, args, options) {+ const diagnostic = `${args.at(-1)}: code object is not signed at all\n`;+ const capture = await new NativeFixtureRunner(+ { codesign: diagnostic },+ 1,+ ).run(tool, args);+ if (!capture.ok) return capture;+ return ok({+ ...capture.value,+ stdout: "",+ stderr: diagnostic,+ stdoutBytes: 0,+ stderrBytes: Buffer.byteLength(diagnostic),+ });+ },+ };let failed = false;const runner: NativeCommandRunner = {async run(tool, args) {@@ -259,7 +273,7 @@ it.each([return err(new NativeCommandFailure(tool, "nonzero-exit", 1));}if (stage === "slice" && args.includes("-r-"))- return unsigned.run(tool, args);+ return unsigned.run(tool, args, {});return replay.run(tool, args);},};@@ -361,6 +375,110 @@ it("preserves cancellation after a capture instead of classifying it as invalid});});+it("does not classify an unrelated path-echo diagnostic as an unsigned observation", async () => {+ const directory = await createTestTempDirectory(+ "rea-signature-path-diagnostic-",+ );+ const path = join(directory, "source\ncode object is not signed\noperand");+ await writeFile(path, CONTENT);+ const target = await nativeMachoTargetForFile(path);+ let snapshotPath: string | undefined;+ const runner: NativeCommandRunner = {+ async run(tool, args) {+ snapshotPath = args.at(-1);+ if (snapshotPath === undefined)+ throw new Error("Expected the bound snapshot as the codesign operand");+ expect(await readFile(snapshotPath)).toEqual(Buffer.from(CONTENT));+ return new NativeFixtureRunner(+ { codesign: `${snapshotPath}: No such file or directory\n` },+ 1,+ ).run(tool, args);+ },+ };++ const result = await new NativeMacOSProvider({}, runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});++ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "ProviderAdapterError" },+ });+ expect(await readFile(path, "utf8")).toBe(CONTENT);+ if (snapshotPath === undefined) throw new Error("Expected codesign capture");+ await expect(lstat(dirname(snapshotPath))).rejects.toMatchObject({+ code: "ENOENT",+ });+});++it.skipIf(process.platform !== "darwin")(+ "rejects a path-injected unsigned diagnostic when real codesign sees a removed private snapshot",+ async () => {+ const directory = await createTestTempDirectory(+ "rea-signature-snapshot-path-",+ );+ const path = join(directory, "source\ncode object is not signed\noperand");+ await copyFile("/usr/bin/true", path);+ const target = await nativeMachoTargetForFile(path);+ const originalBytes = await readFile(path);+ const real = new XcrunCommandRunner({});+ let snapshotPath: string | undefined;+ const runner: NativeCommandRunner = {+ async run(tool, args, options) {+ snapshotPath = args.at(-1);+ if (snapshotPath === undefined)+ throw new Error(+ "Expected the bound snapshot as the codesign operand",+ );+ expect(snapshotPath).not.toBe(path);+ expect(snapshotPath).toContain("\ncode object is not signed\n");+ await rm(snapshotPath);+ return real.run(tool, args, options);+ },+ };++ const result = await new NativeMacOSProvider({}, runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});++ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisArtifactChangedError" },+ });+ expect(await readFile(path)).toEqual(originalBytes);+ if (snapshotPath === undefined)+ throw new Error("Expected codesign capture");+ await expect(lstat(dirname(snapshotPath))).rejects.toMatchObject({+ code: "ENOENT",+ });+ },+);++it.skipIf(process.platform !== "darwin")(+ "accepts the exact unsigned diagnostic for a caller path containing that phrase",+ async () => {+ const directory = await createTestTempDirectory(+ "rea-signature-real-unsigned-",+ );+ const path = join(directory, "source\ncode object is not signed\noperand");+ await copyFile("/usr/bin/true", path);+ await runFile("/usr/bin/codesign", ["--remove-signature", path]);+ const target = await nativeMachoTargetForFile(path);+ const result = await new NativeMacOSProvider(+ {},+ new XcrunCommandRunner({}),+ "darwin",+ )+ .createClient(target)+ .execute("inspect_signature", {});+ if (!result.ok) throw result.error;+ const parsed = inspectSignatureSchema.parse(result.value.result);+ expect(parsed).toMatchObject({ signed: false });+ expect(parsed.provenance).toHaveLength(3);+ expect(parsed.provenance.every(({ exit }) => exit.code === 1)).toBe(true);+ },+);+it.each(["success", "failure", "cancellation", "throw"] as const)("releases the verified snapshot after %s",async (outcome) => {@@ -409,6 +527,28 @@ it("copies and hashes the same bytes across multiple snapshot chunks", async ());});+it.skipIf(process.platform === "win32")(+ "rejects a changed snapshot identity while the registered source remains unchanged",+ async () => {+ const { path, target } = await fixture();+ const result = await withSignatureTarget(+ target,+ new ArtifactResourceScope(),+ async (binding) => {+ await chmod(binding.snapshotPath, 0o600);+ await writeFile(binding.snapshotPath, "replacement snapshot bytes");+ const verified = await verifySignatureTarget(target, binding);+ return verified.ok ? ok(signatureInspectionFixture()) : verified;+ },+ );+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisArtifactChangedError" },+ });+ expect(await readFile(path, "utf8")).toBe(CONTENT);+ },+);+it("cleans the private snapshot when inspection throws", async () => {const { target } = await fixture();let snapshotPath: string | undefined;