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
+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"),
},
};
};