From 78a59d4e8f23814649834b498a4ff6e188ba9e39 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 8 Oct 2026 23:47:39 +0800 Subject: [PATCH] fix(native): bind signature results and preserve verification uncertainty --- scripts/verify/apple/code-signature.mjs | 37 +++-- src/native/CodesignVerification.ts | 1 + src/native/NativeNestedCode.test.ts | 4 +- src/native/NativeNestedCode.ts | 6 +- src/native/NativeSignatureInspection.ts | 21 +-- src/native/SignatureTargetBinding.ts | 131 ++++++++++++------ .../codesignVerificationReasons.test.ts | 1 + .../providers/native/nativeProvider.test.ts | 13 +- .../native/nativeSignaturePosture.test.ts | 86 ++++++++++-- 9 files changed, 209 insertions(+), 91 deletions(-) diff --git a/scripts/verify/apple/code-signature.mjs b/scripts/verify/apple/code-signature.mjs index 8aaae6208..efc1247a4 100644 --- a/scripts/verify/apple/code-signature.mjs +++ b/scripts/verify/apple/code-signature.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { copyFile, + lstat, mkdir, mkdtemp, realpath, @@ -123,22 +124,30 @@ try { }); // Deep verification reports the fixture's real nested code, all on disk. assert.ok(plain.verification.validated_nested_code.length > 0); - assert.ok( - !plain.limitations.some((limitation) => - limitation.includes("which does not exist"), - ), - ); + const checkNestedProgress = async (signature) => { + for (const path of signature.verification.validated_nested_code) { + try { + await lstat(path); + } catch { + assert.ok( + signature.limitations.some((limitation) => + limitation.includes(JSON.stringify(path)), + ), + `Unconfirmed progress pathname must retain its limitation: ${path}`, + ); + } + } + }; + await checkNestedProgress(plain); await withArtifactMcp(app, async (client) => { const viaMcp = await artifactMcpResult(client, "inspect_signature"); - const semantic = (value) => ({ - ...value, - provenance: [], - verification: { - ...value.verification, - raw_stdout: "", - raw_stderr: "", - }, - }); + assert.equal(viaMcp.verification.status, plain.verification.status); + assert.equal(viaMcp.verification.path, plain.verification.path); + await checkNestedProgress(viaMcp); + // Separate live codesign runs can interleave progress records differently. + // Compare the artifact's signature posture; check each capture independently. + const semantic = ({ provenance, verification, limitations, ...posture }) => + posture; assert.deepEqual(semantic(viaMcp), semantic(plain)); }); diff --git a/src/native/CodesignVerification.ts b/src/native/CodesignVerification.ts index 53ca3d8f7..f7bd51923 100644 --- a/src/native/CodesignVerification.ts +++ b/src/native/CodesignVerification.ts @@ -58,6 +58,7 @@ const INVALID_SIGNATURE_REASONS = [ "file modified:", "invalid or unsupported format", "invalid signature", + "main executable failed strict validation", "resource envelope is obsolete", "resource fork, Finder information, or similar detritus not allowed", "signature is invalid", diff --git a/src/native/NativeNestedCode.test.ts b/src/native/NativeNestedCode.test.ts index 90525f9c8..6356a994a 100644 --- a/src/native/NativeNestedCode.test.ts +++ b/src/native/NativeNestedCode.test.ts @@ -40,7 +40,7 @@ it("checks prepared-only fragments with the same completeness rules", async () = ); }); -it.each(["EIO", "ESTALE"])( +it.each(["EACCES", "EPERM", "EIO", "ESTALE"])( "keeps observed records when path lookup fails with %s", async (code) => { const result = await inspectNestedCodePaths( @@ -60,7 +60,7 @@ it.each(["EIO", "ESTALE"])( expect(result.limitations.every((message) => message.includes(code))).toBe( true, ); - expect(result.progressAmbiguous).toBe(false); + expect(result.progressAmbiguous).toBe(true); }, ); it("detects newline ambiguity even when the reported first fragment does not exist", async () => { diff --git a/src/native/NativeNestedCode.ts b/src/native/NativeNestedCode.ts index 6aed612b2..05235bdce 100644 --- a/src/native/NativeNestedCode.ts +++ b/src/native/NativeNestedCode.ts @@ -49,6 +49,7 @@ export const inspectNestedCodePaths = async ( signal?.throwIfAborted(); const code = errorCode(cause); if (code === "EACCES" || code === "EPERM") { + progressAmbiguous = true; limitations.push( `Could not confirm completeness of codesign nested path ${JSON.stringify(path)}: permission denied (${code}); the reported path may be a fragment.`, ); @@ -58,10 +59,12 @@ export const inspectNestedCodePaths = async ( limitations.push( `codesign reported ${record} nested code at ${JSON.stringify(path)}, which does not exist; structured nested-code records may hold fragments of a path containing a newline.`, ); - else + else { + progressAmbiguous = true; limitations.push( `Could not confirm completeness of codesign nested path ${JSON.stringify(path)}: ${cause instanceof Error ? cause.message : String(cause)} (${String(code ?? "unknown")}); the reported path may be a fragment.`, ); + } } signal?.throwIfAborted(); const parent = dirname(path); @@ -91,6 +94,7 @@ export const inspectNestedCodePaths = async ( } } catch (cause: unknown) { signal?.throwIfAborted(); + progressAmbiguous = true; limitations.push( `Could not confirm completeness of codesign nested path ${JSON.stringify(path)} from parent directory ${JSON.stringify(parent)}: ${cause instanceof Error ? cause.message : String(cause)}`, ); diff --git a/src/native/NativeSignatureInspection.ts b/src/native/NativeSignatureInspection.ts index cca5d4163..7840d1c81 100644 --- a/src/native/NativeSignatureInspection.ts +++ b/src/native/NativeSignatureInspection.ts @@ -10,7 +10,7 @@ import { import { deriveSecurityFacets } from "./CodeSigningPolicy.js"; import { bindSignatureTarget, - signatureTargetIssue, + verifySignatureTarget, } from "./SignatureTargetBinding.js"; import { omittedPrototypeKeysLimitation } from "../domain/propertyListKeys.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -107,6 +107,7 @@ export const inspectNativeSignature = async (options: { }): Promise> => { const { target, capture, signal } = options; const binding = await bindSignatureTarget(target, signal); + if (!binding.ok) return binding; const displays = await signatureDisplays(target.path, capture, signal); if (!displays.ok) return displays; const { display, requirements, entitlements } = displays.value; @@ -201,7 +202,8 @@ export const inspectNativeSignature = async (options: { } const provenance = captures.map(options.invocation); const ticket = await stapledTicket(target, signal); - const versionIssue = await signatureTargetIssue(target, binding, signal); + const version = await verifySignatureTarget(target, binding.value, signal); + if (!version.ok) return version; const facets = deriveSecurityFacets({ signed: !aggregateUnsigned, codeDirectory: parsed.code_directory, @@ -211,11 +213,6 @@ export const inspectNativeSignature = async (options: { appleOrigin, signatureInvalid: mainInvalid, }); - if (versionIssue !== null) - limitations.push( - versionIssue, - "Security facets are unknown because command observations could not be bound to one registered target version.", - ); const result = inspectSignatureSchema.parse({ ...parsed, signed: !aggregateUnsigned, @@ -224,15 +221,7 @@ export const inspectNativeSignature = async (options: { entitlements: entitlementValue.value, verification, stapled_ticket: ticket, - security_facets: - versionIssue === null - ? facets - : facets.map((facet) => ({ - ...facet, - state: "unknown" as const, - evidence: [...facet.evidence, "target version not bound"], - explanation: `${facet.explanation} Target version binding failed: ${versionIssue}`, - })), + security_facets: facets, provenance, limitations, }); diff --git a/src/native/SignatureTargetBinding.ts b/src/native/SignatureTargetBinding.ts index 89980eafc..75a0430e8 100644 --- a/src/native/SignatureTargetBinding.ts +++ b/src/native/SignatureTargetBinding.ts @@ -2,29 +2,77 @@ import { createHash } from "node:crypto"; import { constants, type BigIntStats } from "node:fs"; import { lstat, open } from "node:fs/promises"; import type { BinaryTarget } from "../domain/binaryTarget.js"; +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { + AnalysisAccessDeniedError, + AnalysisArtifactChangedError, + AnalysisResourceConstraintError, +} from "../domain/analysisErrorCore.js"; +import { ProviderAdapterError } from "../domain/providerAdapterError.js"; +import { err, ok, type Result } from "../domain/result.js"; +import { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js"; /** Binding of commands to the selected executable's registered content/version. */ export interface SignatureTargetBinding { - readonly identity: string | null; - readonly reason: string | null; + readonly identity: string; } const identity = (stat: BigIntStats): string => [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":"); +const changedTarget = (target: BinaryTarget, reason: string) => + err( + new AnalysisArtifactChangedError("inspect_signature", target.path, reason), + ); + +const signatureReadFailure = ( + target: BinaryTarget, + cause: unknown, +): AnalysisError => { + const code = + cause instanceof Error && "code" in cause ? cause.code : undefined; + if (code === "EACCES" || code === "EPERM") + return new AnalysisAccessDeniedError( + "inspect_signature", + target.path, + code, + { cause }, + ); + if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP") + return new AnalysisArtifactChangedError( + "inspect_signature", + target.path, + `Registered signature target is no longer readable (${code}): ${target.path}`, + { cause }, + ); + return new ProviderAdapterError( + NATIVE_MACOS_PROVIDER_IDENTITY.id, + "inspect_signature", + { + cause, + diagnostics: { + path: target.path, + phase: "target-version-binding", + system_code: typeof code === "string" ? code : null, + reason: cause instanceof Error ? cause.message : String(cause), + }, + }, + ); +}; + /** Establish a bounded-memory digest/version baseline before external commands run. */ export const bindSignatureTarget = async ( target: BinaryTarget, signal?: AbortSignal, -): Promise => { +): Promise> => { signal?.throwIfAborted(); try { const before = await lstat(target.path, { bigint: true }); if (!before.isFile() || before.isSymbolicLink()) - return { - identity: null, - reason: `Signature target is no longer a regular file: ${target.path}`, - }; + return changedTarget( + target, + `Signature target is no longer a regular file: ${target.path}`, + ); const file = await open( target.path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, @@ -32,16 +80,20 @@ export const bindSignatureTarget = async ( try { const opened = await file.stat({ bigint: true }); if (identity(opened) !== identity(before)) - return { - identity: null, - reason: `Signature target changed before open: ${target.path}`, - }; + return changedTarget( + target, + `Signature target changed before open: ${target.path}`, + ); const size = Number(opened.size); if (!Number.isSafeInteger(size)) - return { - identity: null, - reason: `Signature target size is not exactly representable: ${target.path}`, - }; + return err( + new AnalysisResourceConstraintError( + "inspect_signature", + "file-size", + `Signature target size is not exactly representable: ${target.path}`, + null, + ), + ); const hash = createHash("sha256"); const chunk = Buffer.alloc(64 * 1024); let position = 0; @@ -54,61 +106,56 @@ export const bindSignatureTarget = async ( position, ); if (bytesRead === 0) - return { - identity: null, - reason: `Signature target was truncated while hashing: ${target.path}`, - }; + return changedTarget( + target, + `Signature target was truncated while hashing: ${target.path}`, + ); hash.update(chunk.subarray(0, bytesRead)); position += bytesRead; } const observed = hash.digest("hex"); if (observed !== target.sha256) - return { - identity: null, - reason: `Signature target digest changed: ${target.path}; expected ${target.sha256}, observed ${observed}`, - }; + return changedTarget( + target, + `Signature target digest changed: ${target.path}; expected ${target.sha256}, observed ${observed}`, + ); const after = await file.stat({ bigint: true }); const current = await lstat(target.path, { bigint: true }); if ( identity(after) !== identity(opened) || identity(current) !== identity(opened) ) - return { - identity: null, - reason: `Signature target changed while establishing its version: ${target.path}`, - }; - return { identity: identity(opened), reason: null }; + return changedTarget( + target, + `Signature target changed while establishing its version: ${target.path}`, + ); + return ok({ identity: identity(opened) }); } finally { await file.close(); } } catch (cause: unknown) { signal?.throwIfAborted(); - if (cause instanceof Error && "code" in cause) - return { - identity: null, - reason: `Signature target version is unavailable: ${target.path}; ${cause.message}`, - }; - throw cause; + return err(signatureReadFailure(target, cause)); } }; /** Reject drift between display, entitlement and verification captures. */ -export const signatureTargetIssue = async ( +export const verifySignatureTarget = async ( target: BinaryTarget, binding: SignatureTargetBinding, signal?: AbortSignal, -): Promise => { +): Promise> => { signal?.throwIfAborted(); - if (binding.identity === null) return binding.reason; try { const current = await lstat(target.path, { bigint: true }); return current.isFile() && identity(current) === binding.identity - ? null - : `Signature target changed during inspection: ${target.path}`; + ? ok(undefined) + : changedTarget( + target, + `Signature target changed during inspection: ${target.path}`, + ); } catch (cause: unknown) { signal?.throwIfAborted(); - if (cause instanceof Error && "code" in cause) - return `Signature target version could not be rechecked: ${target.path}; ${cause.message}`; - throw cause; + return err(signatureReadFailure(target, cause)); } }; diff --git a/tests/boundary/providers/native/codesignVerificationReasons.test.ts b/tests/boundary/providers/native/codesignVerificationReasons.test.ts index 128ba9ce0..699d16864 100644 --- a/tests/boundary/providers/native/codesignVerificationReasons.test.ts +++ b/tests/boundary/providers/native/codesignVerificationReasons.test.ts @@ -43,6 +43,7 @@ it("keeps operational, unsigned, definite invalid and unrecognized failures dist expect(status("permission denied")).toBe("unknown"); expect(status("I/O error")).toBe("unknown"); expect(status("invalid signature")).toBe("invalid"); + expect(status("main executable failed strict validation")).toBe("invalid"); expect(status("bundle format unrecognized, invalid, or unsuitable")).toBe( "invalid", ); diff --git a/tests/boundary/providers/native/nativeProvider.test.ts b/tests/boundary/providers/native/nativeProvider.test.ts index 68eeee7b3..85c362599 100644 --- a/tests/boundary/providers/native/nativeProvider.test.ts +++ b/tests/boundary/providers/native/nativeProvider.test.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { mkdir, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -18,9 +19,14 @@ import { parseCodeSignature } from "../../../../src/native/parsers/codesign.js"; import { NativeFixtureRunner as FixtureRunner, nativeFixture as fixture, - nativeMachoTarget as machoTarget, + nativeMachoTarget as unboundMachoTarget, } from "../../../fixtures/nativeCommands.js"; +const machoTarget = (path: string, app?: string) => ({ + ...unboundMachoTarget(path, app), + sha256: createHash("sha256").update("fixture").digest("hex"), +}); + let directory: string | undefined; afterEach(async () => { if (directory !== undefined) @@ -318,10 +324,13 @@ class PrototypeEntitlementsRunner extends FixtureRunner { describe("native signature entitlements", () => { it("reports entitlement entries keyed __proto__ that the result omits", async () => { + directory = await createTestTempDirectory("rea-signature-entitlements-"); + const executable = join(directory, "fixture"); + await writeFile(executable, "fixture"); const client = new NativeMacOSProvider( new PrototypeEntitlementsRunner(), "darwin", - ).createClient(machoTarget("/private/fixture")); + ).createClient(machoTarget(executable)); const signature = await client.execute("inspect_signature", {}); diff --git a/tests/boundary/providers/native/nativeSignaturePosture.test.ts b/tests/boundary/providers/native/nativeSignaturePosture.test.ts index d51014d8d..434e230b8 100644 --- a/tests/boundary/providers/native/nativeSignaturePosture.test.ts +++ b/tests/boundary/providers/native/nativeSignaturePosture.test.ts @@ -106,6 +106,8 @@ describe("native signature posture", () => { it("keeps a failed strict verification as an observation", async () => { const { app, executable } = await fixtureApp(undefined); + await mkdir(join(app, "Contents/PlugIns/A.appex"), { recursive: true }); + await mkdir(join(app, "Contents/XPCServices/B.xpc"), { recursive: true }); const signature = await new NativeMacOSProvider( new TamperedRunner(), "darwin", @@ -506,6 +508,52 @@ describe("signature architecture coverage", () => { }); describe("signature target version binding", () => { + it("rejects a replacement before invoking signature tools", async () => { + const { app, executable } = await fixtureApp(undefined); + const runner = new (class extends FixtureRunner { + calls = 0; + override async run(tool: string, args: readonly string[]) { + this.calls += 1; + return super.run(tool, args); + } + })(); + const client = new NativeMacOSProvider(runner, "darwin").createClient( + machoTarget(executable, app), + ); + await writeFile(executable, "replacement bytes"); + const signature = await client.execute("inspect_signature", {}); + expect(signature.ok).toBe(false); + if (signature.ok) throw new Error("Expected target change"); + expect(projectAnalysisError(signature.error)).toMatchObject({ + code: "artifact_changed", + details: { path: executable }, + }); + expect(runner.calls).toBe(0); + }); + + it.skipIf(process.getuid?.() === 0)( + "rejects an unreadable selected executable", + async () => { + const { app, executable } = await fixtureApp(undefined); + const client = new NativeMacOSProvider( + new FixtureRunner(), + "darwin", + ).createClient(machoTarget(executable, app)); + await chmod(executable, 0); + try { + const signature = await client.execute("inspect_signature", {}); + expect(signature.ok).toBe(false); + if (signature.ok) throw new Error("Expected access denial"); + expect(projectAnalysisError(signature.error)).toMatchObject({ + code: "access_denied", + details: { path: executable }, + }); + } finally { + await chmod(executable, 0o600); + } + }, + ); + it("reports a regular ticket replaced by a directory as changed", async () => { const { app } = await fixtureApp(notarizationTicketFixture()); const ticket = await stapledTicket( @@ -548,7 +596,7 @@ describe("signature target version binding", () => { }); }, ); - it("downgrades facets when the executable changes between captures", async () => { + it("rejects observations when the executable changes between captures", async () => { const { app, executable } = await fixtureApp(undefined); const signature = await new NativeMacOSProvider( new ReplacingExecutableRunner(), @@ -556,18 +604,12 @@ describe("signature target version binding", () => { ) .createClient(machoTarget(executable, app)) .execute("inspect_signature", {}); - if (!signature.ok) throw signature.error; - const result = inspectSignatureSchema.parse(signature.value.result); - expect(result.verification?.status).toBe("valid"); - expect( - result.security_facets.every(({ state }) => state === "unknown"), - ).toBe(true); - expect(result.limitations).toContain( - `Signature target changed during inspection: ${executable}`, - ); - expect(result.security_facets[0]?.evidence).toContain( - "target version not bound", - ); + expect(signature.ok).toBe(false); + if (signature.ok) throw new Error("Expected target change"); + expect(projectAnalysisError(signature.error)).toMatchObject({ + code: "artifact_changed", + details: { path: executable }, + }); }); it.skipIf(process.getuid?.() === 0)( @@ -579,13 +621,29 @@ describe("signature target version binding", () => { await chmod(helpers, 0); try { const signature = await new NativeMacOSProvider( - new NewlinePathRunner(), + new (class extends FixtureRunner { + override async run(tool: string, args: readonly string[]) { + const result = await super.run(tool, args); + if (!result.ok || args[0] !== "--verify") return result; + const stderr = `--prepared:${helpers}/odd\n${app}: invalid signature\n${app}: permission denied\n`; + return ok({ + ...result.value, + exitCode: 1, + stderr, + stderrBytes: Buffer.byteLength(stderr), + }); + } + })(), "darwin", ) .createClient(machoTarget(executable, app)) .execute("inspect_signature", {}); if (!signature.ok) throw signature.error; const result = inspectSignatureSchema.parse(signature.value.result); + expect(result.verification?.status).toBe("unknown"); + expect(result.verification?.raw_stderr).toContain( + `${app}: invalid signature`, + ); expect(result.limitations).toContainEqual( expect.stringContaining("Could not confirm completeness"), );