feat(native): report code-signing posture in inspect_signature
inspect_signature reduced the CodeDirectory to a hardened-runtime boolean and never verified the signature. It now also reports: - the parsed CodeDirectory: version, flags decoded from their numeric value (runtime, library-validation, restrict, kill, adhoc, linker-signed, unknown bits in hex), code and special slot counts, location, hash type, platform identifier, runtime version, and executable-segment flags; - sealed resources (version, rules, files, or none); - a local `codesign --verify --strict` result on the opened bundle or Mach-O, with diagnostics and the sorted nested code it validated; - whether a notarization ticket is stapled at Contents/CodeResources, with its digest. The ticket and Apple's records are not checked because that needs the network; - derived security facets with their supporting evidence: library validation, DYLD_* handling, debugger attach, executable-memory policy, and App Sandbox. Facets stay unknown when flags or aggregate entitlements are unavailable. verify:code-signature re-signs copies of the clang-built fixture with real codesign (ad hoc, hardened runtime, hardened runtime with relaxing entitlements, library,restrict). It also checks a platform binary and a tampered bundle, with CLI/MCP parity, and runs in the macOS CI job. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
dcde958450
commit
25ca63f231
@@ -53,6 +53,13 @@ import {
|
||||
type NativeCommandRunner,
|
||||
} from "./CommandRunner.js";
|
||||
import { parseCodeSignature } from "./parsers/codesign.js";
|
||||
import {
|
||||
SIGNATURE_POSTURE_LIMITATIONS,
|
||||
signatureVerification,
|
||||
signedCodePath,
|
||||
stapledTicket,
|
||||
} from "./NativeSignaturePosture.js";
|
||||
import { deriveSecurityFacets } from "../domain/codeSigningPosture.js";
|
||||
import { parseDemangledSymbols } from "./parsers/demangle.js";
|
||||
import { parseLipoArchitectures } from "./parsers/lipo.js";
|
||||
import {
|
||||
@@ -335,9 +342,23 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
/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 captures = [display.value, requirements.value, entitlements.value];
|
||||
const verifyPath = signedCodePath(this.target);
|
||||
const verify = await this.#run(
|
||||
"inspect_signature",
|
||||
"codesign",
|
||||
["--verify", "--strict", "--verbose=2", verifyPath],
|
||||
{ signal, acceptNonZero: true },
|
||||
);
|
||||
if (!verify.ok) return verify;
|
||||
const captures = [
|
||||
display.value,
|
||||
requirements.value,
|
||||
entitlements.value,
|
||||
verify.value,
|
||||
];
|
||||
const limitations = [
|
||||
...parsed.limitations,
|
||||
...SIGNATURE_POSTURE_LIMITATIONS,
|
||||
...(entitlementValue.omittedPrototypeKeys === 0
|
||||
? []
|
||||
: [
|
||||
@@ -366,6 +387,18 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
...parsed,
|
||||
designated_requirement: requirementText,
|
||||
entitlements: entitlementValue.value,
|
||||
verification: signatureVerification(
|
||||
verify.value,
|
||||
verifyPath,
|
||||
isNonzeroUnsignedObservation(verify.value),
|
||||
),
|
||||
stapled_ticket: await stapledTicket(this.target, signal),
|
||||
security_facets: deriveSecurityFacets({
|
||||
signed: !unsigned,
|
||||
codeDirectory: parsed.code_directory,
|
||||
entitlements: entitlementValue.value,
|
||||
entitlementsKnown: unsigned || entitlements.value.exitCode === 0,
|
||||
}),
|
||||
provenance,
|
||||
limitations,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { InspectSignature } from "../domain/nativeInspection.js";
|
||||
import type { NativeCommandCapture } from "./CommandRunner.js";
|
||||
|
||||
/** Notarization tickets are a few kilobytes; larger files are hashed in chunks. */
|
||||
const HASH_CHUNK_BYTES = 64 * 1024;
|
||||
|
||||
/** The code `codesign --verify` should check: the bundle when one was opened. */
|
||||
export const signedCodePath = (target: {
|
||||
readonly path: string;
|
||||
readonly sourcePath?: string;
|
||||
}): string =>
|
||||
target.sourcePath?.toLowerCase().endsWith(".app") === true
|
||||
? target.sourcePath
|
||||
: target.path;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
export const signatureVerification = (
|
||||
capture: NativeCommandCapture,
|
||||
path: string,
|
||||
unsigned: boolean,
|
||||
): NonNullable<InspectSignature["verification"]> => {
|
||||
const lines = `${capture.stderr}\n${capture.stdout}`
|
||||
.split(/\r?\n/u)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
return {
|
||||
path,
|
||||
status:
|
||||
capture.exitCode === 0 ? "valid" : unsigned ? "unsigned" : "invalid",
|
||||
exit_code: capture.exitCode,
|
||||
diagnostics: lines.filter(
|
||||
(line) => !/^--(?:prepared|validated):/u.test(line),
|
||||
),
|
||||
validated_nested_code: [
|
||||
...new Set(
|
||||
lines.flatMap((line) =>
|
||||
line.startsWith("--validated:")
|
||||
? [line.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
|
||||
* Apple's notarization record are not checked, because that needs the network.
|
||||
*/
|
||||
export const stapledTicket = async (
|
||||
target: { readonly sourcePath?: string },
|
||||
signal?: AbortSignal,
|
||||
): Promise<InspectSignature["stapled_ticket"]> => {
|
||||
const bundle = target.sourcePath;
|
||||
if (bundle?.toLowerCase().endsWith(".app") !== true)
|
||||
return { status: "not-applicable", path: null, sha256: null, size: null };
|
||||
const relative = "Contents/CodeResources";
|
||||
const path = join(bundle, relative);
|
||||
try {
|
||||
const metadata = await lstat(path);
|
||||
if (!metadata.isFile())
|
||||
return { status: "absent", path: null, sha256: null, size: null };
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
|
||||
)
|
||||
return { status: "absent", path: null, sha256: null, size: null };
|
||||
throw cause;
|
||||
}
|
||||
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const hash = createHash("sha256");
|
||||
const buffer = new Uint8Array(HASH_CHUNK_BYTES);
|
||||
let size = 0;
|
||||
for (;;) {
|
||||
signal?.throwIfAborted();
|
||||
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
||||
if (bytesRead === 0) break;
|
||||
size += bytesRead;
|
||||
hash.update(buffer.subarray(0, bytesRead));
|
||||
}
|
||||
return {
|
||||
status: "present",
|
||||
path: relative,
|
||||
sha256: hash.digest("hex"),
|
||||
size,
|
||||
};
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** Limitations that keep verification and notarization claims bounded. */
|
||||
export const SIGNATURE_POSTURE_LIMITATIONS = [
|
||||
"Signature verification is local `codesign --verify --strict`; certificate revocation, Gatekeeper policy, and Apple's notarization records are not checked.",
|
||||
"Security facets are derived from CodeDirectory flags and entitlements; runtime policy such as System Integrity Protection, AMFI, and setuid bits can further restrict a process.",
|
||||
];
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseCodeSignature } from "./codesign.js";
|
||||
|
||||
const display = (lines: readonly string[]): string =>
|
||||
[
|
||||
"Identifier=com.example.fixture",
|
||||
"Format=app bundle with Mach-O thin (arm64)",
|
||||
...lines,
|
||||
"TeamIdentifier=TEAM12345",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
describe("codesign CodeDirectory parsing", () => {
|
||||
it("decodes CodeDirectory fields and flags from the numeric value", () => {
|
||||
const parsed = parseCodeSignature(
|
||||
display([
|
||||
"CodeDirectory v=20500 size=443 flags=0x12a00(kill,restrict,library-validation,runtime) hashes=3209+7 location=embedded",
|
||||
"Platform identifier=26",
|
||||
"Hash type=sha256 size=32",
|
||||
"Executable Segment flags=0x1",
|
||||
"Runtime Version=26.4.0",
|
||||
"Sealed Resources version=2 rules=13 files=290",
|
||||
]),
|
||||
false,
|
||||
);
|
||||
expect(parsed.code_directory).toEqual({
|
||||
version: "20500",
|
||||
flags: {
|
||||
value: 0x12a00,
|
||||
names: ["kill", "restrict", "library-validation", "runtime"],
|
||||
},
|
||||
code_slots: 3209,
|
||||
special_slots: 7,
|
||||
location: "embedded",
|
||||
hash_type: "sha256",
|
||||
platform_identifier: 26,
|
||||
runtime_version: "26.4.0",
|
||||
executable_segment_flags: 1,
|
||||
});
|
||||
expect(parsed.hardened_runtime).toBe(true);
|
||||
expect(parsed.sealed_resources).toEqual({
|
||||
status: "sealed",
|
||||
version: 2,
|
||||
rules: 13,
|
||||
files: 290,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports unsealed, unsigned and incomplete output without guessing", () => {
|
||||
const bare = parseCodeSignature(
|
||||
display([
|
||||
"CodeDirectory v=20400 size=336 location=embedded",
|
||||
"Sealed Resources=none",
|
||||
]),
|
||||
false,
|
||||
);
|
||||
expect(bare.code_directory).toMatchObject({
|
||||
flags: null,
|
||||
code_slots: null,
|
||||
platform_identifier: null,
|
||||
});
|
||||
expect(bare.sealed_resources.status).toBe("none");
|
||||
expect(parseCodeSignature(display([]), false)).toMatchObject({
|
||||
code_directory: null,
|
||||
sealed_resources: { status: "unknown" },
|
||||
});
|
||||
expect(
|
||||
parseCodeSignature("fixture: code object is not signed at all\n", true),
|
||||
).toMatchObject({
|
||||
signed: false,
|
||||
code_directory: null,
|
||||
sealed_resources: { status: "none" },
|
||||
stapled_ticket: { status: "not-applicable" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
codeDirectoryFlagNames,
|
||||
type CodeDirectory,
|
||||
} from "../../domain/codeSigningPosture.js";
|
||||
import {
|
||||
inspectSignatureSchema,
|
||||
type InspectSignature,
|
||||
@@ -23,11 +27,21 @@ export const parseCodeSignature = (
|
||||
const values = new Map<string, string>();
|
||||
const authorities: string[] = [];
|
||||
const cdhashes: string[] = [];
|
||||
let sealed: InspectSignature["sealed_resources"] = {
|
||||
status: "unknown",
|
||||
version: null,
|
||||
rules: null,
|
||||
files: null,
|
||||
};
|
||||
for (const line of fields.split("\n")) {
|
||||
if (line.startsWith("CodeDirectory ")) {
|
||||
values.set("CodeDirectory", line.slice("CodeDirectory ".length));
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("Sealed Resources")) {
|
||||
sealed = parseSealedResources(line);
|
||||
continue;
|
||||
}
|
||||
const separator = line.indexOf("=");
|
||||
if (separator < 1) continue;
|
||||
const key = line.slice(0, separator).trim();
|
||||
@@ -48,6 +62,18 @@ export const parseCodeSignature = (
|
||||
entitlements: null,
|
||||
timestamp: values.get("Timestamp") ?? null,
|
||||
hardened_runtime: parseRuntime(values.get("CodeDirectory")),
|
||||
code_directory: unsigned ? null : parseCodeDirectory(values),
|
||||
sealed_resources: unsigned
|
||||
? { status: "none", version: null, rules: null, files: null }
|
||||
: sealed,
|
||||
verification: null,
|
||||
stapled_ticket: {
|
||||
status: "not-applicable",
|
||||
path: null,
|
||||
sha256: null,
|
||||
size: null,
|
||||
},
|
||||
security_facets: [],
|
||||
limitations: unsigned
|
||||
? ["Artifact is not signed."]
|
||||
: [
|
||||
@@ -104,3 +130,62 @@ const parseRuntime = (value: string | undefined): boolean | null => {
|
||||
if (flags === undefined) return null;
|
||||
return flags.split(",").some((flag) => flag.trim() === "runtime");
|
||||
};
|
||||
|
||||
const integerField = (
|
||||
text: string | undefined,
|
||||
pattern: RegExp,
|
||||
radix = 10,
|
||||
): number | null => {
|
||||
const match = text === undefined ? undefined : pattern.exec(text)?.[1];
|
||||
if (match === undefined) return null;
|
||||
const value = Number.parseInt(match, radix);
|
||||
return Number.isSafeInteger(value) ? value : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* `CodeDirectory v=20500 size=… flags=0x10000(runtime) hashes=3209+7
|
||||
* location=embedded`, plus the separate hash, platform, runtime-version and
|
||||
* executable-segment lines. Flag names are decoded from the numeric value.
|
||||
*/
|
||||
const parseCodeDirectory = (
|
||||
values: ReadonlyMap<string, string>,
|
||||
): CodeDirectory | null => {
|
||||
const line = values.get("CodeDirectory");
|
||||
if (line === undefined) return null;
|
||||
const flags = integerField(line, /(?:^|\s)flags=0x([0-9a-f]+)/iu, 16);
|
||||
return {
|
||||
version: /(?:^|\s)v=(\S+)/u.exec(line)?.[1] ?? null,
|
||||
flags:
|
||||
flags === null
|
||||
? null
|
||||
: { value: flags, names: codeDirectoryFlagNames(flags) },
|
||||
code_slots: integerField(line, /(?:^|\s)hashes=(\d+)\+/u),
|
||||
special_slots: integerField(line, /(?:^|\s)hashes=\d+\+(\d+)/u),
|
||||
location: /(?:^|\s)location=(\S+)/u.exec(line)?.[1] ?? null,
|
||||
hash_type: values.get("Hash type")?.split(/\s+/u)[0] ?? null,
|
||||
platform_identifier: integerField(
|
||||
values.get("Platform identifier"),
|
||||
/^(\d+)$/u,
|
||||
),
|
||||
runtime_version: values.get("Runtime Version") ?? null,
|
||||
executable_segment_flags: integerField(
|
||||
values.get("Executable Segment flags"),
|
||||
/^0x([0-9a-f]+)$/iu,
|
||||
16,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
/** `Sealed Resources version=2 rules=13 files=290` or `Sealed Resources=none`. */
|
||||
const parseSealedResources = (
|
||||
line: string,
|
||||
): InspectSignature["sealed_resources"] => {
|
||||
if (/^Sealed Resources\s*=\s*none$/u.test(line.trim()))
|
||||
return { status: "none", version: null, rules: null, files: null };
|
||||
return {
|
||||
status: "sealed",
|
||||
version: integerField(line, /\sversion=(\d+)/u),
|
||||
rules: integerField(line, /\srules=(\d+)/u),
|
||||
files: integerField(line, /\sfiles=(\d+)/u),
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user