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:
Kaoru0822
2026-10-07 11:16:55 +00:00
co-authored by Claude Opus 5.5
parent dcde958450
commit 25ca63f231
19 changed files with 1247 additions and 10 deletions
+1
View File
@@ -303,6 +303,7 @@ jobs:
- run: npm run verify:keyed-archive
- run: npm run verify:asset-catalog
- run: npm run verify:macos-bundle
- run: npm run verify:code-signature
- name: Native compiled NIB hierarchy regressions
run: npm run test:focused -- tests/boundary/filesystem/nibNativeHierarchy.test.ts tests/boundary/filesystem/interfaceBuilderBundle.test.ts
- name: Real binary metadata and Interface Builder integration
+22
View File
@@ -12,6 +12,28 @@ input file and include the observed lipo slice offset for universal binaries.
If that offset is unavailable, segment evidence locations are omitted with an
explicit limitation; architecture inventory locations remain available.
- `inspect_signature` / `rea inspect-signature <app-or-mach-o>` reports
codesign identity, requirements and entitlements, and adds:
- **Observed facts:**
- the parsed CodeDirectory, with flags decoded from their numeric value
(`runtime`, `library-validation`, `restrict`, `kill`, `adhoc`,
`linker-signed`, …), slot counts, platform identifier and runtime
version;
- sealed resources;
- a local `codesign --verify --strict` result, with diagnostics and the
nested code it validated;
- whether a notarization ticket is stapled at `Contents/CodeResources`.
The ticket itself and Apple's notarization record are not checked,
because that needs the network.
- **Derived `security_facets`**, each with the flags or entitlements that
support it:
- library validation;
- whether dyld honors `DYLD_*` variables;
- debugger attach;
- executable-memory policy;
- App Sandbox.
System Integrity Protection, AMFI and setuid policy are not evaluated.
- `inspect_asset_catalog` / `rea inspect-asset-catalog <app>` reads compiled
`Assets.car` metadata through macOS `assetutil --info`. Catalog digests, raw
rendition fields, pagination and exact UI resource-name matches are returned.
+3 -3
View File
@@ -7,7 +7,7 @@
"client": "2.3.1",
"core": "2.3.1"
},
"skill_version": "27"
"skill_version": "28"
},
"tools": {
"total": 131,
@@ -669,9 +669,9 @@
"mcp_prompts": 6
},
"digests": {
"tools_sha256": "d0b9e5c99d6a2c9bdf065429db901231326a7de5910f2d878cee124891dba57e",
"tools_sha256": "1b01577d3ad5b8815e08a52a5681c2af738935c43695b4a21d36f1d26333e680",
"prompts_sha256": "ef2de8814390b340623c32001610aa2709d90bed51537b6e562ab3abf144ab4d",
"combined_sha256": "188d726867808cd63764625b93d89e2936af29d9943dbc0e5d22044294521e1d",
"combined_sha256": "07b4bcbc620ade41ffa4da3a5676d92fe3e7366fc60eebdb543bec7ba359d3f8",
"providers_sha256": "a7d885531ee25d42c51385444faec544d34cd7eba6250a7dc75c4faedd4454a3"
}
}
+7
View File
@@ -71,6 +71,13 @@ an XML graph golden. `verify:asset-catalog` compiles source-owned colors with
`actool`, invokes real `assetutil`, then checks CLI/MCP results, exact catalog
digest, every raw metadata field, pagination and malformed input rejection.
Neither artifact workflow requires Hopper or launches it. Both run in macOS CI.
`verify:code-signature` needs only macOS with Command Line Tools. It re-signs
copies of a clang-built fixture with real `codesign`: ad hoc, hardened
runtime, hardened runtime with relaxing entitlements, and `library,restrict`
flags. It checks that `inspect-signature` decodes those flags and derives the
expected security facets. It also checks a platform binary, which must report a
platform identifier, and a bundle with an added unsealed file, which must fail
strict verification. CLI and stdio MCP results must match.
`verify:macos-bundle` needs only macOS with Command Line Tools. It compiles a
source-owned app with `clang`: a versioned framework, XPC services, an app
extension, a login item, a privileged helper, launchd plists, and a helper tool,
@@ -1,5 +1,5 @@
{
"manifest_id": "ecm_4bb7d6acd148fffbd7e696cd56b22ed7a031fcb4b51473170058b4a9e902ee44",
"manifest_id": "ecm_7c023e043e069545c78f60e894c1f66a357a9b9435a1f1b3ade09eb7b1a821f1",
"verifier": {
"id": "rea-managed-conformance",
"version": "1"
@@ -13,7 +13,7 @@
"skill_digests": [
{
"skill_id": "reverse-engineer-anything",
"sha256": "1738df3db4b39d4967e40cc147d24393fd8e1e21fc4f7b7b45da30ce8880c2a9"
"sha256": "81e7b30e94cec01efa31f18553919665b3617282f5cc23ee01a3e158ef665468"
}
],
"claims": [
+1
View File
@@ -123,6 +123,7 @@
"verify:apple-dispatch": "npm run build:cached && node scripts/verify-apple-dispatch.mjs",
"verify:native-ui": "npm run build:cached && node scripts/verify-native-ui.mjs",
"verify:keyed-archive": "npm run build:cached && node scripts/verify-keyed-archive.mjs",
"verify:code-signature": "npm run build:cached && node scripts/verify-code-signature.mjs",
"verify:macos-bundle": "npm run build:cached && node scripts/verify-macos-bundle.mjs",
"verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs",
"verify:ida": "npm run build:cached && node scripts/verify-real-ida.mjs",
+162
View File
@@ -0,0 +1,162 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import {
copyFile,
mkdir,
mkdtemp,
realpath,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import {
artifactCli,
artifactMcpResult,
withArtifactMcp,
} from "./lib/artifact-e2e.mjs";
import {
buildMacosBundleFixture,
preflightMacosBundleFixture,
} from "./lib/macos-bundle-fixture.mjs";
const exec = promisify(execFile);
await preflightMacosBundleFixture();
const root = await mkdtemp(join(tmpdir(), "rea-code-signature-"));
const facets = (signature) =>
Object.fromEntries(
signature.security_facets.map(({ facet, state }) => [facet, state]),
);
/** Re-sign a copy of one fixture executable ad hoc with the given options. */
const signedCopy = async (source, name, options) => {
const path = join(root, name);
await copyFile(source, path);
await exec("/usr/bin/xcrun", [
"codesign",
"--force",
"--sign",
"-",
...options,
path,
]);
return path;
};
const ENTITLEMENTS = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>com.apple.security.cs.disable-library-validation</key><true/>
<key>com.apple.security.cs.allow-dyld-environment-variables</key><true/>
<key>com.apple.security.get-task-allow</key><true/>
<key>com.apple.security.cs.allow-jit</key><true/>
</dict></plist>
`;
try {
const { app } = await buildMacosBundleFixture(root);
const plain = await artifactCli("inspect-signature", app);
assert.deepEqual(plain.code_directory.flags.names, ["adhoc"]);
assert.equal(plain.verification.status, "valid");
// The opened bundle is reported by its canonical path.
assert.equal(plain.verification.path, await realpath(app));
assert.equal(plain.stapled_ticket.status, "absent");
assert.equal(plain.sealed_resources.status, "sealed");
assert.deepEqual(facets(plain), {
"library-validation": "not-enforced",
"dyld-environment-variables": "honored",
"debugger-attach": "allowed",
"executable-memory": "unrestricted",
"app-sandbox": "not-sandboxed",
});
await withArtifactMcp(app, async (client) => {
const viaMcp = await artifactMcpResult(client, "inspect_signature");
assert.deepEqual(
{ ...viaMcp, provenance: [] },
{ ...plain, provenance: [] },
);
});
const tool = join(app, "Contents/Helpers/rea-tool");
const hardened = await artifactCli(
"inspect-signature",
await signedCopy(tool, "hardened", ["--options", "runtime"]),
);
assert.deepEqual(hardened.code_directory.flags.names, ["adhoc", "runtime"]);
assert.equal(hardened.stapled_ticket.status, "not-applicable");
assert.deepEqual(facets(hardened), {
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
"debugger-attach": "blocked",
"executable-memory": "restricted",
"app-sandbox": "not-sandboxed",
});
const entitlements = join(root, "relaxed.entitlements");
await writeFile(entitlements, ENTITLEMENTS);
const relaxed = await artifactCli(
"inspect-signature",
await signedCopy(tool, "relaxed", [
"--options",
"runtime",
"--entitlements",
entitlements,
]),
);
assert.deepEqual(facets(relaxed), {
"library-validation": "disabled",
"dyld-environment-variables": "honored",
"debugger-attach": "allowed",
"executable-memory": "jit-allowed",
"app-sandbox": "not-sandboxed",
});
const flagged = await artifactCli(
"inspect-signature",
await signedCopy(tool, "flagged", ["--options", "library,restrict"]),
);
assert.deepEqual(flagged.code_directory.flags.names, [
"adhoc",
"restrict",
"library-validation",
]);
assert.equal(facets(flagged)["library-validation"], "enforced");
assert.equal(facets(flagged)["dyld-environment-variables"], "ignored");
const platform = await artifactCli("inspect-signature", "/usr/bin/true");
assert.notEqual(platform.code_directory.platform_identifier, null);
assert.equal(platform.verification.status, "valid");
assert.equal(facets(platform)["library-validation"], "enforced");
await mkdir(join(app, "Contents/Resources"), { recursive: true });
await writeFile(join(app, "Contents/Resources/added.txt"), "unsealed");
const tampered = await artifactCli("inspect-signature", app);
assert.equal(tampered.verification.status, "invalid");
assert.ok(
tampered.verification.diagnostics.some((line) => line.includes("added")),
JSON.stringify(tampered.verification),
);
process.stdout.write(
`${JSON.stringify({
ok: true,
mocked: false,
cli: true,
stdio_mcp: true,
variants: [
"adhoc",
"runtime",
"runtime+entitlements",
"library,restrict",
],
platform_identifier: platform.code_directory.platform_identifier,
tampered_verification: tampered.verification.status,
})}\n`,
);
} finally {
await rm(root, { recursive: true, force: true });
}
+2 -2
View File
@@ -2,9 +2,9 @@
name: reverse-engineer-anything
description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.
metadata:
version: "27"
version: "28"
tool_count: 131
catalog_digest: "188d726867808cd63764625b93d89e2936af29d9943dbc0e5d22044294521e1d"
catalog_digest: "07b4bcbc620ade41ffa4da3a5676d92fe3e7366fc60eebdb543bec7ba359d3f8"
---
# REA
@@ -69,6 +69,12 @@ ASAR, or DMG inputs when the artifact graph and findings help answer the
question. It returns the complete artifact graph inline. Cite graph manifest
IDs when using them.
`inspect_signature` decodes CodeDirectory flags, runs local strict
verification, reports a stapled notarization ticket, and derives security
facets: library validation, `DYLD_*` handling, debugger attach, executable
memory, and sandbox. Cite each facet's `evidence`; system policy such as SIP and
AMFI is not evaluated.
For an IPA or a macOS `.app`, ZIP, or DMG, pass the inventory Evidence to
`project_apple_application_graph`. It reports application roots and nested
bundles by path convention: app extensions, XPC services, frameworks, login
+168
View File
@@ -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",
});
});
});
+418
View File
@@ -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),
];
+12
View File
@@ -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
+1 -1
View File
@@ -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;
+34 -1
View File
@@ -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,
});
+110
View File
@@ -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.",
];
+77
View File
@@ -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" },
});
});
});
+85
View File
@@ -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),
};
};
@@ -0,0 +1,135 @@
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
import { ok } from "../../../../src/domain/result.js";
import { inspectSignatureSchema } from "../../../../src/domain/nativeInspection.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import {
NativeFixtureRunner as FixtureRunner,
nativeMachoTarget as machoTarget,
} from "../../../fixtures/nativeCommands.js";
/** Fail only strict verification, as a tampered bundle does. */
class TamperedRunner extends FixtureRunner {
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 =
"--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";
return ok({
...result.value,
stdout: "",
stderr,
stdoutBytes: 0,
stderrBytes: Buffer.byteLength(stderr),
exitCode: 1,
});
}
}
const fixtureApp = async (ticket: string | undefined) => {
const directory = await createTestTempDirectory("rea-signature-posture-");
const app = join(directory, "Fixture.app");
const executable = join(app, "Contents/MacOS/Fixture");
await mkdir(join(app, "Contents/MacOS"), { recursive: true });
await writeFile(executable, "fixture");
if (ticket !== undefined)
await writeFile(join(app, "Contents/CodeResources"), ticket);
return { app, executable };
};
describe("native signature posture", () => {
it("verifies the opened bundle and reports a stapled ticket", async () => {
const ticket = "stapled ticket bytes";
const { app, executable } = await fixtureApp(ticket);
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(signature.ok).toBe(true);
if (!signature.ok) return;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.code_directory).toMatchObject({
version: "20500",
flags: { value: 0x10000, names: ["runtime"] },
code_slots: 10,
special_slots: 7,
});
expect(result.verification).toMatchObject({
path: app,
status: "valid",
exit_code: 0,
});
expect(result.stapled_ticket).toEqual({
status: "present",
path: "Contents/CodeResources",
sha256: createHash("sha256").update(ticket).digest("hex"),
size: ticket.length,
});
expect(
Object.fromEntries(
result.security_facets.map(({ facet, state }) => [facet, state]),
),
).toEqual({
"library-validation": "enforced",
"dyld-environment-variables": "ignored",
"debugger-attach": "blocked",
"executable-memory": "restricted",
"app-sandbox": "sandboxed",
});
expect(result.provenance.map(({ command }) => command[1])).toContain(
"--verify",
);
});
it("keeps a failed strict verification as an observation", async () => {
const { app, executable } = await fixtureApp(undefined);
const signature = await new NativeMacOSProvider(
new TamperedRunner(),
"darwin",
)
.createClient(machoTarget(executable, app))
.execute("inspect_signature", {});
expect(signature.ok).toBe(true);
if (!signature.ok) return;
const result = inspectSignatureSchema.parse(signature.value.result);
expect(result.verification).toEqual({
path: app,
status: "invalid",
exit_code: 1,
diagnostics: [
"/Applications/Fixture.app: a sealed resource is missing or invalid",
"file modified: /Applications/Fixture.app/Contents/Resources/en.lproj/Main.nib",
],
validated_nested_code: [
"/Applications/Fixture.app/Contents/PlugIns/A.appex",
"/Applications/Fixture.app/Contents/XPCServices/B.xpc",
],
});
expect(result.stapled_ticket.status).toBe("absent");
});
it("does not look for a stapled ticket beside a bare Mach-O", async () => {
const directory = await createTestTempDirectory("rea-signature-bare-");
const executable = join(directory, "tool");
await writeFile(executable, "fixture");
const signature = await new NativeMacOSProvider(
new FixtureRunner(),
"darwin",
)
.createClient(machoTarget(executable))
.execute("inspect_signature", {});
expect(signature.ok && signature.value.result).toMatchObject({
verification: { path: executable },
stapled_ticket: { status: "not-applicable" },
});
});
});