Add evidence-backed investigation workflows

This commit is contained in:
morluto
2026-07-12 21:12:18 +00:00
parent 4110a4d717
commit 4ff4c11a00
178 changed files with 26320 additions and 1222 deletions
+254
View File
@@ -0,0 +1,254 @@
import { createHash, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { realpath } from "node:fs/promises";
import { spawn } from "node:child_process";
import { err, ok, type Result } from "../domain/result.js";
export interface NativeCommandCapture {
readonly tool: string;
readonly executable: string;
readonly executableSha256: string;
readonly toolVersion: string | null;
readonly versionReason: string | null;
readonly arguments: readonly string[];
readonly stdout: string;
readonly stderr: string;
readonly stdoutBytes: number;
readonly stderrBytes: number;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
readonly exitCode: number | null;
readonly signal: string | null;
}
export class NativeCommandFailure extends Error {
constructor(
readonly tool: string,
readonly reason:
| "unavailable"
| "cancelled"
| "timeout"
| "output-limit"
| "nonzero-exit"
| "io",
readonly exitCode: number | null = null,
options?: ErrorOptions,
) {
super(`Native command ${tool} failed: ${reason}`, options);
}
}
export interface NativeCommandRunner {
run(
tool: string,
arguments_: readonly string[],
options: {
readonly signal?: AbortSignal;
readonly timeoutMs: number;
readonly maxOutputBytes: number;
readonly acceptNonZero?: boolean;
},
): Promise<Result<NativeCommandCapture, NativeCommandFailure>>;
}
/** Run allowlisted Xcode tools directly with bounded output and no shell. */
export class XcrunCommandRunner implements NativeCommandRunner {
readonly #resolved = new Map<
string,
Promise<Result<ResolvedTool, NativeCommandFailure>>
>();
run(
tool: string,
arguments_: readonly string[],
options: {
readonly signal?: AbortSignal;
readonly timeoutMs: number;
readonly maxOutputBytes: number;
readonly acceptNonZero?: boolean;
},
): Promise<Result<NativeCommandCapture, NativeCommandFailure>> {
if (!ALLOWED_TOOLS.has(tool))
return Promise.resolve(
err(new NativeCommandFailure(tool, "unavailable")),
);
return this.#resolve(tool).then(async (resolved) => {
if (!resolved.ok) return resolved;
const captured = await captureProcess(
resolved.value.path,
arguments_,
tool,
options,
);
return captured.ok
? ok({
...captured.value,
tool,
executable: resolved.value.path,
executableSha256: resolved.value.sha256,
toolVersion: null,
versionReason:
"Tool exposes no uniform stable version flag; executable digest identifies it.",
arguments: [...arguments_],
})
: captured;
});
}
#resolve(tool: string): Promise<Result<ResolvedTool, NativeCommandFailure>> {
const existing = this.#resolved.get(tool);
if (existing !== undefined) return existing;
const pending = resolveTool(tool);
this.#resolved.set(tool, pending);
return pending;
}
}
interface ResolvedTool {
readonly path: string;
readonly sha256: string;
}
const ALLOWED_TOOLS = new Set([
"codesign",
"dyld_info",
"dwarfdump",
"file",
"lipo",
"nm",
"otool",
"plutil",
"strings",
"swift-demangle",
"vtool",
]);
const resolveTool = async (
tool: string,
): Promise<Result<ResolvedTool, NativeCommandFailure>> => {
const found = await captureProcess(
"/usr/bin/xcrun",
["--find", tool],
"xcrun",
{ timeoutMs: 5_000, maxOutputBytes: 64 * 1024 },
);
if (!found.ok || found.value.exitCode !== 0)
return err(new NativeCommandFailure(tool, "unavailable"));
const candidate = found.value.stdout.trim();
if (!candidate.startsWith("/"))
return err(new NativeCommandFailure(tool, "unavailable"));
try {
const path = await realpath(candidate);
return ok({ path, sha256: await hashFile(path) });
} catch (cause: unknown) {
return err(new NativeCommandFailure(tool, "io", null, { cause }));
}
};
type ProcessCapture = Omit<
NativeCommandCapture,
| "tool"
| "executable"
| "executableSha256"
| "toolVersion"
| "versionReason"
| "arguments"
>;
const captureProcess = (
executable: string,
arguments_: readonly string[],
tool: string,
options: {
readonly signal?: AbortSignal;
readonly timeoutMs: number;
readonly maxOutputBytes: number;
readonly acceptNonZero?: boolean;
},
): Promise<Result<ProcessCapture, NativeCommandFailure>> =>
new Promise((resolve) => {
if (options.signal?.aborted === true) {
resolve(err(new NativeCommandFailure(tool, "cancelled")));
return;
}
const runToken = randomUUID();
const child = spawn(executable, [...arguments_], {
shell: false,
stdio: ["ignore", "pipe", "pipe"],
env: {
PATH: "/usr/bin:/bin:/usr/sbin:/sbin",
LC_ALL: "C",
LANG: "C",
REA_NATIVE_RUN_TOKEN: runToken,
},
});
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
let stdoutBytes = 0;
let stderrBytes = 0;
let settled = false;
let reason: NativeCommandFailure["reason"] | undefined;
const finish = (
result: Result<ProcessCapture, NativeCommandFailure>,
): void => {
if (settled) return;
settled = true;
clearTimeout(timeout);
options.signal?.removeEventListener("abort", onAbort);
resolve(result);
};
const stop = (failure: NativeCommandFailure["reason"]): void => {
reason ??= failure;
child.kill("SIGKILL");
};
const onAbort = (): void => stop("cancelled");
options.signal?.addEventListener("abort", onAbort, { once: true });
const timeout = setTimeout(() => stop("timeout"), options.timeoutMs);
child.stdout.on("data", (chunk: Buffer) => {
stdoutBytes += chunk.length;
if (stdoutBytes + stderrBytes > options.maxOutputBytes)
stop("output-limit");
else stdout.push(chunk);
});
child.stderr.on("data", (chunk: Buffer) => {
stderrBytes += chunk.length;
if (stdoutBytes + stderrBytes > options.maxOutputBytes)
stop("output-limit");
else stderr.push(chunk);
});
child.once("error", (cause: unknown) =>
finish(err(new NativeCommandFailure(tool, "io", null, { cause }))),
);
child.once("close", (code, signal) => {
if (reason !== undefined) {
finish(err(new NativeCommandFailure(tool, reason, code)));
return;
}
if (code !== 0 && options.acceptNonZero !== true) {
finish(err(new NativeCommandFailure(tool, "nonzero-exit", code)));
return;
}
finish(
ok({
stdout: Buffer.concat(stdout).toString("utf8"),
stderr: Buffer.concat(stderr).toString("utf8"),
stdoutBytes,
stderrBytes,
stdoutTruncated: false,
stderrTruncated: false,
exitCode: code,
signal,
}),
);
});
});
const hashFile = (path: string): Promise<string> =>
new Promise((resolve, reject) => {
const hash = createHash("sha256");
const stream = createReadStream(path);
stream.on("data", (chunk) => hash.update(chunk));
stream.once("error", reject);
stream.once("end", () => resolve(hash.digest("hex")));
});
+490
View File
@@ -0,0 +1,490 @@
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
import { realpath, stat } from "node:fs/promises";
import { parse as parseXmlPlist } from "plist";
import { z } from "zod";
import {
createAnalysisExecution,
type AnalysisClient,
type AnalysisOperation,
type AnalysisProvider,
type CapabilityDescriptor,
type ProviderIdentity,
} from "../application/AnalysisProvider.js";
import {
NATIVE_TOOL_CONTRACTS,
type NativeToolName,
} from "../contracts/nativeToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
AnalysisTimeoutError,
ProviderAdapterError,
type AnalysisError,
} from "../domain/errors.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import {
demangleSwiftSchema,
inspectPlistSchema,
inspectSignatureSchema,
listArchitecturesSchema,
type NativeCommandInvocation,
} from "../domain/nativeInspection.js";
import { err, ok, type Result } from "../domain/result.js";
import {
NativeCommandFailure,
XcrunCommandRunner,
type NativeCommandCapture,
type NativeCommandRunner,
} from "./CommandRunner.js";
import { parseCodeSignature } from "./parsers/codesign.js";
import { parseDemangledSymbols } from "./parsers/demangle.js";
import { parseLipoArchitectures } from "./parsers/lipo.js";
import { parsePlistJson } from "./parsers/plist.js";
import {
architectureLocations,
inspectNativeMacho,
} from "./NativeMachoInspection.js";
const IDENTITY: ProviderIdentity = Object.freeze({
id: "native-macos",
name: "macOS native inspection utilities",
version: null,
});
const TIMEOUT_MS = 30_000;
const OUTPUT_LIMIT = 4 * 1024 * 1024;
/** Read-only semantic provider composed from Xcode command-line utilities. */
export class NativeMacOSProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[];
constructor(
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(),
platform: NodeJS.Platform = process.platform,
) {
const available = platform === "darwin";
this.#capabilities = Object.freeze(
NATIVE_TOOL_CONTRACTS.map((contract): CapabilityDescriptor => {
const availability = available
? ({ available: true, reason: null } as const)
: ({
available: false,
reason: "Native macOS utilities require macOS.",
} as const);
return Object.freeze({
provider: IDENTITY,
operation: contract.name,
inputContractVersion: 1,
outputContractVersion: 1,
...availability,
pagination: "none" as const,
exhaustive: contract.name !== "inspect_macho",
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: true,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
}),
limits: Object.freeze({
maxResults: contract.name === "demangle_swift" ? 500 : null,
maxPayloadBytes: OUTPUT_LIMIT,
timeoutMs: TIMEOUT_MS,
}),
limitations: Object.freeze([
"Availability and textual formats depend on the installed macOS/Xcode toolchain.",
]),
});
}),
);
}
identity(): ProviderIdentity {
return IDENTITY;
}
capabilities(): readonly CapabilityDescriptor[] {
return this.#capabilities;
}
createClient(target: BinaryTarget): AnalysisClient {
return new NativeMacOSClient(target, this.runner);
}
}
class NativeMacOSClient implements AnalysisClient {
constructor(
private readonly target: BinaryTarget,
private readonly runner: NativeCommandRunner,
) {}
async execute(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: { readonly signal?: AbortSignal },
) {
if (operation === "health")
return ok(createAnalysisExecution(null, IDENTITY));
if (!isNativeOperation(operation))
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
"Operation is not implemented by native macOS tools.",
),
);
try {
const observation = await this.#dispatch(
operation,
parameters,
options?.signal,
);
return observation.ok
? ok(
createAnalysisExecution(observation.value.result, IDENTITY, {
rawResult: { provenance: observation.value.provenance },
limitations: observation.value.limitations,
locations: observation.value.locations,
}),
)
: observation;
} catch (cause: unknown) {
return err(
new AnalysisOutputError(operation, "Native output parsing failed", {
cause,
}),
);
}
}
close(): Promise<void> {
return Promise.resolve();
}
#dispatch(
operation: NativeToolName,
parameters: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
switch (operation) {
case "inspect_macho":
return this.#inspectMacho(signal);
case "inspect_signature":
return this.#inspectSignature(signal);
case "inspect_plist":
return this.#inspectPlist(parameters, signal);
case "list_architectures":
return this.#listArchitectures(signal);
case "demangle_swift":
return this.#demangle(parameters, signal);
}
}
async #listArchitectures(
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
const capture = await this.#run(
"list_architectures",
"lipo",
["-detailed_info", this.target.path],
{ signal },
);
if (!capture.ok) return capture;
const provenance = [invocation(capture.value, this.target.path)];
const result = listArchitecturesSchema.parse({
architectures: {
items: parseLipoArchitectures(capture.value.stdout),
total: parseLipoArchitectures(capture.value.stdout).length,
exhaustive: true,
limitations: [],
},
provenance,
limitations: [],
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: [],
locations: architectureLocations(result.architectures.items),
});
}
async #demangle(
parameters: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
const symbols = z.array(z.string()).safeParse(parameters.symbols);
if (!symbols.success)
return err(
new AnalysisOutputError(
"demangle_swift",
"symbols were not parsed strings",
),
);
const capture = await this.#run(
"demangle_swift",
"swift-demangle",
["--compact", ...symbols.data],
{ signal },
);
if (!capture.ok) return capture;
const provenance = [invocation(capture.value, this.target.path)];
const result = demangleSwiftSchema.parse({
symbols: parseDemangledSymbols(symbols.data, capture.value.stdout),
provenance,
limitations: [],
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: [],
locations: [],
});
}
async #inspectSignature(
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
const display = await this.#run(
"inspect_signature",
"codesign",
["-d", "--verbose=4", this.target.path],
{ signal, acceptNonZero: true },
);
if (!display.ok) return display;
const requirements = await this.#run(
"inspect_signature",
"codesign",
["-d", "-r-", this.target.path],
{ signal, acceptNonZero: true },
);
if (!requirements.ok) return requirements;
const entitlements = await this.#run(
"inspect_signature",
"codesign",
["-d", "--entitlements", ":-", this.target.path],
{ signal, acceptNonZero: true },
);
if (!entitlements.ok) return entitlements;
const unsigned = /not signed at all|code object is not signed/iu.test(
`${display.value.stdout}\n${display.value.stderr}`,
);
const parsed = parseCodeSignature(
`${display.value.stdout}\n${display.value.stderr}`,
unsigned,
);
const requirementText =
/designated\s*=>\s*(.+)$/mu.exec(
`${requirements.value.stdout}\n${requirements.value.stderr}`,
)?.[1] ?? null;
const entitlementValue = parseEntitlements(
`${entitlements.value.stdout}\n${entitlements.value.stderr}`,
);
const provenance = [
display.value,
requirements.value,
entitlements.value,
].map((capture) => invocation(capture, this.target.path));
const result = inspectSignatureSchema.parse({
...parsed,
designated_requirement: requirementText,
entitlements: entitlementValue,
provenance,
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: result.limitations,
locations: [],
});
}
async #inspectPlist(
parameters: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
const requested = parameters.relative_path;
if (typeof requested !== "string")
return err(
new AnalysisOutputError(
"inspect_plist",
"relative_path was not a string",
),
);
const plist = await resolvePlistPath(this.target, requested);
if (!plist.ok) return plist;
const classified = await this.#run(
"inspect_plist",
"file",
["-b", plist.value],
{ signal },
);
if (!classified.ok) return classified;
const capture = await this.#run(
"inspect_plist",
"plutil",
["-convert", "json", "-o", "-", "--", plist.value],
{ signal },
);
if (!capture.ok) return capture;
const parsed = parsePlistJson(capture.value.stdout);
const provenance = [classified.value, capture.value].map((item) =>
invocation(item, plist.value, "$PLIST"),
);
const result = inspectPlistSchema.parse({
format: /binary property list/iu.test(classified.value.stdout)
? "binary"
: /XML|text/iu.test(classified.value.stdout)
? "xml"
: "unknown",
...parsed,
source_path: requested,
provenance,
limitations: [],
});
return ok({
result: jsonValueSchema.parse(result),
provenance,
limitations: [],
locations: [{ kind: "artifact-path", path: requested }],
});
}
async #inspectMacho(
signal?: AbortSignal,
): Promise<Result<NativeObservation, AnalysisError>> {
if (this.target.format !== "mach-o")
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
"inspect_macho",
"Active artifact is not Mach-O.",
),
);
return inspectNativeMacho({
target: this.target,
...(signal === undefined ? {} : { signal }),
run: (tool, arguments_, commandSignal) =>
this.#run("inspect_macho", tool, arguments_, {
signal: commandSignal,
}),
invocation: (capture) => invocation(capture, this.target.path),
});
}
async #run(
operation: NativeToolName,
tool: string,
arguments_: readonly string[],
options: {
readonly signal?: AbortSignal | undefined;
readonly acceptNonZero?: boolean;
} = {},
): Promise<Result<NativeCommandCapture, AnalysisError>> {
const captured = await this.runner.run(tool, arguments_, {
...(options.signal === undefined ? {} : { signal: options.signal }),
timeoutMs: TIMEOUT_MS,
maxOutputBytes: OUTPUT_LIMIT,
acceptNonZero: options.acceptNonZero ?? false,
});
if (captured.ok) return captured;
return err(translateCommandFailure(operation, captured.error));
}
}
interface NativeObservation {
readonly result: JsonValue;
readonly provenance: readonly NativeCommandInvocation[];
readonly limitations: readonly string[];
readonly locations: readonly EvidenceLocation[];
}
const isNativeOperation = (
operation: AnalysisOperation,
): operation is NativeToolName =>
NATIVE_TOOL_CONTRACTS.some(({ name }) => name === operation);
const translateCommandFailure = (
operation: NativeToolName,
failure: NativeCommandFailure,
): AnalysisError => {
if (failure.reason === "unavailable")
return new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
`${failure.tool} is unavailable through xcrun.`,
);
if (failure.reason === "cancelled")
return new AnalysisCancelledError(operation);
if (failure.reason === "timeout")
return new AnalysisTimeoutError(operation, TIMEOUT_MS);
return new ProviderAdapterError(IDENTITY.id, operation, { cause: failure });
};
const invocation = (
capture: NativeCommandCapture,
artifactPath: string,
alias = "$ARTIFACT",
): NativeCommandInvocation => ({
tool: capture.tool,
command: [
capture.executable,
...capture.arguments.map((argument) =>
argument === artifactPath ? alias : argument,
),
],
tool_version: capture.toolVersion,
version_reason: capture.versionReason,
executable_sha256: capture.executableSha256,
exit: { code: capture.exitCode, signal: capture.signal },
stdout_bytes: capture.stdoutBytes,
stderr_bytes: capture.stderrBytes,
stdout_truncated: capture.stdoutTruncated,
stderr_truncated: capture.stderrTruncated,
});
const parseEntitlements = (output: string): JsonValue | null => {
const start = output.indexOf("<?xml");
const end = output.lastIndexOf("</plist>");
if (start < 0 || end < start) return null;
return jsonValueSchema.parse(
parseXmlPlist(output.slice(start, end + "</plist>".length)),
);
};
const resolvePlistPath = async (
target: BinaryTarget,
requested: string,
): Promise<Result<string, AnalysisError>> => {
try {
const source = target.sourcePath ?? target.path;
const sourceMetadata = await stat(source);
const root = sourceMetadata.isDirectory() ? source : dirname(target.path);
const candidate = resolve(root, requested);
if (!within(root, candidate))
return err(new ProviderAdapterError(IDENTITY.id, "inspect_plist"));
const canonicalRoot = await realpath(root);
const canonical = await realpath(candidate);
if (!within(canonicalRoot, canonical))
return err(new ProviderAdapterError(IDENTITY.id, "inspect_plist"));
return ok(canonical);
} catch (cause: unknown) {
return err(
new ProviderAdapterError(IDENTITY.id, "inspect_plist", { cause }),
);
}
};
const within = (root: string, candidate: string): boolean => {
const child = relative(root, candidate);
return (
child === "" ||
(!child.startsWith(`..${sep}`) && child !== ".." && !isAbsolute(child))
);
};
+206
View File
@@ -0,0 +1,206 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { AnalysisError } from "../domain/errors.js";
import {
inspectMachoSchema,
type NativeCommandInvocation,
} from "../domain/nativeInspection.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type { NativeCommandCapture } from "./CommandRunner.js";
import { parseDyldSymbols } from "./parsers/dyldInfo.js";
import { parseLipoArchitectures } from "./parsers/lipo.js";
import { parseOtoolLoadCommands } from "./parsers/otool.js";
interface NativeMachoObservation {
readonly result: JsonValue;
readonly provenance: readonly NativeCommandInvocation[];
readonly limitations: readonly string[];
readonly locations: readonly EvidenceLocation[];
}
interface NativeMachoInspectionContext {
readonly target: BinaryTarget;
readonly signal?: AbortSignal;
readonly run: (
tool: string,
arguments_: readonly string[],
signal?: AbortSignal,
) => Promise<Result<NativeCommandCapture, AnalysisError>>;
readonly invocation: (
capture: NativeCommandCapture,
) => NativeCommandInvocation;
}
const COMMANDS = [
["file", ["-b"]],
["lipo", ["-detailed_info"]],
["otool", ["-l"]],
["nm", ["-gjU"]],
["dyld_info", ["-imports"]],
["dyld_info", ["-exports"]],
["dwarfdump", ["--uuid"]],
["vtool", ["-show-build"]],
] as const;
/** Inspect one Mach-O with bounded native commands and normalized output. */
export const inspectNativeMacho = async (
context: NativeMachoInspectionContext,
): Promise<Result<NativeMachoObservation, AnalysisError>> => {
const captures: NativeCommandCapture[] = [];
for (const [tool, prefix] of COMMANDS) {
const captured = await context.run(
tool,
[...prefix, context.target.path],
context.signal,
);
if (!captured.ok) return err(captured.error);
captures.push(captured.value);
}
const result = normalizeMacho(captures, context.invocation);
return ok({
result: jsonValueSchema.parse(result),
provenance: result.provenance,
limitations: result.limitations,
locations: fileOffsetLocations(result),
});
};
const normalizeMacho = (
captures: readonly NativeCommandCapture[],
toInvocation: (capture: NativeCommandCapture) => NativeCommandInvocation,
) => {
const byTool = captureLookup(captures);
const architectures = parseLipoArchitectures(byTool("lipo").stdout);
const load = parseOtoolLoadCommands(byTool("otool").stdout);
const imports = parseDyldSymbols(byTool("dyld_info", 0).stdout, "imports");
const dyldExports = parseDyldSymbols(
byTool("dyld_info", 1).stdout,
"exports",
);
const exports = uniqueSymbols([
...dyldExports,
...parseNmExports(byTool("nm").stdout),
]);
const uuid =
/UUID:\s*([A-Fa-f0-9-]+)/u.exec(byTool("dwarfdump").stdout)?.[1] ??
load.uuid;
const provenance = captures.map(toInvocation);
const limitations = [
"Imports and exports combine dyld_info and nm; stripped or toolchain-hidden symbols may be absent.",
"vtool output is retained as provenance but only otool build metadata is normalized.",
];
return inspectMachoSchema.parse({
format: "mach-o",
endian: parseEndian(byTool("file").stdout),
word_size: parseWordSize(byTool("file").stdout),
file_type: load.fileType,
flags: load.flags,
uuid: uuid ?? null,
entrypoints: covered(load.entrypoints, true),
architectures: covered(architectures, true),
build_metadata: covered(load.builds, true),
load_commands: covered(load.commands, true),
dependencies: covered(load.dependencies, true),
imports: covered(imports, false, [
"dyld_info textual imports may omit chained or toolchain-unsupported metadata.",
]),
exports: covered(exports, false, [
"Merged nm/dyld_info results may be incomplete for stripped binaries.",
]),
segments: covered(
load.segments.map((segment) => ({
...segment,
sections: covered(segment.sections, true),
})),
true,
),
provenance,
limitations,
});
};
const captureLookup =
(captures: readonly NativeCommandCapture[]) =>
(tool: string, occurrence = 0): NativeCommandCapture => {
const capture = captures.filter((item) => item.tool === tool)[occurrence];
if (capture === undefined) throw new TypeError(`Missing ${tool} capture`);
return capture;
};
const parseNmExports = (output: string) =>
output
.split(/\r?\n/u)
.filter((name) => name.length > 0)
.map((name) => ({
name,
address: null,
weak: null,
reexport: null,
source: "nm",
}));
const parseEndian = (output: string): "little" | "big" | null =>
/little-endian/iu.test(output)
? "little"
: /big-endian/iu.test(output)
? "big"
: null;
const parseWordSize = (output: string): 32 | 64 | null =>
/64-bit/iu.test(output) ? 64 : /32-bit/iu.test(output) ? 32 : null;
const covered = <Value>(
items: readonly Value[],
exhaustive: boolean,
limitations: readonly string[] = [],
) => ({
items: [...items],
total: exhaustive ? items.length : null,
exhaustive,
limitations: [...limitations],
});
const uniqueSymbols = <Value extends { readonly name: string }>(
items: readonly Value[],
): Value[] => {
const unique = new Map<string, Value>();
for (const item of items) unique.set(item.name, item);
return [...unique.values()].sort((left, right) =>
left.name.localeCompare(right.name),
);
};
const fileOffsetLocations = (
macho: ReturnType<typeof inspectMachoSchema.parse>,
): EvidenceLocation[] => {
const locations = architectureLocations(macho.architectures.items);
for (const segment of macho.segments.items) {
if (segment.file_offset === null || segment.file_size === null) continue;
locations.push({
kind: "file-offset-range",
start: segment.file_offset,
end: segment.file_offset + segment.file_size,
});
}
return locations;
};
/** Project architecture slices into evidence file-offset locations. */
export const architectureLocations = (
architectures: readonly {
readonly file_offset: number | null;
readonly size: number | null;
}[],
): EvidenceLocation[] => {
const locations: EvidenceLocation[] = [];
for (const { file_offset: offset, size } of architectures) {
if (offset === null) continue;
locations.push(
size === null
? { kind: "file-offset", offset }
: { kind: "file-offset-range", start: offset, end: offset + size },
);
}
return locations;
};
+62
View File
@@ -0,0 +1,62 @@
import {
inspectSignatureSchema,
type InspectSignature,
} from "../../domain/nativeInspection.js";
/** Parse bounded `codesign -d` diagnostics, which Apple emits on stderr. */
export const parseCodeSignature = (
output: string,
unsigned: boolean,
): Omit<InspectSignature, "provenance"> => {
const values = new Map<string, string>();
const authorities: string[] = [];
const cdhashes: string[] = [];
for (const line of output.split(/\r?\n/u)) {
if (line.startsWith("CodeDirectory ")) {
values.set("CodeDirectory", line.slice("CodeDirectory ".length));
continue;
}
const separator = line.indexOf("=");
if (separator < 1) continue;
const key = line.slice(0, separator).trim();
const value = line.slice(separator + 1).trim();
if (key === "Authority") authorities.push(value);
else if (key === "CDHash") cdhashes.push(value);
else values.set(key, value);
}
const parsed = inspectSignatureSchema.omit({ provenance: true }).parse({
signed: !unsigned,
identifier: values.get("Identifier") ?? null,
team_identifier: nullableCodeSignValue(values.get("TeamIdentifier")),
format: values.get("Format") ?? null,
cdhashes,
hash_algorithms: splitAlgorithms(values.get("Hash choices")),
authorities,
designated_requirement: values.get("designated") ?? null,
entitlements: null,
timestamp: values.get("Timestamp") ?? null,
hardened_runtime: parseRuntime(values.get("CodeDirectory")),
limitations: unsigned
? ["Artifact is not signed."]
: [
"Entitlements and designated requirements require separate bounded commands.",
],
});
return parsed;
};
const nullableCodeSignValue = (value: string | undefined): string | null =>
value === undefined || value === "not set" ? null : value;
const splitAlgorithms = (value: string | undefined): string[] =>
value === undefined
? []
: value
.split(/[,+\s]+/u)
.map((part) => part.trim())
.filter((part) => part.length > 0);
const parseRuntime = (value: string | undefined): boolean | null => {
if (value === undefined) return null;
return /\bruntime\b/u.test(value);
};
+32
View File
@@ -0,0 +1,32 @@
import { z } from "zod";
const resultSchema = z.object({
input: z.string(),
output: z.string(),
status: z.enum(["demangled", "unchanged", "invalid"]),
});
/** Preserve input ordering while parsing `swift-demangle --compact` lines. */
export const parseDemangledSymbols = (
inputs: readonly string[],
output: string,
) => {
const lines = output.trimEnd().split(/\r?\n/u);
if (lines.length !== inputs.length)
throw new TypeError("swift-demangle output count does not match input");
return inputs.map((input, index) => {
const value = lines[index];
if (value === undefined)
throw new TypeError("swift-demangle omitted an output line");
return resultSchema.parse({
input,
output: value,
status:
value === input
? input.startsWith("$s") || input.startsWith("_$s")
? "invalid"
: "unchanged"
: "demangled",
});
});
};
+29
View File
@@ -0,0 +1,29 @@
/** Parse bounded imports/exports from dyld_info's line-oriented tables. */
export const parseDyldSymbols = (output: string, mode: "imports" | "exports") =>
output.split(/\r?\n/u).flatMap((rawLine) => {
const line = rawLine.trim();
if (
line.length === 0 ||
/^(?:imports|exports|binding|address|segment|ordinal)\b/iu.test(line)
)
return [];
const tokens = line.split(/\s+/u);
const name = tokens.at(-1);
if (name === undefined || !/^(?:_|\$s|objc_|swift_)/u.test(name)) return [];
const addressToken = tokens.find((token) =>
/^0x[a-fA-F0-9]+$/u.test(token),
);
return [
{
name,
address: addressToken ?? null,
weak: /\bweak\b/iu.test(line) ? true : null,
reexport: /\bre-?export\b/iu.test(line)
? true
: mode === "exports"
? false
: null,
source: mode === "imports" ? (tokens.at(-2) ?? null) : null,
},
];
});
+71
View File
@@ -0,0 +1,71 @@
import { z } from "zod";
const architectureSchema = z.object({
name: z.string().min(1),
cpu_type: z.string().nullable(),
cpu_subtype: z.string().nullable(),
file_offset: z.number().int().min(0).nullable(),
size: z.number().int().min(0).nullable(),
alignment: z.number().int().min(0).nullable(),
});
export type LipoArchitecture = z.infer<typeof architectureSchema>;
/** Parse `lipo -detailed_info` into deterministic slice metadata. */
export const parseLipoArchitectures = (output: string): LipoArchitecture[] => {
const architectures: LipoArchitecture[] = [];
let current: Record<string, string> | undefined;
const flush = (): void => {
if (current === undefined) return;
const name = current.architecture ?? current["Non-fat file"];
if (name !== undefined)
architectures.push(
architectureSchema.parse({
name: name.includes(" is architecture: ")
? (name.split(" is architecture: ").at(-1) ?? name)
: name,
cpu_type: current.cputype ?? null,
cpu_subtype: current.cpusubtype ?? null,
file_offset: integer(current.offset),
size: integer(current.size),
alignment: alignment(current.align),
}),
);
current = undefined;
};
for (const rawLine of output.split(/\r?\n/u)) {
const line = rawLine.trim();
if (line.startsWith("Non-fat file:")) {
flush();
current = { "Non-fat file": line };
continue;
}
if (line.startsWith("architecture ")) {
flush();
current = { architecture: line.slice("architecture ".length).trim() };
continue;
}
const match = /^(cputype|cpusubtype|offset|size|align)\s+(.+)$/u.exec(line);
if (match?.[1] !== undefined && match[2] !== undefined) {
current ??= {};
current[match[1]] = match[2].trim();
}
}
flush();
if (architectures.length === 0)
throw new TypeError("lipo output contained no architectures");
return architectures;
};
const integer = (value: string | undefined): number | null => {
if (value === undefined) return null;
const parsed = Number.parseInt(value, 10);
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
};
const alignment = (value: string | undefined): number | null => {
if (value === undefined) return null;
const exponent = /2\^(\d+)/u.exec(value)?.[1];
if (exponent !== undefined) return 2 ** Number.parseInt(exponent, 10);
return integer(value);
};
+296
View File
@@ -0,0 +1,296 @@
interface ParsedSection {
readonly segment: string;
readonly name: string;
readonly address: string | null;
readonly size: number | null;
readonly file_offset: number | null;
readonly alignment: number | null;
readonly flags: string[];
}
interface ParsedSegment {
readonly name: string;
readonly vm_address: string | null;
readonly vm_size: number | null;
readonly file_offset: number | null;
readonly file_size: number | null;
readonly maximum_permissions: ReturnType<typeof permissions>;
readonly initial_permissions: ReturnType<typeof permissions>;
readonly sections: ParsedSection[];
}
interface ParsedLoadCommands {
readonly commands: Array<{
index: number;
kind: string;
file_offset: number | null;
fields: Record<string, string | number | null>;
}>;
readonly segments: ParsedSegment[];
readonly dependencies: Array<{
path: string;
kind: string;
current_version: string | null;
compatibility_version: string | null;
}>;
readonly entrypoints: Array<{ file_offset: number }>;
readonly builds: Array<{
platform: string | null;
minimum_os: string | null;
sdk: string | null;
tools: Array<{ name: string; version: string }>;
}>;
uuid: string | null;
readonly flags: Set<string>;
}
/** Parse stable fields from `otool -l`, preserving unknown command fields. */
export const parseOtoolLoadCommands = (output: string) => {
const headerTokens = parseHeaderTokens(output);
const state = createLoadCommandState(headerTokens);
for (const block of output.split(/(?=Load command \d+)/u))
parseLoadCommand(block, state);
return {
fileType: headerTokens?.[4] ?? null,
flags: [...state.flags].sort(),
uuid: state.uuid,
commands: state.commands,
segments: state.segments,
dependencies: state.dependencies,
entrypoints: state.entrypoints,
builds: state.builds,
};
};
const parseHeaderTokens = (output: string): string[] | undefined =>
output
.split(/\r?\n/u)
.map((line) => line.trim())
.find((line) => /^0x[a-fA-F0-9]+\s/u.test(line))
?.split(/\s+/u);
const createLoadCommandState = (
headerTokens: readonly string[] | undefined,
): ParsedLoadCommands => ({
commands: [],
segments: [],
dependencies: [],
entrypoints: [],
builds: [],
uuid: null,
flags: new Set(headerTokens?.slice(7) ?? []),
});
const parseLoadCommand = (block: string, state: ParsedLoadCommands): void => {
const indexText = /^Load command (\d+)/u.exec(block)?.[1];
if (indexText === undefined) return;
const header = block.split(/\n\s*Section\n/u)[0] ?? block;
const fields = parseFields(header);
const kind = stringField(fields, "cmd") ?? "unknown";
state.commands.push({
index: Number.parseInt(indexText, 10),
kind,
file_offset: null,
fields,
});
collectUuid(kind, fields, state);
collectEntrypoint(kind, fields, state);
collectBuild(kind, block, fields, state);
collectDependency(kind, fields, state);
collectSegment(kind, block, fields, state);
collectFlags(fields, state.flags);
};
const collectUuid = (
kind: string,
fields: Readonly<Record<string, string | number | null>>,
state: ParsedLoadCommands,
): void => {
if (kind === "LC_UUID")
state.uuid = stringField(fields, "uuid") ?? state.uuid;
};
const collectEntrypoint = (
kind: string,
fields: Readonly<Record<string, string | number | null>>,
state: ParsedLoadCommands,
): void => {
if (kind !== "LC_MAIN") return;
const entry = numberField(fields, "entryoff");
if (entry !== null) state.entrypoints.push({ file_offset: entry });
};
const collectBuild = (
kind: string,
block: string,
fields: Readonly<Record<string, string | number | null>>,
state: ParsedLoadCommands,
): void => {
if (kind !== "LC_BUILD_VERSION") return;
state.builds.push({
platform: stringField(fields, "platform"),
minimum_os: stringField(fields, "minos"),
sdk: stringField(fields, "sdk"),
tools: parseBuildTools(block),
});
};
const collectDependency = (
kind: string,
fields: Readonly<Record<string, string | number | null>>,
state: ParsedLoadCommands,
): void => {
if (!kind.startsWith("LC_LOAD_") && kind !== "LC_ID_DYLIB") return;
state.dependencies.push({
path: stripOffsetSuffix(stringField(fields, "name")),
kind,
current_version: stringField(fields, "current version"),
compatibility_version: stringField(fields, "compatibility version"),
});
};
const collectSegment = (
kind: string,
block: string,
fields: Readonly<Record<string, string | number | null>>,
state: ParsedLoadCommands,
): void => {
if (kind === "LC_SEGMENT" || kind === "LC_SEGMENT_64")
state.segments.push(parseSegment(block, fields));
};
const collectFlags = (
fields: Readonly<Record<string, string | number | null>>,
flags: Set<string>,
): void => {
const rawFlags = stringField(fields, "flags");
if (rawFlags === null) return;
for (const flag of rawFlags.split(/\s+/u))
if (flag.length > 0) flags.add(flag);
};
const parseFields = (block: string): Record<string, string | number | null> => {
const fields: Record<string, string | number | null> = {};
for (const rawLine of block.split(/\r?\n/u).slice(1)) {
const line = rawLine.trim();
const match = /^(\S+(?:\s+version)?)\s+(.+)$/u.exec(line);
if (match?.[1] === undefined || match[2] === undefined) continue;
const value = match[2].trim();
fields[match[1]] = numeric(value) ?? value;
}
return fields;
};
const parseSegment = (
block: string,
fields: Readonly<Record<string, string | number | null>>,
): ParsedSegment => ({
name: stringField(fields, "segname") ?? "unknown",
vm_address: hexField(fields, "vmaddr"),
vm_size: numberField(fields, "vmsize"),
file_offset: numberField(fields, "fileoff"),
file_size: numberField(fields, "filesize"),
maximum_permissions: permissions(stringField(fields, "maxprot")),
initial_permissions: permissions(stringField(fields, "initprot")),
sections: parseSections(block),
});
const parseSections = (block: string): ParsedSection[] =>
block
.split(/(?=\n\s*Section\n)/u)
.slice(1)
.map((sectionBlock) => {
const fields = parseFields(`Section${sectionBlock}`);
return {
segment: stringField(fields, "segname") ?? "unknown",
name: stringField(fields, "sectname") ?? "unknown",
address: hexField(fields, "addr"),
size: numberField(fields, "size"),
file_offset: numberField(fields, "offset"),
alignment: sectionAlignment(numberField(fields, "align")),
flags: (stringField(fields, "flags") ?? "")
.split(/\s+/u)
.filter((flag) => flag.length > 0),
};
});
const parseBuildTools = (
block: string,
): Array<{ name: string; version: string }> => {
const tools: Array<{ name: string; version: string }> = [];
const lines = block.split(/\r?\n/u).map((line) => line.trim());
for (let index = 0; index < lines.length - 1; index += 1) {
const tool = /^tool\s+(.+)$/u.exec(lines[index] ?? "")?.[1];
const version = /^version\s+(.+)$/u.exec(lines[index + 1] ?? "")?.[1];
if (tool !== undefined && version !== undefined)
tools.push({ name: tool, version });
}
return tools;
};
const permissions = (raw: string | null) => {
if (raw === null)
return { read: null, write: null, execute: null, raw: null };
const numericValue = numeric(raw);
if (numericValue !== null)
return {
read: (numericValue & 4) !== 0,
write: (numericValue & 2) !== 0,
execute: (numericValue & 1) !== 0,
raw,
};
if (/^[r-][w-][x-]$/u.test(raw))
return {
read: raw[0] === "r",
write: raw[1] === "w",
execute: raw[2] === "x",
raw,
};
return { read: null, write: null, execute: null, raw };
};
const numeric = (value: string): number | null => {
const token = value.split(/\s+/u)[0];
if (token === undefined || !/^(?:0x[a-fA-F0-9]+|\d+)$/u.test(token))
return null;
const parsed = Number.parseInt(token, token.startsWith("0x") ? 16 : 10);
return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : null;
};
const stringField = (
fields: Readonly<Record<string, string | number | null>>,
name: string,
): string | null => {
const value = fields[name];
return typeof value === "string"
? value
: value === undefined || value === null
? null
: String(value);
};
const numberField = (
fields: Readonly<Record<string, string | number | null>>,
name: string,
): number | null => {
const value = fields[name];
return typeof value === "number"
? value
: typeof value === "string"
? numeric(value)
: null;
};
const hexField = (
fields: Readonly<Record<string, string | number | null>>,
name: string,
): string | null => {
const value = numberField(fields, name);
return value === null ? null : `0x${value.toString(16)}`;
};
const stripOffsetSuffix = (value: string | null): string =>
value?.replace(/\s+\(offset\s+\d+\)$/u, "") ?? "unknown";
const sectionAlignment = (exponent: number | null): number | null =>
exponent === null || exponent > 52 ? null : 2 ** exponent;
+24
View File
@@ -0,0 +1,24 @@
import { z } from "zod";
const plistObject = z.record(z.string(), z.unknown());
/** Parse plutil JSON output and project stable bundle metadata. */
export const parsePlistJson = (output: string) => {
const value: unknown = JSON.parse(output);
const object = plistObject.safeParse(value);
const field = (name: string): string | null => {
if (!object.success) return null;
const candidate = object.data[name];
return typeof candidate === "string" ? candidate : null;
};
return {
value,
bundle: {
identifier: field("CFBundleIdentifier"),
executable: field("CFBundleExecutable"),
name: field("CFBundleName"),
version: field("CFBundleVersion"),
short_version: field("CFBundleShortVersionString"),
},
};
};