refactor(native): isolate signature workflow and evidence classification

This commit is contained in:
morluto
2026-10-08 17:43:48 +08:00
parent d93f8209d4
commit c202ee9479
9 changed files with 534 additions and 479 deletions
+77
View File
@@ -0,0 +1,77 @@
import type { InspectSignature } from "../domain/native/nativeInspection.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
/** Strip the diagnostic's echoed pathname for classification, keeping the raw line elsewhere. */
export const codesignReason = (line: string, path: string): string => {
if (line.startsWith(`${path}: `)) return line.slice(path.length + 2);
if (line.startsWith("/")) {
const delimiter = line.lastIndexOf(": ");
return delimiter >= 0 ? line.slice(delimiter + 2) : "";
}
return line;
};
/** Classify only explicit diagnostic reasons; nonzero exit alone proves no invalidity. */
const verificationStatus = (
capture: NativeCommandCapture,
reasons: readonly string[],
unsigned: boolean,
): NonNullable<InspectSignature["verification"]>["status"] => {
if (capture.exitCode === 0) return "valid";
if (
reasons.some((reason) =>
/^(?:permission denied|operation not permitted|EACCES\b|EPERM\b|I\/O error|input\/output error)/iu.test(
reason,
),
)
)
return "unknown";
const unsignedReason = reasons.some((reason) =>
/^(?:code object is not signed at all|code object is not signed|not signed at all)/iu.test(
reason,
),
);
if (unsignedReason) return unsigned ? "unsigned" : "invalid";
if (
reasons.some((reason) =>
/^(?:a sealed resource is missing or invalid|code or signature modified|invalid signature|invalid or unsupported format|resource envelope is obsolete|signature is invalid|unsealed contents present|file modified:|file added:|a resource envelope is obsolete)/iu.test(
reason,
),
)
)
return "invalid";
return "unknown";
};
/** Project codesign verification without changing pathname bytes or discarding diagnostics. */
export const signatureVerification = (
capture: NativeCommandCapture,
path: string,
unsigned: boolean,
): NonNullable<InspectSignature["verification"]> => {
const lines = `${capture.stderr}\n${capture.stdout}`
.split("\n")
.filter((line) => line.length > 0);
const diagnostics = lines.filter(
(line) => !/^--(?:prepared|validated):/u.test(line),
);
return {
path,
status: verificationStatus(
capture,
diagnostics.map((line) => codesignReason(line, path)),
unsigned,
),
exit_code: capture.exitCode,
diagnostics,
validated_nested_code: [
...new Set(
lines.flatMap((line) =>
line.startsWith("--validated:")
? [line.slice("--validated:".length)]
: [],
),
),
].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
};
};
+12 -419
View File
@@ -8,7 +8,7 @@ import { observeNativeUi } from "./NativeUiObservation.js";
import { LldbCallTracer, type NativeCallTracer } from "./LldbCallTracer.js";
import { observeNativeCalls } from "./NativeCallObservation.js";
import { dirname, isAbsolute, resolve } from "node:path";
import { open, realpath, stat } from "node:fs/promises";
import { open, stat } from "node:fs/promises";
import { z } from "zod";
@@ -25,8 +25,6 @@ import {
type NativeToolName,
} from "../contracts/native/nativeToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import { canonicalJson } from "../domain/comparisonSemantics.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
@@ -37,14 +35,9 @@ import { BinaryTargetError } from "../domain/configurationErrors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import {
omittedPrototypeKeysLimitation,
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
import {
demangleSwiftSchema,
inspectPlistSchema,
inspectSignatureSchema,
listArchitecturesSchema,
type NativeCommandInvocation,
} from "../domain/native/nativeInspection.js";
@@ -55,19 +48,8 @@ import {
type NativeCommandCapture,
type NativeCommandRunner,
} from "./CommandRunner.js";
import { parseCodeSignature } from "./parsers/codesign.js";
import {
SIGNATURE_POSTURE_LIMITATIONS,
signatureVerification,
signedCodePath,
stapledTicket,
unconfirmedNestedCode,
} from "./NativeSignaturePosture.js";
import { deriveSecurityFacets } from "../domain/native/codeSigningPosture.js";
import {
signatureArchitectures,
summarizeSignatureSlices,
} from "./NativeSignatureSlices.js";
import { inspectNativeSignature } from "./NativeSignatureInspection.js";
import type { NativeObservation } from "./NativeObservation.js";
import { parseDemangledSymbols } from "./parsers/demangle.js";
import { parseLipoArchitectures } from "./parsers/lipo.js";
import {
@@ -335,341 +317,15 @@ class NativeMacOSClient implements AnalysisClient {
async #inspectSignature(
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
const display = await this.#run(
"inspect_signature",
"codesign",
["-d", "--verbose=4", this.target.path],
{ signal, acceptNonZero: true },
);
if (!display.ok) return display;
const unsigned = isNonzeroUnsignedObservation(display.value);
const displayFailure = codeSignCaptureFailure(display.value);
if (displayFailure !== null) return err(displayFailure);
const requirements = await this.#run(
"inspect_signature",
"codesign",
["-d", "-r-", this.target.path],
{ signal, acceptNonZero: true },
);
if (!requirements.ok) return requirements;
const requirementsFailure = codeSignCaptureFailure(requirements.value);
if (requirementsFailure !== null) return err(requirementsFailure);
const entitlements = await this.#run(
"inspect_signature",
"codesign",
["-d", "--entitlements", ":-", this.target.path],
{ signal, acceptNonZero: true },
);
if (!entitlements.ok) return entitlements;
const entitlementsFailure = codeSignCaptureFailure(entitlements.value);
if (entitlementsFailure !== null) return err(entitlementsFailure);
// codesign echoes the resolved executable path in its diagnostics.
const parsed = parseCodeSignature(display.value.stderr, unsigned, [
this.target.path,
...(await canonicalPath(this.target.path)),
]);
// The requirement is printed to stdout; stderr echoes the path.
const requirementText =
/designated\s*=>\s*(.+)$/mu.exec(requirements.value.stdout)?.[1] ?? null;
// Entitlements XML is printed to stdout; stderr echoes the path.
const entitlementValue = parseEntitlements(entitlements.value.stdout);
const verifyPath = signedCodePath(this.target);
const verify = await this.#verifySignature(verifyPath, signal);
if (!verify.ok) return verify;
const captures = [
display.value,
requirements.value,
entitlements.value,
verify.value,
];
// A platform identifier means a platform binary only in Apple's own
// signatures, which satisfy `anchor apple`; Developer ID code does not.
let appleOrigin = false;
if (
!unsigned &&
(parsed.code_directory?.platform_identifier ?? null) !== null
) {
const anchor = await this.#run(
"inspect_signature",
"codesign",
["--verify", "-R=anchor apple", verifyPath],
{ signal, acceptNonZero: true },
);
if (!anchor.ok) return anchor;
captures.push(anchor.value);
appleOrigin = anchor.value.exitCode === 0;
}
const limitations = [
...parsed.limitations,
...SIGNATURE_POSTURE_LIMITATIONS,
...(entitlementValue.omittedPrototypeKeys === 0
? []
: [
`Entitlements: ${omittedPrototypeKeysLimitation(entitlementValue.omittedPrototypeKeys)}`,
]),
];
const sliceState = await this.#sliceSigningState(
parsed.format,
requirements.value,
entitlements.value,
unsigned,
signal,
);
if (!sliceState.ok) return sliceState;
const mixedSigning = sliceState.value.mixed;
const aggregateUnsigned =
sliceState.value.signed === undefined
? unsigned
: !sliceState.value.signed;
captures.push(...sliceState.value.captures);
limitations.push(...sliceState.value.limitations);
// Only the top-level signature decides "unsigned"; unsigned nested
// code inside a signed bundle makes the bundle invalid.
const verification = signatureVerification(
verify.value,
verifyPath,
aggregateUnsigned,
);
if (
sliceState.value.classificationUnknown &&
verification.status !== "valid"
)
verification.status = "unknown";
limitations.push(...(await unconfirmedNestedCode(verification)));
if (verification.status === "unknown")
limitations.push(
"Signature verification could not read its target (permission or I/O diagnostic); the unknown status reflects an operational failure, not a proven broken signature.",
);
// Deep verification covers nested code: when it fails only there, the
// main executable's own signature may still be valid. Check it directly
// before hiding its facets as unauthenticated.
let mainInvalid =
verification.status === "invalid" || verification.status === "unknown";
if (mainInvalid && !unsigned && verifyPath !== this.target.path) {
const mainVerify = await this.#verifySignature(this.target.path, signal);
if (!mainVerify.ok) return mainVerify;
captures.push(mainVerify.value);
mainInvalid = mainVerify.value.exitCode !== 0;
}
const provenance = captures.map((capture) =>
invocation(capture, this.target.path),
);
const result = inspectSignatureSchema.parse({
...parsed,
signed: !aggregateUnsigned,
designated_requirement: requirementText,
entitlements: entitlementValue.value,
verification,
stapled_ticket: await stapledTicket(this.target, signal),
security_facets: deriveSecurityFacets({
signed: !aggregateUnsigned,
codeDirectory: parsed.code_directory,
entitlements: entitlementValue.value,
entitlementsKnown: unsigned || entitlements.value.exitCode === 0,
mixedSlices: mixedSigning,
appleOrigin,
signatureInvalid: mainInvalid,
}),
provenance,
limitations,
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: result.limitations,
locations: [],
});
}
/**
* Whether Mach-O slices differ in signing state. Aggregate `codesign -d`
* calls without `-a` report only the host-native slice of a universal
* binary, so universal files get per-slice probing before any aggregate
* signing claim; thin files keep the aggregate requirements/entitlements
* gate.
*/
async #sliceSigningState(
format: string | null,
requirements: NativeCommandCapture,
entitlements: NativeCommandCapture,
unsigned: boolean,
signal?: AbortSignal,
): Promise<
Result<
{
readonly mixed: boolean;
readonly captures: readonly NativeCommandCapture[];
readonly limitations: readonly string[];
readonly signed?: boolean;
readonly classificationUnknown: boolean;
},
AnalysisError
>
> {
const universal = signatureArchitectures(format, this.target).length > 1;
const gate =
!unsigned &&
(isNonzeroUnsignedObservation(requirements) ||
isNonzeroUnsignedObservation(entitlements));
if (!gate && !universal)
return ok({
mixed: false,
captures: [],
limitations: [],
classificationUnknown: false,
});
const slices = await this.#inspectMixedSignatureSlices(
format,
requirements.exitCode !== 0,
entitlements.exitCode !== 0,
signal,
);
if (!slices.ok) return slices;
return ok({
mixed: gate || (universal && slices.value.mixed),
captures: slices.value.captures,
limitations: slices.value.limitations,
...(slices.value.signed === undefined
? {}
: { signed: slices.value.signed }),
classificationUnknown: slices.value.classificationUnknown,
});
}
/** Local verification of the opened code, including nested code. */
#verifySignature(
path: string,
signal?: AbortSignal,
): Promise<Result<NativeCommandCapture, AnalysisError>> {
// --deep verifies nested frameworks, helpers, extensions and XPC services.
return this.#run(
"inspect_signature",
"codesign",
["--verify", "--deep", "--strict", "--verbose=2", path],
{ signal, acceptNonZero: true },
);
}
async #inspectMixedSignatureSlices(
format: string | null,
requirementsUnavailable: boolean,
entitlementsUnavailable: boolean,
signal?: AbortSignal,
): Promise<Result<MixedSignatureSlices, AnalysisError>> {
const captures: NativeCommandCapture[] = [];
const signed: string[] = [];
const unsigned: string[] = [];
const unclassified: string[] = [];
const postures = new Map<string, string>();
for (const architecture of signatureArchitectures(format, this.target)) {
const slice = await this.#run(
"inspect_signature",
"codesign",
["-d", "-a", architecture, "--verbose=4", this.target.path],
{ signal, acceptNonZero: true },
);
if (!slice.ok) return slice;
captures.push(slice.value);
if (slice.value.exitCode === 0) {
signed.push(architecture);
const posture = await this.#slicePosture(
architecture,
slice.value,
signal,
);
if (!posture.ok) return posture;
captures.push(posture.value.capture);
if (posture.value.posture === null) unclassified.push(architecture);
else postures.set(architecture, posture.value.posture);
continue;
}
if (isNonzeroUnsignedObservation(slice.value))
unsigned.push(architecture);
else unclassified.push(architecture);
}
// Slices differ in signing state when a signed slice coexists with an
// unsigned or unclassifiable one; all-signed or all-unsigned files agree.
// Signed slices can still disagree among themselves: per-architecture
// display is authoritative per slice, so differing flags or entitlements
// also make the aggregate facets unknown.
const summary = summarizeSignatureSlices({
signed,
unsigned,
unclassified,
postures,
});
const limitations: string[] = [];
if (unsigned.length > 0)
limitations.push(`Unsigned Mach-O slices: ${unsigned.join(", ")}.`);
if (
summary.postureDiffers &&
unsigned.length === 0 &&
unclassified.length === 0
)
limitations.push(
"Signed Mach-O slices differ in CodeDirectory flags or entitlements; aggregate facets are unknown.",
);
if (unclassified.length > 0)
limitations.push(
`Signature state could not be classified for Mach-O slices: ${unclassified.join(", ")}.`,
);
if (requirementsUnavailable)
limitations.push(
"The aggregate designated requirement is unavailable because Mach-O slices have mixed signing states.",
);
if (entitlementsUnavailable)
limitations.push(
"The aggregate entitlements are unavailable because Mach-O slices have mixed signing states.",
);
return ok({ captures, limitations, ...summary });
}
/**
* Canonical posture of one signed slice: sorted CodeDirectory flag names and
* entitlements. Null when the slice display cannot be parsed; the slice
* still counts as signed from its zero exit code.
*/
async #slicePosture(
architecture: string,
display: NativeCommandCapture,
signal?: AbortSignal,
): Promise<
Result<
{
readonly posture: string | null;
readonly capture: NativeCommandCapture;
},
AnalysisError
>
> {
const entitlements = await this.#run(
"inspect_signature",
"codesign",
["-d", "--entitlements", ":-", "-a", architecture, this.target.path],
{ signal, acceptNonZero: true },
);
if (!entitlements.ok) return entitlements;
const parsed = parseCodeSignature(display.stderr, false, [
this.target.path,
]);
const directory = parsed.code_directory;
if (
directory?.flags === null ||
directory === null ||
entitlements.value.exitCode !== 0
)
return ok({ posture: null, capture: entitlements.value });
const entitlementValue = parseEntitlements(entitlements.value.stdout);
return ok({
posture: canonicalJson(
{
flags: directory.flags.value,
platform: directory.platform_identifier,
entitlements: entitlementValue.value,
},
"Signature slice posture",
),
capture: entitlements.value,
return inspectNativeSignature({
target: this.target,
capture: (argv, commandSignal) =>
this.#run("inspect_signature", "codesign", argv, {
signal: commandSignal,
acceptNonZero: true,
}),
invocation: (capture) => invocation(capture, this.target.path),
...(signal === undefined ? {} : { signal }),
});
}
@@ -795,22 +451,6 @@ class NativeMacOSClient implements AnalysisClient {
}
}
interface NativeObservation {
readonly result: JsonValue;
readonly provenance: readonly NativeCommandInvocation[];
readonly limitations: readonly string[];
readonly locations: readonly EvidenceLocation[];
}
interface MixedSignatureSlices {
readonly captures: readonly NativeCommandCapture[];
readonly limitations: readonly string[];
/** A signed slice coexists with an unsigned or unclassifiable one. */
readonly mixed: boolean;
readonly signed: boolean | undefined;
readonly classificationUnknown: boolean;
}
const isNativeOperation = (
operation: AnalysisOperation,
): operation is NativeToolName =>
@@ -831,41 +471,6 @@ const translateCommandFailure = (
return new ProviderAdapterError(IDENTITY.id, operation, { cause: failure });
};
const translateCodeSignExitFailure = (
capture: NativeCommandCapture,
): AnalysisError =>
translateCommandFailure(
"inspect_signature",
new NativeCommandFailure("codesign", "nonzero-exit", capture.exitCode),
);
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.
*/
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 canonicalPath = async (path: string): Promise<string[]> => {
try {
return [await realpath(path)];
} catch {
return [];
}
};
const codeSignCaptureFailure = (
capture: NativeCommandCapture,
): AnalysisError | null =>
capture.exitCode === 0 || isNonzeroUnsignedObservation(capture)
? null
: translateCodeSignExitFailure(capture);
const invocation = (
capture: NativeCommandCapture,
artifactPath: string,
@@ -886,18 +491,6 @@ const invocation = (
stderr_bytes: capture.stderrBytes,
});
const parseEntitlements = (
output: string,
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
const start = output.indexOf("<?xml");
const end = output.lastIndexOf("</plist>");
if (start < 0 || end < start) return { value: null, omittedPrototypeKeys: 0 };
const { value, omittedPrototypeKeys } = parseXmlPropertyList(
output.slice(start, end + "</plist>".length),
);
return { value: jsonValueSchema.parse(value), omittedPrototypeKeys };
};
/**
* Report a plist that cannot be decoded as the caller's selection, or as the
* target's missing default, rather than as a failed tool run.
+11
View File
@@ -0,0 +1,11 @@
import type { JsonValue } from "../domain/jsonValue.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { NativeCommandInvocation } from "../domain/native/nativeInspection.js";
/** Provider observation before shared execution/Evidence projection. */
export interface NativeObservation {
readonly result: JsonValue;
readonly provenance: readonly NativeCommandInvocation[];
readonly limitations: readonly string[];
readonly locations: readonly EvidenceLocation[];
}
+15
View File
@@ -0,0 +1,15 @@
import { parseXmlPropertyList } from "../domain/propertyListKeys.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
/** Parse the XML entitlement document within codesign output, retaining omission evidence. */
export const parseSignatureEntitlements = (
output: string,
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
const start = output.indexOf("<?xml");
const end = output.lastIndexOf("</plist>");
if (start < 0 || end < start) return { value: null, omittedPrototypeKeys: 0 };
const { value, omittedPrototypeKeys } = parseXmlPropertyList(
output.slice(start, end + "</plist>".length),
);
return { value: jsonValueSchema.parse(value), omittedPrototypeKeys };
};
+189
View File
@@ -0,0 +1,189 @@
import { realpath } from "node:fs/promises";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
inspectSignatureSchema,
type NativeCommandInvocation,
} from "../domain/native/nativeInspection.js";
import { deriveSecurityFacets } from "../domain/native/codeSigningPosture.js";
import { omittedPrototypeKeysLimitation } from "../domain/propertyListKeys.js";
import { err, ok, type Result } from "../domain/result.js";
import {
NativeCommandFailure,
type NativeCommandCapture,
} from "./CommandRunner.js";
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";
import type { NativeObservation } from "./NativeObservation.js";
import { signatureVerification } from "./CodesignVerification.js";
import { parseCodeSignature } from "./parsers/codesign.js";
import { parseSignatureEntitlements } from "./NativeSignatureEntitlements.js";
import {
inspectSignatureSlices,
unsignedSignatureCapture,
type SignatureCapture,
} from "./NativeSignatureProbes.js";
import {
SIGNATURE_POSTURE_LIMITATIONS,
signedCodePath,
stapledTicket,
unconfirmedNestedCode,
} from "./NativeSignaturePosture.js";
interface SignatureDisplays {
readonly display: NativeCommandCapture;
readonly requirements: NativeCommandCapture;
readonly entitlements: NativeCommandCapture;
}
/** Display failures and unsigned observations use the same reason parser as verification. */
const signatureDisplays = async (
path: string,
capture: SignatureCapture,
signal?: AbortSignal,
): Promise<Result<SignatureDisplays, AnalysisError>> => {
const display = await capture(["-d", "--verbose=4", path], signal);
if (!display.ok) return display;
const requirements = await capture(["-d", "-r-", path], signal);
if (!requirements.ok) return requirements;
const entitlements = await capture(
["-d", "--entitlements", ":-", path],
signal,
);
if (!entitlements.ok) return entitlements;
for (const result of [
display.value,
requirements.value,
entitlements.value,
]) {
if (result.exitCode !== 0 && !unsignedSignatureCapture(result, path))
return err(
new ProviderAdapterError(
NATIVE_MACOS_PROVIDER_IDENTITY.id,
"inspect_signature",
{
cause: new NativeCommandFailure(
"codesign",
"nonzero-exit",
result.exitCode,
),
},
),
);
}
return ok({
display: display.value,
requirements: requirements.value,
entitlements: entitlements.value,
});
};
/** Compose displays, independent slice knowledge, verification, and local ticket evidence. */
export const inspectNativeSignature = async (options: {
readonly target: BinaryTarget;
readonly capture: SignatureCapture;
readonly invocation: (
capture: NativeCommandCapture,
) => NativeCommandInvocation;
readonly signal?: AbortSignal;
}): Promise<Result<NativeObservation, AnalysisError>> => {
const { target, capture, signal } = options;
const displays = await signatureDisplays(target.path, capture, signal);
if (!displays.ok) return displays;
const { display, requirements, entitlements } = displays.value;
const unsigned = unsignedSignatureCapture(display, target.path);
let canonical: string[] = [];
try {
canonical = [await realpath(target.path)];
} catch {
/* The display retains the observed path. */
}
const parsed = parseCodeSignature(display.stderr, unsigned, [
target.path,
...canonical,
]);
const entitlementValue = parseSignatureEntitlements(entitlements.stdout);
const code = signedCodePath(target);
const verify = (path: string) =>
capture(["--verify", "--deep", "--strict", "--verbose=2", path], signal);
const verified = await verify(code);
if (!verified.ok) return verified;
const captures = [display, requirements, entitlements, verified.value];
let appleOrigin = false;
if (
!unsigned &&
(parsed.code_directory?.platform_identifier ?? null) !== null
) {
const anchor = await capture(["--verify", "-R=anchor apple", code], signal);
if (!anchor.ok) return anchor;
captures.push(anchor.value);
appleOrigin = anchor.value.exitCode === 0;
}
const slices = await inspectSignatureSlices(
target,
{ format: parsed.format, requirements, entitlements, unsigned },
capture,
signal,
);
if (!slices.ok) return slices;
captures.push(...slices.value.captures);
const aggregateUnsigned =
slices.value.signed === undefined ? unsigned : !slices.value.signed;
// Verification is independent evidence: uncertain display probes must not
// erase an explicit signature failure from the verifier.
const verification = signatureVerification(
verified.value,
code,
aggregateUnsigned,
);
const limitations = [
...parsed.limitations,
...SIGNATURE_POSTURE_LIMITATIONS,
...slices.value.limitations,
...(await unconfirmedNestedCode(verification)),
];
if (entitlementValue.omittedPrototypeKeys !== 0)
limitations.push(
`Entitlements: ${omittedPrototypeKeysLimitation(entitlementValue.omittedPrototypeKeys)}`,
);
if (verification.status === "unknown")
limitations.push(
"Signature verification is inconclusive (permission, I/O or unrecognized diagnostic); this is not a proven broken signature.",
);
let mainInvalid =
verification.status === "invalid" || verification.status === "unknown";
if (mainInvalid && !unsigned && code !== target.path) {
const main = await verify(target.path);
if (!main.ok) return main;
captures.push(main.value);
mainInvalid = main.value.exitCode !== 0;
}
const provenance = captures.map(options.invocation);
const result = inspectSignatureSchema.parse({
...parsed,
signed: !aggregateUnsigned,
designated_requirement:
/designated\s*=>\s*(.+)$/mu.exec(requirements.stdout)?.[1] ?? null,
entitlements: entitlementValue.value,
verification,
stapled_ticket: await stapledTicket(target, signal),
security_facets: deriveSecurityFacets({
signed: !aggregateUnsigned,
codeDirectory: parsed.code_directory,
entitlements: entitlementValue.value,
entitlementsKnown: unsigned || entitlements.exitCode === 0,
mixedSlices: slices.value.mixed,
appleOrigin,
signatureInvalid: mainInvalid,
}),
provenance,
limitations,
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: result.limitations,
locations: [],
});
};
-57
View File
@@ -4,7 +4,6 @@ import { lstat, open, readdir } from "node:fs/promises";
import { dirname, join } from "node:path";
import type { InspectSignature } from "../domain/native/nativeInspection.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
import { ticketStructureIssue } from "./NotarizationTicket.js";
/** Notarization tickets are a few kilobytes; larger files are hashed in chunks. */
@@ -49,62 +48,6 @@ const bundleDirFromPlist = (plist: string): string | undefined => {
return undefined;
};
/**
* Project a local `codesign --verify --strict` capture without reinterpreting
* its messages. codesign validates nested code concurrently, so its
* `--prepared:`/`--validated:` progress lines arrive in no fixed order; they
* are reported as a sorted list of validated nested code instead.
*/
/** Diagnostics showing verification could not read its target. */
export const verificationIOFailure = (
diagnostics: readonly string[],
): boolean =>
diagnostics.some((line) =>
/permission denied|operation not permitted|\bEACCES\b|\bEPERM\b|I\/O error|input\/output error/iu.test(
line,
),
);
export const signatureVerification = (
capture: NativeCommandCapture,
path: string,
unsigned: boolean,
): NonNullable<InspectSignature["verification"]> => {
// Preserve trailing whitespace and carriage returns: a nested path may end
// in a space, tab, or CR. codesign delimits records with LF, so split on LF
// only and strip leading whitespace for record parsing.
const lines = `${capture.stderr}\n${capture.stdout}`
.split(/\n/u)
.filter((line) => line.length > 0);
const record = (line: string): string => line.replace(/^\s+/u, "");
const diagnostics = lines.filter(
(line) => !/^--(?:prepared|validated):/u.test(record(line)),
);
return {
path,
status:
capture.exitCode === 0
? "valid"
: unsigned
? "unsigned"
: verificationIOFailure(diagnostics)
? "unknown"
: "invalid",
exit_code: capture.exitCode,
diagnostics,
validated_nested_code: [
...new Set(
lines.flatMap((line) => {
const trimmed = record(line);
return trimmed.startsWith("--validated:")
? [trimmed.slice("--validated:".length)]
: [];
}),
),
].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0)),
};
};
/**
* Report a ticket stapled to an app bundle, which `stapler` stores at
* `Contents/CodeResources`. Presence is observed; the ticket's validity and
+150
View File
@@ -0,0 +1,150 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { canonicalJson } from "../domain/comparisonSemantics.js";
import { ok, type Result } from "../domain/result.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
import { codesignReason } from "./CodesignVerification.js";
import { parseCodeSignature } from "./parsers/codesign.js";
import { parseSignatureEntitlements } from "./NativeSignatureEntitlements.js";
import {
signatureArchitectures,
summarizeSignatureSlices,
} from "./NativeSignatureSlices.js";
/** The provider owns process execution and typed failure translation. */
export type SignatureCapture = (
argv: readonly string[],
signal?: AbortSignal,
) => Promise<Result<NativeCommandCapture, AnalysisError>>;
/** Detect explicit unsigned display reasons, not words embedded in echoed pathnames. */
export const unsignedSignatureCapture = (
capture: NativeCommandCapture,
path: string,
): boolean =>
capture.exitCode !== null &&
capture.exitCode !== 0 &&
`${capture.stderr}\n${capture.stdout}`
.split("\n")
.some((line) =>
/^(?:code object is not signed at all|code object is not signed|not signed at all)/iu.test(
codesignReason(line, path),
),
);
/** Slice observations and aggregate knowledge, with every contributing capture retained. */
export interface SignatureSliceObservation {
readonly mixed: boolean;
readonly captures: readonly NativeCommandCapture[];
readonly limitations: readonly string[];
readonly signed: boolean | undefined;
readonly classificationUnknown: boolean;
}
/** Proactively inspect independent signatures of universal Mach-O architectures. */
export const inspectSignatureSlices = async (
target: BinaryTarget,
input: {
readonly format: string | null;
readonly requirements: NativeCommandCapture;
readonly entitlements: NativeCommandCapture;
readonly unsigned: boolean;
},
capture: SignatureCapture,
signal?: AbortSignal,
): Promise<Result<SignatureSliceObservation, AnalysisError>> => {
const architectures = signatureArchitectures(input.format, target);
const gate =
!input.unsigned &&
(unsignedSignatureCapture(input.requirements, target.path) ||
unsignedSignatureCapture(input.entitlements, target.path));
if (!gate && architectures.length <= 1)
return ok({
mixed: false,
captures: [],
limitations: [],
signed: undefined,
classificationUnknown: false,
});
const captures: NativeCommandCapture[] = [];
const signed: string[] = [];
const unsigned: string[] = [];
const unclassified: string[] = [];
const postures = new Map<string, string>();
for (const architecture of architectures) {
const display = await capture(
["-d", "-a", architecture, "--verbose=4", target.path],
signal,
);
if (!display.ok) return display;
captures.push(display.value);
if (display.value.exitCode !== 0) {
(unsignedSignatureCapture(display.value, target.path)
? unsigned
: unclassified
).push(architecture);
continue;
}
signed.push(architecture);
const entitlements = await capture(
["-d", "--entitlements", ":-", "-a", architecture, target.path],
signal,
);
if (!entitlements.ok) return entitlements;
captures.push(entitlements.value);
const directory = parseCodeSignature(display.value.stderr, false, [
target.path,
]).code_directory;
if (
directory?.flags === null ||
directory === null ||
entitlements.value.exitCode !== 0
) {
unclassified.push(architecture);
continue;
}
postures.set(
architecture,
canonicalJson(
{
flags: directory.flags.value,
platform: directory.platform_identifier,
entitlements: parseSignatureEntitlements(entitlements.value.stdout)
.value,
},
"Signature slice posture",
),
);
}
const summary = summarizeSignatureSlices({
signed,
unsigned,
unclassified,
postures,
});
const limitations: string[] = [];
if (unsigned.length > 0)
limitations.push(`Unsigned Mach-O slices: ${unsigned.join(", ")}.`);
if (summary.postureDiffers)
limitations.push(
"Signed Mach-O slices differ in CodeDirectory flags or entitlements; aggregate facets are unknown.",
);
if (unclassified.length > 0)
limitations.push(
`Signature state could not be classified for Mach-O slices: ${unclassified.join(", ")}.`,
);
if (gate && input.requirements.exitCode !== 0)
limitations.push(
"The aggregate designated requirement is unavailable because Mach-O slices have mixed signing states.",
);
if (gate && input.entitlements.exitCode !== 0)
limitations.push(
"The aggregate entitlements are unavailable because Mach-O slices have mixed signing states.",
);
return ok({
...summary,
mixed: gate || summary.mixed,
captures,
limitations,
});
};
@@ -0,0 +1,49 @@
import { expect, it } from "vitest";
import { signatureVerification } from "../../../../src/native/CodesignVerification.js";
import { NativeFixtureRunner } from "../../../fixtures/nativeCommands.js";
it.each(["permission denied", "I/O error", "EACCES"])(
"does not classify echoed pathname %s as an I/O failure",
async (text) => {
const path = `/Applications/${text}.app`;
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const observed = signatureVerification(
{
...capture.value,
exitCode: 1,
stderr: `${path}: a sealed resource is missing or invalid\n`,
},
path,
false,
);
expect(observed.status).toBe("invalid");
expect(observed.diagnostics).toEqual([
`${path}: a sealed resource is missing or invalid`,
]);
},
);
it("keeps operational, unsigned, definite invalid and unrecognized failures distinct", async () => {
const path = "/Applications/Fixture.app";
const capture = await new NativeFixtureRunner().run("codesign", [
"--verify",
path,
]);
if (!capture.ok) throw capture.error;
const status = (reason: string, unsigned = false) =>
signatureVerification(
{ ...capture.value, exitCode: 1, stderr: `${path}: ${reason}\n` },
path,
unsigned,
).status;
expect(status("permission denied")).toBe("unknown");
expect(status("I/O error")).toBe("unknown");
expect(status("invalid signature")).toBe("invalid");
expect(status("code object is not signed at all", true)).toBe("unsigned");
expect(status("code object is not signed at all")).toBe("invalid");
expect(status("unrecognized failure")).toBe("unknown");
});
@@ -388,14 +388,28 @@ describe("native signature posture slice-aware cases", () => {
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.verification?.status).toBe("unknown");
expect(result.limitations).toContainEqual(
expect.stringContaining(
"operational failure, not a proven broken signature",
),
expect.stringContaining("not a proven broken signature"),
);
});
});
describe("signature architecture coverage", () => {
it("does not let uncertain display probes hide definitive verification failure", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new DefiniteInvalidWithUncertainSlicesRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
if (!signature.ok) throw signature.error;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.signed).toBe(true);
expect(result.verification?.status).toBe("invalid");
expect(result.limitations).toContainEqual(
expect.stringContaining("could not be classified"),
);
});
it("does not turn inconclusive slice probes into an unsigned claim", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
@@ -606,6 +620,20 @@ class InconclusiveSlicesRunner extends FixtureRunner {
}
}
/** Slice display uncertainty and an independently established invalid signature. */
class DefiniteInvalidWithUncertainSlicesRunner extends InconclusiveSlicesRunner {
override async run(tool: string, arguments_: readonly string[]) {
const result = await super.run(tool, arguments_);
if (!result.ok || arguments_[0] !== "--verify") return result;
const stderr = `${arguments_.at(-1)}: invalid signature\n`;
return ok({
...result.value,
stderr,
stderrBytes: Buffer.byteLength(stderr),
});
}
}
/** A nested helper whose file name ends in a carriage return. */
class CarriageReturnPathRunner extends FixtureRunner {
override async run(tool: string, arguments_: readonly string[]) {