refactor(native): own signing policy and bind capture target versions
This commit is contained in:
@@ -1,22 +1,6 @@
|
||||
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`. */
|
||||
/** Observed signing-directory metadata; policy interpretation belongs to the adapter. */
|
||||
export const codeDirectorySchema = z.object({
|
||||
version: z.string().nullable(),
|
||||
flags: z
|
||||
@@ -34,7 +18,7 @@ export const codeDirectorySchema = z.object({
|
||||
executable_segment_flags: z.number().int().nonnegative().nullable(),
|
||||
});
|
||||
|
||||
/** Sealed-resource summary of a bundle signature. */
|
||||
/** Observed sealed-resource summary. */
|
||||
export const sealedResourcesSchema = z.object({
|
||||
status: z.enum(["sealed", "none", "unknown"]),
|
||||
version: z.number().int().nullable(),
|
||||
@@ -42,7 +26,7 @@ export const sealedResourcesSchema = z.object({
|
||||
files: z.number().int().nullable(),
|
||||
});
|
||||
|
||||
/** Local `codesign --verify --deep --strict` outcome for the signed code. */
|
||||
/** Local verification observation; unknown is distinct from a proven invalid signature. */
|
||||
export const signatureVerificationSchema = z.object({
|
||||
path: z.string(),
|
||||
status: z.enum(["valid", "invalid", "unsigned", "unknown"]),
|
||||
@@ -51,7 +35,7 @@ export const signatureVerificationSchema = z.object({
|
||||
validated_nested_code: z.array(z.string()),
|
||||
});
|
||||
|
||||
/** Presence of a notarization ticket stapled to an app bundle. */
|
||||
/** Local ticket presence and content identity, without a remote notarization claim. */
|
||||
export const stapledTicketSchema = z.object({
|
||||
status: z.enum(["present", "absent", "unreadable", "not-applicable"]),
|
||||
path: z.string().nullable(),
|
||||
@@ -60,7 +44,6 @@ export const stapledTicketSchema = z.object({
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
size: z.number().int().nonnegative().nullable(),
|
||||
/** Why an existing ticket file could not be read, such as EACCES. */
|
||||
reason: z.string().nullable(),
|
||||
});
|
||||
|
||||
@@ -109,382 +92,7 @@ const facetSchema = z.discriminatedUnion("facet", [
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Shared result semantics; adapters determine each facet's policy and evidence. */
|
||||
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;
|
||||
/** Architecture slices differ in signing state, so no one CodeDirectory describes the process. */
|
||||
readonly mixedSlices: boolean;
|
||||
/**
|
||||
* The signature satisfies `anchor apple`. Only then does a CodeDirectory
|
||||
* platform identifier mean an Apple platform binary.
|
||||
*/
|
||||
readonly appleOrigin: boolean;
|
||||
/**
|
||||
* The local `--deep --strict` verification failed for the opened code.
|
||||
* Flag bits from an unauthenticated CodeDirectory must not decide facets.
|
||||
*/
|
||||
readonly signatureInvalid?: boolean;
|
||||
}
|
||||
|
||||
/** Whether the CodeDirectory claims a platform binary, and whether Apple signed it. */
|
||||
const platformBinary = (
|
||||
input: PostureInput,
|
||||
): "apple" | "unverified" | "none" =>
|
||||
(input.codeDirectory?.platform_identifier ?? null) === null
|
||||
? "none"
|
||||
: input.appleOrigin
|
||||
? "apple"
|
||||
: "unverified";
|
||||
|
||||
const UNVERIFIED_PLATFORM = [
|
||||
"platform identifier",
|
||||
"Apple origin not verified",
|
||||
] as const;
|
||||
|
||||
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,
|
||||
};
|
||||
const platform = platformBinary(input);
|
||||
if (platform !== "none")
|
||||
return platform === "apple"
|
||||
? {
|
||||
...base,
|
||||
state: "enforced",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: [...UNVERIFIED_PLATFORM],
|
||||
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,
|
||||
};
|
||||
const platform = platformBinary(input);
|
||||
if (platform !== "none")
|
||||
return platform === "apple"
|
||||
? {
|
||||
...base,
|
||||
state: "ignored",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: [...UNVERIFIED_PLATFORM],
|
||||
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,
|
||||
};
|
||||
const platform = platformBinary(input);
|
||||
if (platform !== "none")
|
||||
return platform === "apple"
|
||||
? {
|
||||
...base,
|
||||
state: "blocked",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: [...UNVERIFIED_PLATFORM],
|
||||
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[] => {
|
||||
const facets = [
|
||||
libraryValidation(input),
|
||||
dyldEnvironment(input),
|
||||
debuggerAttach(input),
|
||||
executableMemory(input),
|
||||
appSandbox(input),
|
||||
];
|
||||
// An invalid main signature leaves flag bits unauthenticated; keep the raw
|
||||
// CodeDirectory fields but report every facet as unknown.
|
||||
if (input.signatureInvalid === true)
|
||||
return facets.map((facet) => ({
|
||||
...facet,
|
||||
state: "unknown" as const,
|
||||
evidence: ["signature verification failed"],
|
||||
}));
|
||||
// Each slice runs under its own signature; the inspected one does not
|
||||
// describe an unsigned slice of the same file.
|
||||
return input.mixedSlices
|
||||
? facets.map((facet) => ({
|
||||
...facet,
|
||||
state: "unknown" as const,
|
||||
evidence: ["architecture slices differ in signing state"],
|
||||
}))
|
||||
: facets;
|
||||
};
|
||||
|
||||
@@ -3,8 +3,8 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
codeDirectoryFlagNames,
|
||||
deriveSecurityFacets,
|
||||
type CodeDirectory,
|
||||
} from "./codeSigningPosture.js";
|
||||
} from "./CodeSigningPolicy.js";
|
||||
import type { CodeDirectory } from "../domain/native/codeSigningPosture.js";
|
||||
|
||||
const directory = (
|
||||
flags: number | null,
|
||||
@@ -0,0 +1,395 @@
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type {
|
||||
CodeDirectory,
|
||||
SecurityFacet,
|
||||
} from "../domain/native/codeSigningPosture.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"],
|
||||
];
|
||||
|
||||
/** 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;
|
||||
/** Architecture slices differ in signing state, so no one CodeDirectory describes the process. */
|
||||
readonly mixedSlices: boolean;
|
||||
/**
|
||||
* The signature satisfies `anchor apple`. Only then does a CodeDirectory
|
||||
* platform identifier mean an Apple platform binary.
|
||||
*/
|
||||
readonly appleOrigin: boolean;
|
||||
/**
|
||||
* The local `--deep --strict` verification failed for the opened code.
|
||||
* Flag bits from an unauthenticated CodeDirectory must not decide facets.
|
||||
*/
|
||||
readonly signatureInvalid?: boolean;
|
||||
}
|
||||
|
||||
/** Whether the CodeDirectory claims a platform binary, and whether Apple signed it. */
|
||||
const platformBinary = (
|
||||
input: PostureInput,
|
||||
): "apple" | "unverified" | "none" =>
|
||||
(input.codeDirectory?.platform_identifier ?? null) === null
|
||||
? "none"
|
||||
: input.appleOrigin
|
||||
? "apple"
|
||||
: "unverified";
|
||||
|
||||
const UNVERIFIED_PLATFORM = [
|
||||
"platform identifier",
|
||||
"Apple origin not verified",
|
||||
] as const;
|
||||
|
||||
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,
|
||||
};
|
||||
const platform = platformBinary(input);
|
||||
if (platform !== "none")
|
||||
return platform === "apple"
|
||||
? {
|
||||
...base,
|
||||
state: "enforced",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: [...UNVERIFIED_PLATFORM],
|
||||
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,
|
||||
};
|
||||
const platform = platformBinary(input);
|
||||
if (platform !== "none")
|
||||
return platform === "apple"
|
||||
? {
|
||||
...base,
|
||||
state: "ignored",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: [...UNVERIFIED_PLATFORM],
|
||||
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,
|
||||
};
|
||||
const platform = platformBinary(input);
|
||||
if (platform !== "none")
|
||||
return platform === "apple"
|
||||
? {
|
||||
...base,
|
||||
state: "blocked",
|
||||
evidence: ["platform binary"],
|
||||
explanation,
|
||||
}
|
||||
: {
|
||||
...base,
|
||||
state: "unknown",
|
||||
evidence: [...UNVERIFIED_PLATFORM],
|
||||
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[] => {
|
||||
const facets = [
|
||||
libraryValidation(input),
|
||||
dyldEnvironment(input),
|
||||
debuggerAttach(input),
|
||||
executableMemory(input),
|
||||
appSandbox(input),
|
||||
];
|
||||
// An invalid main signature leaves flag bits unauthenticated; keep the raw
|
||||
// CodeDirectory fields but report every facet as unknown.
|
||||
if (input.signatureInvalid === true)
|
||||
return facets.map((facet) => ({
|
||||
...facet,
|
||||
state: "unknown" as const,
|
||||
evidence: ["signature verification failed"],
|
||||
}));
|
||||
// Each slice runs under its own signature; the inspected one does not
|
||||
// describe an unsigned slice of the same file.
|
||||
return input.mixedSlices
|
||||
? facets.map((facet) => ({
|
||||
...facet,
|
||||
state: "unknown" as const,
|
||||
evidence: ["architecture slices differ in signing state"],
|
||||
}))
|
||||
: facets;
|
||||
};
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
inspectSignatureSchema,
|
||||
type NativeCommandInvocation,
|
||||
} from "../domain/native/nativeInspection.js";
|
||||
import { deriveSecurityFacets } from "../domain/native/codeSigningPosture.js";
|
||||
import { deriveSecurityFacets } from "./CodeSigningPolicy.js";
|
||||
import {
|
||||
bindSignatureTarget,
|
||||
signatureTargetIssue,
|
||||
} from "./SignatureTargetBinding.js";
|
||||
import { omittedPrototypeKeysLimitation } from "../domain/propertyListKeys.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -89,6 +93,7 @@ export const inspectNativeSignature = async (options: {
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<Result<NativeObservation, AnalysisError>> => {
|
||||
const { target, capture, signal } = options;
|
||||
const binding = await bindSignatureTarget(target, signal);
|
||||
const displays = await signatureDisplays(target.path, capture, signal);
|
||||
if (!displays.ok) return displays;
|
||||
const { display, requirements, entitlements } = displays.value;
|
||||
@@ -160,6 +165,22 @@ export const inspectNativeSignature = async (options: {
|
||||
mainInvalid = main.value.exitCode !== 0;
|
||||
}
|
||||
const provenance = captures.map(options.invocation);
|
||||
const ticket = await stapledTicket(target, signal);
|
||||
const versionIssue = await signatureTargetIssue(target, binding, signal);
|
||||
const facets = deriveSecurityFacets({
|
||||
signed: !aggregateUnsigned,
|
||||
codeDirectory: parsed.code_directory,
|
||||
entitlements: entitlementValue.value,
|
||||
entitlementsKnown: unsigned || entitlements.exitCode === 0,
|
||||
mixedSlices: slices.value.mixed,
|
||||
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,
|
||||
@@ -167,16 +188,16 @@ export const inspectNativeSignature = async (options: {
|
||||
/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,
|
||||
}),
|
||||
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}`,
|
||||
})),
|
||||
provenance,
|
||||
limitations,
|
||||
});
|
||||
|
||||
@@ -252,13 +252,19 @@ export const unconfirmedNestedCode = async (
|
||||
): Promise<string[]> => {
|
||||
const missing: string[] = [];
|
||||
const ambiguous: string[] = [];
|
||||
const denied: string[] = [];
|
||||
for (const validatedPath of verification.validated_nested_code) {
|
||||
try {
|
||||
await lstat(validatedPath);
|
||||
} catch (cause: unknown) {
|
||||
const code = errorCode(cause);
|
||||
// A denied lookup cannot confirm the path, but is no sign of a split one.
|
||||
if (code === "EACCES" || code === "EPERM") continue;
|
||||
if (code === "EACCES" || code === "EPERM") {
|
||||
denied.push(
|
||||
`Could not confirm completeness of codesign nested path ${JSON.stringify(validatedPath)}: permission denied (${code}); the reported path may be a fragment.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (code !== "ENOENT" && code !== "ENOTDIR") throw cause;
|
||||
missing.push(validatedPath);
|
||||
continue;
|
||||
@@ -268,6 +274,7 @@ export const unconfirmedNestedCode = async (
|
||||
}
|
||||
}
|
||||
return [
|
||||
...denied,
|
||||
...missing.map(
|
||||
(path) =>
|
||||
`codesign reported validated nested code at ${JSON.stringify(path)}, which does not exist; a nested path probably contains a newline, so validated_nested_code and diagnostics hold fragments of it.`,
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
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";
|
||||
|
||||
/** Binding of commands to the selected executable's registered content/version. */
|
||||
export interface SignatureTargetBinding {
|
||||
readonly identity: string | null;
|
||||
readonly reason: string | null;
|
||||
}
|
||||
|
||||
const identity = (stat: BigIntStats): string =>
|
||||
[stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");
|
||||
|
||||
/** Establish a bounded-memory digest/version baseline before external commands run. */
|
||||
export const bindSignatureTarget = async (
|
||||
target: BinaryTarget,
|
||||
signal?: AbortSignal,
|
||||
): Promise<SignatureTargetBinding> => {
|
||||
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}`,
|
||||
};
|
||||
const file = await open(
|
||||
target.path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
try {
|
||||
const opened = await file.stat({ bigint: true });
|
||||
if (identity(opened) !== identity(before))
|
||||
return {
|
||||
identity: null,
|
||||
reason: `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}`,
|
||||
};
|
||||
const hash = createHash("sha256");
|
||||
const chunk = Buffer.alloc(64 * 1024);
|
||||
let position = 0;
|
||||
while (position < size) {
|
||||
signal?.throwIfAborted();
|
||||
const { bytesRead } = await file.read(
|
||||
chunk,
|
||||
0,
|
||||
Math.min(chunk.length, size - position),
|
||||
position,
|
||||
);
|
||||
if (bytesRead === 0)
|
||||
return {
|
||||
identity: null,
|
||||
reason: `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}`,
|
||||
};
|
||||
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 };
|
||||
} 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;
|
||||
}
|
||||
};
|
||||
|
||||
/** Reject drift between display, entitlement and verification captures. */
|
||||
export const signatureTargetIssue = async (
|
||||
target: BinaryTarget,
|
||||
binding: SignatureTargetBinding,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string | null> => {
|
||||
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}`;
|
||||
} 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;
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,5 @@
|
||||
import {
|
||||
codeDirectoryFlagNames,
|
||||
type CodeDirectory,
|
||||
} from "../../domain/native/codeSigningPosture.js";
|
||||
import { type CodeDirectory } from "../../domain/native/codeSigningPosture.js";
|
||||
import { codeDirectoryFlagNames } from "../CodeSigningPolicy.js";
|
||||
import {
|
||||
inspectSignatureSchema,
|
||||
type InspectSignature,
|
||||
|
||||
@@ -12,9 +12,14 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js
|
||||
import { notarizationTicketFixture } from "../../../fixtures/notarizationTicket.js";
|
||||
import {
|
||||
NativeFixtureRunner as FixtureRunner,
|
||||
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"),
|
||||
});
|
||||
|
||||
const TAMPERED_STDERR =
|
||||
"--prepared:/Applications/Fixture.app/Contents/XPCServices/B.xpc\n--validated:/Applications/Fixture.app/Contents/XPCServices/B.xpc\n--validated:/Applications/Fixture.app/Contents/PlugIns/A.appex\n/Applications/Fixture.app: a sealed resource is missing or invalid\nfile modified: /Applications/Fixture.app/Contents/Resources/en.lproj/Main.nib\n";
|
||||
|
||||
@@ -485,6 +490,77 @@ describe("signature architecture coverage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("signature target version binding", () => {
|
||||
it("downgrades facets when the executable changes between captures", async () => {
|
||||
const { app, executable } = await fixtureApp(undefined);
|
||||
const signature = await new NativeMacOSProvider(
|
||||
new ReplacingExecutableRunner(),
|
||||
"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("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",
|
||||
);
|
||||
});
|
||||
|
||||
it.skipIf(process.getuid?.() === 0)(
|
||||
"reports denied nested-path completeness checks",
|
||||
async () => {
|
||||
const { app, executable } = await fixtureApp(undefined);
|
||||
const helpers = join(app, "Contents/Helpers");
|
||||
await mkdir(helpers);
|
||||
await chmod(helpers, 0);
|
||||
try {
|
||||
const signature = await new NativeMacOSProvider(
|
||||
new NewlinePathRunner(),
|
||||
"darwin",
|
||||
)
|
||||
.createClient(machoTarget(executable, app))
|
||||
.execute("inspect_signature", {});
|
||||
if (!signature.ok) throw signature.error;
|
||||
const result = inspectSignatureSchema.parse(signature.value.result);
|
||||
expect(result.limitations).toContainEqual(
|
||||
expect.stringContaining("Could not confirm completeness"),
|
||||
);
|
||||
expect(result.limitations).toContainEqual(
|
||||
expect.stringContaining("permission denied (EACCES)"),
|
||||
);
|
||||
} finally {
|
||||
await chmod(helpers, 0o755);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
/** Mutate only the fixture after its initial display has been observed. */
|
||||
class ReplacingExecutableRunner extends FixtureRunner {
|
||||
#changed = false;
|
||||
override async run(tool: string, arguments_: readonly string[]) {
|
||||
const result = await super.run(tool, arguments_);
|
||||
if (
|
||||
!this.#changed &&
|
||||
tool === "codesign" &&
|
||||
arguments_.includes("--verbose=4")
|
||||
) {
|
||||
const path = arguments_.at(-1);
|
||||
if (path !== undefined)
|
||||
await writeFile(path, "replacement executable bytes");
|
||||
this.#changed = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/** A signed bundle whose nested helper is unsigned. */
|
||||
class UnsignedNestedRunner extends FixtureRunner {
|
||||
override async run(tool: string, arguments_: readonly string[]) {
|
||||
|
||||
Reference in New Issue
Block a user