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
@@ -0,0 +1,168 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
codeDirectoryFlagNames,
|
||||
deriveSecurityFacets,
|
||||
type CodeDirectory,
|
||||
} from "./codeSigningPosture.js";
|
||||
|
||||
const directory = (
|
||||
flags: number | null,
|
||||
platform: number | null = null,
|
||||
): CodeDirectory => ({
|
||||
version: "20500",
|
||||
flags:
|
||||
flags === null
|
||||
? null
|
||||
: { value: flags, names: codeDirectoryFlagNames(flags) },
|
||||
code_slots: 1,
|
||||
special_slots: 7,
|
||||
location: "embedded",
|
||||
hash_type: "sha256",
|
||||
platform_identifier: platform,
|
||||
runtime_version: null,
|
||||
executable_segment_flags: 1,
|
||||
});
|
||||
|
||||
const states = (facets: ReturnType<typeof deriveSecurityFacets>) =>
|
||||
Object.fromEntries(facets.map(({ facet, state }) => [facet, state]));
|
||||
|
||||
const RUNTIME = 0x10000;
|
||||
|
||||
describe("CodeDirectory flags", () => {
|
||||
it("names known bits and keeps unknown bits numeric", () => {
|
||||
expect(codeDirectoryFlagNames(0x12a02)).toEqual([
|
||||
"adhoc",
|
||||
"kill",
|
||||
"restrict",
|
||||
"library-validation",
|
||||
"runtime",
|
||||
]);
|
||||
expect(codeDirectoryFlagNames(0x40000 | 0x2)).toEqual(["adhoc", "0x40000"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("derived security facets", () => {
|
||||
it("treats unsigned and plain ad hoc code as unrestricted", () => {
|
||||
for (const signed of [false, true])
|
||||
expect(
|
||||
states(
|
||||
deriveSecurityFacets({
|
||||
signed,
|
||||
codeDirectory: signed ? directory(0x2) : null,
|
||||
entitlements: null,
|
||||
entitlementsKnown: true,
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
"library-validation": "not-enforced",
|
||||
"dyld-environment-variables": "honored",
|
||||
"debugger-attach": "allowed",
|
||||
"executable-memory": "unrestricted",
|
||||
"app-sandbox": "not-sandboxed",
|
||||
});
|
||||
});
|
||||
|
||||
it("restricts hardened-runtime code unless entitlements relax it", () => {
|
||||
expect(
|
||||
states(
|
||||
deriveSecurityFacets({
|
||||
signed: true,
|
||||
codeDirectory: directory(RUNTIME),
|
||||
entitlements: { "com.apple.security.app-sandbox": true },
|
||||
entitlementsKnown: true,
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
"library-validation": "enforced",
|
||||
"dyld-environment-variables": "ignored",
|
||||
"debugger-attach": "blocked",
|
||||
"executable-memory": "restricted",
|
||||
"app-sandbox": "sandboxed",
|
||||
});
|
||||
const relaxed = deriveSecurityFacets({
|
||||
signed: true,
|
||||
codeDirectory: directory(RUNTIME),
|
||||
entitlements: {
|
||||
"com.apple.security.cs.disable-library-validation": true,
|
||||
"com.apple.security.cs.allow-dyld-environment-variables": true,
|
||||
"com.apple.security.get-task-allow": true,
|
||||
"com.apple.security.cs.allow-jit": true,
|
||||
},
|
||||
entitlementsKnown: true,
|
||||
});
|
||||
expect(states(relaxed)).toMatchObject({
|
||||
"library-validation": "disabled",
|
||||
"dyld-environment-variables": "honored",
|
||||
"debugger-attach": "allowed",
|
||||
"executable-memory": "jit-allowed",
|
||||
});
|
||||
expect(relaxed[0]?.evidence).toEqual([
|
||||
"hardened runtime",
|
||||
"com.apple.security.cs.disable-library-validation",
|
||||
]);
|
||||
});
|
||||
|
||||
it("lets explicit flags and platform identity override entitlements", () => {
|
||||
const flagged = deriveSecurityFacets({
|
||||
signed: true,
|
||||
codeDirectory: directory(0x2000 | 0x800 | RUNTIME),
|
||||
entitlements: {
|
||||
"com.apple.security.cs.disable-library-validation": true,
|
||||
},
|
||||
entitlementsKnown: true,
|
||||
});
|
||||
expect(states(flagged)).toMatchObject({
|
||||
"library-validation": "enforced",
|
||||
"dyld-environment-variables": "ignored",
|
||||
});
|
||||
expect(
|
||||
states(
|
||||
deriveSecurityFacets({
|
||||
signed: true,
|
||||
codeDirectory: directory(RUNTIME, 26),
|
||||
entitlements: null,
|
||||
entitlementsKnown: true,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
"library-validation": "enforced",
|
||||
"dyld-environment-variables": "ignored",
|
||||
"debugger-attach": "blocked",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps facets unknown when flags or entitlements are unavailable", () => {
|
||||
expect(
|
||||
states(
|
||||
deriveSecurityFacets({
|
||||
signed: true,
|
||||
codeDirectory: directory(RUNTIME),
|
||||
entitlements: null,
|
||||
entitlementsKnown: false,
|
||||
}),
|
||||
),
|
||||
).toEqual({
|
||||
"library-validation": "unknown",
|
||||
"dyld-environment-variables": "unknown",
|
||||
"debugger-attach": "unknown",
|
||||
"executable-memory": "unknown",
|
||||
"app-sandbox": "unknown",
|
||||
});
|
||||
expect(
|
||||
states(
|
||||
deriveSecurityFacets({
|
||||
signed: true,
|
||||
codeDirectory: directory(null),
|
||||
entitlements: null,
|
||||
entitlementsKnown: true,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
"library-validation": "unknown",
|
||||
"dyld-environment-variables": "unknown",
|
||||
"debugger-attach": "unknown",
|
||||
"executable-memory": "unknown",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,418 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
/** `SecCodeSignatureFlags` bits that codesign reports in a CodeDirectory. */
|
||||
const CODE_DIRECTORY_FLAGS: readonly (readonly [number, string])[] = [
|
||||
[0x1, "host"],
|
||||
[0x2, "adhoc"],
|
||||
[0x100, "hard"],
|
||||
[0x200, "kill"],
|
||||
[0x400, "expires"],
|
||||
[0x800, "restrict"],
|
||||
[0x1000, "enforcement"],
|
||||
[0x2000, "library-validation"],
|
||||
[0x10000, "runtime"],
|
||||
[0x20000, "linker-signed"],
|
||||
];
|
||||
|
||||
/** Observed CodeDirectory fields from `codesign -d --verbose=4`. */
|
||||
export const codeDirectorySchema = z.object({
|
||||
version: z.string().nullable(),
|
||||
flags: z
|
||||
.object({
|
||||
value: z.number().int().nonnegative(),
|
||||
names: z.array(z.string()),
|
||||
})
|
||||
.nullable(),
|
||||
code_slots: z.number().int().nonnegative().nullable(),
|
||||
special_slots: z.number().int().nonnegative().nullable(),
|
||||
location: z.string().nullable(),
|
||||
hash_type: z.string().nullable(),
|
||||
platform_identifier: z.number().int().nonnegative().nullable(),
|
||||
runtime_version: z.string().nullable(),
|
||||
executable_segment_flags: z.number().int().nonnegative().nullable(),
|
||||
});
|
||||
|
||||
/** Sealed-resource summary of a bundle signature. */
|
||||
export const sealedResourcesSchema = z.object({
|
||||
status: z.enum(["sealed", "none", "unknown"]),
|
||||
version: z.number().int().nullable(),
|
||||
rules: z.number().int().nullable(),
|
||||
files: z.number().int().nullable(),
|
||||
});
|
||||
|
||||
/** Local `codesign --verify --strict` outcome for the signed code. */
|
||||
export const signatureVerificationSchema = z.object({
|
||||
path: z.string(),
|
||||
status: z.enum(["valid", "invalid", "unsigned"]),
|
||||
exit_code: z.number().int().nullable(),
|
||||
diagnostics: z.array(z.string()),
|
||||
validated_nested_code: z.array(z.string()),
|
||||
});
|
||||
|
||||
/** Presence of a notarization ticket stapled to an app bundle. */
|
||||
export const stapledTicketSchema = z.object({
|
||||
status: z.enum(["present", "absent", "not-applicable"]),
|
||||
path: z.string().nullable(),
|
||||
sha256: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
size: z.number().int().nonnegative().nullable(),
|
||||
});
|
||||
|
||||
const facetSchema = z.discriminatedUnion("facet", [
|
||||
z.object({
|
||||
facet: z.literal("library-validation"),
|
||||
state: z.enum(["enforced", "disabled", "not-enforced", "unknown"]),
|
||||
basis: z.literal("derived"),
|
||||
evidence: z.array(z.string()),
|
||||
explanation: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
facet: z.literal("dyld-environment-variables"),
|
||||
state: z.enum(["ignored", "honored", "unknown"]),
|
||||
basis: z.literal("derived"),
|
||||
evidence: z.array(z.string()),
|
||||
explanation: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
facet: z.literal("debugger-attach"),
|
||||
state: z.enum(["allowed", "blocked", "unknown"]),
|
||||
basis: z.literal("derived"),
|
||||
evidence: z.array(z.string()),
|
||||
explanation: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
facet: z.literal("executable-memory"),
|
||||
state: z.enum([
|
||||
"restricted",
|
||||
"jit-allowed",
|
||||
"unsigned-allowed",
|
||||
"protection-disabled",
|
||||
"unrestricted",
|
||||
"unknown",
|
||||
]),
|
||||
basis: z.literal("derived"),
|
||||
evidence: z.array(z.string()),
|
||||
explanation: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
facet: z.literal("app-sandbox"),
|
||||
state: z.enum(["sandboxed", "not-sandboxed", "unknown"]),
|
||||
basis: z.literal("derived"),
|
||||
evidence: z.array(z.string()),
|
||||
explanation: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const securityFacetsSchema = z.array(facetSchema);
|
||||
export type CodeDirectory = z.infer<typeof codeDirectorySchema>;
|
||||
export type SecurityFacet = z.infer<typeof facetSchema>;
|
||||
|
||||
/** Decode CodeDirectory flag bits; unknown bits keep their hexadecimal value. */
|
||||
export const codeDirectoryFlagNames = (value: number): string[] => {
|
||||
const flags = value >>> 0;
|
||||
const names = CODE_DIRECTORY_FLAGS.flatMap(([bit, name]) =>
|
||||
(flags & bit) === 0 ? [] : [name],
|
||||
);
|
||||
const known = CODE_DIRECTORY_FLAGS.reduce((total, [bit]) => total | bit, 0);
|
||||
for (let index = 0; index < 32; index++)
|
||||
if (((flags >>> index) & 1) === 1 && ((known >>> index) & 1) === 0)
|
||||
names.push(`0x${(2 ** index).toString(16)}`);
|
||||
return names;
|
||||
};
|
||||
|
||||
const entitlement = (
|
||||
entitlements: JsonValue | null,
|
||||
key: string,
|
||||
): boolean | undefined => {
|
||||
if (
|
||||
entitlements === null ||
|
||||
typeof entitlements !== "object" ||
|
||||
Array.isArray(entitlements)
|
||||
)
|
||||
return undefined;
|
||||
const value = entitlements[key];
|
||||
return typeof value === "boolean" ? value : undefined;
|
||||
};
|
||||
|
||||
interface PostureInput {
|
||||
readonly signed: boolean;
|
||||
readonly codeDirectory: CodeDirectory | null;
|
||||
readonly entitlements: JsonValue | null;
|
||||
/** False when mixed or unreadable signing states hide the aggregate entitlements. */
|
||||
readonly entitlementsKnown: boolean;
|
||||
}
|
||||
|
||||
const has = (input: PostureInput, flag: string): boolean =>
|
||||
input.codeDirectory?.flags?.names.includes(flag) === true;
|
||||
|
||||
const libraryValidation = (input: PostureInput): SecurityFacet => {
|
||||
const base = { facet: "library-validation", basis: "derived" } as const;
|
||||
const explanation =
|
||||
"With library validation, the process loads only libraries signed by Apple or by the same team; without it, any library dyld finds can load.";
|
||||
if (!input.signed)
|
||||
return {
|
||||
...base,
|
||||
state: "not-enforced",
|
||||
evidence: ["unsigned"],
|
||||
explanation,
|
||||
};
|
||||
if (input.codeDirectory === null || input.codeDirectory.flags === null)
|
||||
return {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["CodeDirectory flags unavailable"],
|
||||
explanation,
|
||||
};
|
||||
if (input.codeDirectory.platform_identifier !== null)
|
||||
return {
|
||||
...base,
|
||||
state: "enforced",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
};
|
||||
if (has(input, "library-validation"))
|
||||
return {
|
||||
...base,
|
||||
state: "enforced",
|
||||
evidence: ["CodeDirectory flag library-validation"],
|
||||
explanation,
|
||||
};
|
||||
if (!has(input, "runtime"))
|
||||
return {
|
||||
...base,
|
||||
state: "not-enforced",
|
||||
evidence: ["no hardened runtime or library-validation flag"],
|
||||
explanation,
|
||||
};
|
||||
if (!input.entitlementsKnown)
|
||||
return {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["hardened runtime", "entitlements unavailable"],
|
||||
explanation,
|
||||
};
|
||||
return entitlement(
|
||||
input.entitlements,
|
||||
"com.apple.security.cs.disable-library-validation",
|
||||
) === true
|
||||
? {
|
||||
...base,
|
||||
state: "disabled",
|
||||
evidence: [
|
||||
"hardened runtime",
|
||||
"com.apple.security.cs.disable-library-validation",
|
||||
],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "enforced",
|
||||
evidence: ["hardened runtime"],
|
||||
explanation,
|
||||
};
|
||||
};
|
||||
|
||||
const dyldEnvironment = (input: PostureInput): SecurityFacet => {
|
||||
const base = {
|
||||
facet: "dyld-environment-variables",
|
||||
basis: "derived",
|
||||
} as const;
|
||||
const explanation =
|
||||
"Whether dyld honors DYLD_* variables such as DYLD_INSERT_LIBRARIES at launch. setuid/setgid bits, a __RESTRICT segment, and system integrity policy can also restrict them and are not evaluated here.";
|
||||
if (has(input, "restrict"))
|
||||
return {
|
||||
...base,
|
||||
state: "ignored",
|
||||
evidence: ["CodeDirectory flag restrict"],
|
||||
explanation,
|
||||
};
|
||||
if ((input.codeDirectory?.platform_identifier ?? null) !== null)
|
||||
return {
|
||||
...base,
|
||||
state: "ignored",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
};
|
||||
if (!has(input, "runtime"))
|
||||
return input.signed && (input.codeDirectory?.flags ?? null) === null
|
||||
? {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["CodeDirectory flags unavailable"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "honored",
|
||||
evidence: ["no hardened runtime"],
|
||||
explanation,
|
||||
};
|
||||
if (!input.entitlementsKnown)
|
||||
return {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["hardened runtime", "entitlements unavailable"],
|
||||
explanation,
|
||||
};
|
||||
return entitlement(
|
||||
input.entitlements,
|
||||
"com.apple.security.cs.allow-dyld-environment-variables",
|
||||
) === true
|
||||
? {
|
||||
...base,
|
||||
state: "honored",
|
||||
evidence: [
|
||||
"hardened runtime",
|
||||
"com.apple.security.cs.allow-dyld-environment-variables",
|
||||
],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "ignored",
|
||||
evidence: ["hardened runtime"],
|
||||
explanation,
|
||||
};
|
||||
};
|
||||
|
||||
const debuggerAttach = (input: PostureInput): SecurityFacet => {
|
||||
const base = { facet: "debugger-attach", basis: "derived" } as const;
|
||||
const explanation =
|
||||
"Whether a debugger running as the same user can obtain the task port. Developer Tools authorization and system integrity policy still apply.";
|
||||
if (
|
||||
input.entitlementsKnown &&
|
||||
entitlement(input.entitlements, "com.apple.security.get-task-allow") ===
|
||||
true
|
||||
)
|
||||
return {
|
||||
...base,
|
||||
state: "allowed",
|
||||
evidence: ["com.apple.security.get-task-allow"],
|
||||
explanation,
|
||||
};
|
||||
if ((input.codeDirectory?.platform_identifier ?? null) !== null)
|
||||
return {
|
||||
...base,
|
||||
state: "blocked",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
};
|
||||
if (has(input, "runtime"))
|
||||
return input.entitlementsKnown
|
||||
? {
|
||||
...base,
|
||||
state: "blocked",
|
||||
evidence: ["hardened runtime without get-task-allow"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["hardened runtime", "entitlements unavailable"],
|
||||
explanation,
|
||||
};
|
||||
if (input.signed && (input.codeDirectory?.flags ?? null) === null)
|
||||
return {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["CodeDirectory flags unavailable"],
|
||||
explanation,
|
||||
};
|
||||
return {
|
||||
...base,
|
||||
state: "allowed",
|
||||
evidence: ["no hardened runtime"],
|
||||
explanation,
|
||||
};
|
||||
};
|
||||
|
||||
const executableMemory = (input: PostureInput): SecurityFacet => {
|
||||
const base = { facet: "executable-memory", basis: "derived" } as const;
|
||||
const explanation =
|
||||
"Hardened-runtime limits on writable or unsigned executable memory, relaxed by code-signing entitlements.";
|
||||
if (!has(input, "runtime"))
|
||||
return input.signed && (input.codeDirectory?.flags ?? null) === null
|
||||
? {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["CodeDirectory flags unavailable"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unrestricted",
|
||||
evidence: ["no hardened runtime"],
|
||||
explanation,
|
||||
};
|
||||
if (!input.entitlementsKnown)
|
||||
return {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["hardened runtime", "entitlements unavailable"],
|
||||
explanation,
|
||||
};
|
||||
for (const [key, state] of [
|
||||
[
|
||||
"com.apple.security.cs.disable-executable-page-protection",
|
||||
"protection-disabled",
|
||||
],
|
||||
[
|
||||
"com.apple.security.cs.allow-unsigned-executable-memory",
|
||||
"unsigned-allowed",
|
||||
],
|
||||
["com.apple.security.cs.allow-jit", "jit-allowed"],
|
||||
] as const)
|
||||
if (entitlement(input.entitlements, key) === true)
|
||||
return {
|
||||
...base,
|
||||
state,
|
||||
evidence: ["hardened runtime", key],
|
||||
explanation,
|
||||
};
|
||||
return {
|
||||
...base,
|
||||
state: "restricted",
|
||||
evidence: ["hardened runtime"],
|
||||
explanation,
|
||||
};
|
||||
};
|
||||
|
||||
const appSandbox = (input: PostureInput): SecurityFacet => {
|
||||
const base = { facet: "app-sandbox", basis: "derived" } as const;
|
||||
const explanation =
|
||||
"Whether the App Sandbox entitlement confines the process.";
|
||||
if (!input.entitlementsKnown)
|
||||
return {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: ["entitlements unavailable"],
|
||||
explanation,
|
||||
};
|
||||
return entitlement(input.entitlements, "com.apple.security.app-sandbox") ===
|
||||
true
|
||||
? {
|
||||
...base,
|
||||
state: "sandboxed",
|
||||
evidence: ["com.apple.security.app-sandbox"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "not-sandboxed",
|
||||
evidence: ["no com.apple.security.app-sandbox entitlement"],
|
||||
explanation,
|
||||
};
|
||||
};
|
||||
|
||||
/** Derive launch-time security facets from observed flags and entitlements. */
|
||||
export const deriveSecurityFacets = (input: PostureInput): SecurityFacet[] => [
|
||||
libraryValidation(input),
|
||||
dyldEnvironment(input),
|
||||
debuggerAttach(input),
|
||||
executableMemory(input),
|
||||
appSandbox(input),
|
||||
];
|
||||
@@ -1,4 +1,11 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
codeDirectorySchema,
|
||||
sealedResourcesSchema,
|
||||
securityFacetsSchema,
|
||||
signatureVerificationSchema,
|
||||
stapledTicketSchema,
|
||||
} from "./codeSigningPosture.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const hexAddress = z.string().regex(/^0x[a-fA-F0-9]+$/u);
|
||||
@@ -113,6 +120,11 @@ export const inspectSignatureSchema = z.object({
|
||||
entitlements: jsonValueSchema.nullable(),
|
||||
timestamp: z.string().nullable(),
|
||||
hardened_runtime: z.boolean().nullable(),
|
||||
code_directory: codeDirectorySchema.nullable(),
|
||||
sealed_resources: sealedResourcesSchema,
|
||||
verification: signatureVerificationSchema.nullable(),
|
||||
stapled_ticket: stapledTicketSchema,
|
||||
security_facets: securityFacetsSchema,
|
||||
provenance: z.array(nativeCommandInvocationSchema),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
|
||||
serverSdkVersion: "2.3.1",
|
||||
clientSdkVersion: "2.3.1",
|
||||
coreSdkVersion: "2.3.1",
|
||||
skillVersion: "27",
|
||||
skillVersion: "28",
|
||||
} as const;
|
||||
|
||||
@@ -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