fix(native): centralize slice knowledge and validate local ticket framing
This commit is contained in:
@@ -64,6 +64,10 @@ import {
|
||||
unconfirmedNestedCode,
|
||||
} from "./NativeSignaturePosture.js";
|
||||
import { deriveSecurityFacets } from "../domain/native/codeSigningPosture.js";
|
||||
import {
|
||||
signatureArchitectures,
|
||||
summarizeSignatureSlices,
|
||||
} from "./NativeSignatureSlices.js";
|
||||
import { parseDemangledSymbols } from "./parsers/demangle.js";
|
||||
import { parseLipoArchitectures } from "./parsers/lipo.js";
|
||||
import {
|
||||
@@ -426,6 +430,11 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
verifyPath,
|
||||
aggregateUnsigned,
|
||||
);
|
||||
if (
|
||||
sliceState.value.classificationUnknown &&
|
||||
verification.status !== "valid"
|
||||
)
|
||||
verification.status = "unknown";
|
||||
limitations.push(...(await unconfirmedNestedCode(verification)));
|
||||
if (verification.status === "unknown")
|
||||
limitations.push(
|
||||
@@ -492,17 +501,23 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
readonly captures: readonly NativeCommandCapture[];
|
||||
readonly limitations: readonly string[];
|
||||
readonly signed?: boolean;
|
||||
readonly classificationUnknown: boolean;
|
||||
},
|
||||
AnalysisError
|
||||
>
|
||||
> {
|
||||
const universal = codeSignArchitectures(format, this.target).length > 1;
|
||||
const universal = signatureArchitectures(format, this.target).length > 1;
|
||||
const gate =
|
||||
!unsigned &&
|
||||
(isNonzeroUnsignedObservation(requirements) ||
|
||||
isNonzeroUnsignedObservation(entitlements));
|
||||
if (!gate && !universal)
|
||||
return ok({ mixed: false, captures: [], limitations: [] });
|
||||
return ok({
|
||||
mixed: false,
|
||||
captures: [],
|
||||
limitations: [],
|
||||
classificationUnknown: false,
|
||||
});
|
||||
const slices = await this.#inspectMixedSignatureSlices(
|
||||
format,
|
||||
requirements.exitCode !== 0,
|
||||
@@ -514,7 +529,10 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
mixed: gate || (universal && slices.value.mixed),
|
||||
captures: slices.value.captures,
|
||||
limitations: slices.value.limitations,
|
||||
signed: slices.value.signed,
|
||||
...(slices.value.signed === undefined
|
||||
? {}
|
||||
: { signed: slices.value.signed }),
|
||||
classificationUnknown: slices.value.classificationUnknown,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -543,7 +561,7 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
const unsigned: string[] = [];
|
||||
const unclassified: string[] = [];
|
||||
const postures = new Map<string, string>();
|
||||
for (const architecture of codeSignArchitectures(format, this.target)) {
|
||||
for (const architecture of signatureArchitectures(format, this.target)) {
|
||||
const slice = await this.#run(
|
||||
"inspect_signature",
|
||||
"codesign",
|
||||
@@ -574,15 +592,20 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
// Signed slices can still disagree among themselves: per-architecture
|
||||
// display is authoritative per slice, so differing flags or entitlements
|
||||
// also make the aggregate facets unknown.
|
||||
const postureDiffers = new Set(postures.values()).size > 1;
|
||||
const mixed =
|
||||
unclassified.length > 0 ||
|
||||
(signed.length > 0 && unsigned.length > 0) ||
|
||||
postureDiffers;
|
||||
const summary = summarizeSignatureSlices({
|
||||
signed,
|
||||
unsigned,
|
||||
unclassified,
|
||||
postures,
|
||||
});
|
||||
const limitations: string[] = [];
|
||||
if (unsigned.length > 0)
|
||||
limitations.push(`Unsigned Mach-O slices: ${unsigned.join(", ")}.`);
|
||||
if (postureDiffers && unsigned.length === 0 && unclassified.length === 0)
|
||||
if (
|
||||
summary.postureDiffers &&
|
||||
unsigned.length === 0 &&
|
||||
unclassified.length === 0
|
||||
)
|
||||
limitations.push(
|
||||
"Signed Mach-O slices differ in CodeDirectory flags or entitlements; aggregate facets are unknown.",
|
||||
);
|
||||
@@ -598,7 +621,7 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
limitations.push(
|
||||
"The aggregate entitlements are unavailable because Mach-O slices have mixed signing states.",
|
||||
);
|
||||
return ok({ captures, limitations, mixed, signed: signed.length > 0 });
|
||||
return ok({ captures, limitations, ...summary });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -784,7 +807,8 @@ interface MixedSignatureSlices {
|
||||
readonly limitations: readonly string[];
|
||||
/** A signed slice coexists with an unsigned or unclassifiable one. */
|
||||
readonly mixed: boolean;
|
||||
readonly signed: boolean;
|
||||
readonly signed: boolean | undefined;
|
||||
readonly classificationUnknown: boolean;
|
||||
}
|
||||
|
||||
const isNativeOperation = (
|
||||
@@ -842,41 +866,6 @@ const codeSignCaptureFailure = (
|
||||
? null
|
||||
: translateCodeSignExitFailure(capture);
|
||||
|
||||
/**
|
||||
* Architectures declared by a universal Mach-O format string, or undefined
|
||||
* for thin files. Display commands without `-a` report only the host-native
|
||||
* slice, so universal files need per-slice probing before any aggregate
|
||||
* signing claim.
|
||||
*/
|
||||
const universalSliceArchitectures = (
|
||||
format: string | null,
|
||||
): string[] | undefined => {
|
||||
const universal = /^Mach-O universal \(([^)\r\n]+)\)$/u.exec(
|
||||
format ?? "",
|
||||
)?.[1];
|
||||
if (universal === undefined) return undefined;
|
||||
const architectures = universal
|
||||
.split(/\s+/u)
|
||||
.filter((architecture) =>
|
||||
/^(?:i386|x86_64|x86_64h|armv7|arm64|arm64e)$/u.test(architecture),
|
||||
);
|
||||
return architectures.length > 0 ? [...new Set(architectures)] : undefined;
|
||||
};
|
||||
|
||||
const codeSignArchitectures = (
|
||||
format: string | null,
|
||||
target: BinaryTarget,
|
||||
): string[] => {
|
||||
const declared = universalSliceArchitectures(format) ?? [];
|
||||
const available =
|
||||
target.kind === "executable" && target.format === "mach-o"
|
||||
? target.availableArchitectures.map((architecture) =>
|
||||
architecture === "x86" ? "i386" : architecture,
|
||||
)
|
||||
: [];
|
||||
return [...new Set([...declared, ...available])];
|
||||
};
|
||||
|
||||
const invocation = (
|
||||
capture: NativeCommandCapture,
|
||||
artifactPath: string,
|
||||
|
||||
@@ -5,6 +5,7 @@ import { dirname, join } from "node:path";
|
||||
|
||||
import type { InspectSignature } from "../domain/native/nativeInspection.js";
|
||||
import type { NativeCommandCapture } from "./CommandRunner.js";
|
||||
import { ticketStructureIssue } from "./NotarizationTicket.js";
|
||||
|
||||
/** Notarization tickets are a few kilobytes; larger files are hashed in chunks. */
|
||||
const HASH_CHUNK_BYTES = 64 * 1024;
|
||||
@@ -59,7 +60,7 @@ export const verificationIOFailure = (
|
||||
diagnostics: readonly string[],
|
||||
): boolean =>
|
||||
diagnostics.some((line) =>
|
||||
/permission denied|operation not permitted|\bEACCES\b|\bEPERM\b/iu.test(
|
||||
/permission denied|operation not permitted|\bEACCES\b|\bEPERM\b|I\/O error|input\/output error/iu.test(
|
||||
line,
|
||||
),
|
||||
);
|
||||
@@ -155,12 +156,36 @@ export const stapledTicket = async (
|
||||
size: null,
|
||||
reason: "changed",
|
||||
};
|
||||
const structureIssue = await ticketStructureIssue(
|
||||
async (offset, length) => {
|
||||
signal?.throwIfAborted();
|
||||
const buffer = new Uint8Array(length);
|
||||
let done = 0;
|
||||
while (done < length) {
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
done,
|
||||
length - done,
|
||||
offset + done,
|
||||
);
|
||||
if (bytesRead === 0) break;
|
||||
done += bytesRead;
|
||||
}
|
||||
return buffer.subarray(0, done);
|
||||
},
|
||||
opened.size,
|
||||
);
|
||||
const hash = createHash("sha256");
|
||||
const buffer = new Uint8Array(HASH_CHUNK_BYTES);
|
||||
let size = 0;
|
||||
for (;;) {
|
||||
while (size < opened.size) {
|
||||
signal?.throwIfAborted();
|
||||
const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
|
||||
const { bytesRead } = await handle.read(
|
||||
buffer,
|
||||
0,
|
||||
Math.min(buffer.length, opened.size - size),
|
||||
size,
|
||||
);
|
||||
if (bytesRead === 0) break;
|
||||
size += bytesRead;
|
||||
hash.update(buffer.subarray(0, bytesRead));
|
||||
@@ -198,11 +223,11 @@ export const stapledTicket = async (
|
||||
};
|
||||
}
|
||||
return {
|
||||
status: "present",
|
||||
status: structureIssue === null ? "present" : "unreadable",
|
||||
path: relative,
|
||||
sha256: hash.digest("hex"),
|
||||
size,
|
||||
reason: null,
|
||||
reason: structureIssue,
|
||||
};
|
||||
} finally {
|
||||
await handle.close();
|
||||
@@ -268,6 +293,7 @@ const errorCode = (cause: unknown): string | undefined =>
|
||||
export const SIGNATURE_POSTURE_LIMITATIONS = [
|
||||
"Signature verification is local `codesign --verify --deep --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.",
|
||||
"Ticket presence requires recognized local s8ch/g8tk container and DER framing; certificate authenticity, ticket signature validity, and ticket-to-code binding are not verified.",
|
||||
];
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
|
||||
/** Architectures to probe, retaining subtypes from codesign and target inventory. */
|
||||
export const signatureArchitectures = (
|
||||
format: string | null,
|
||||
target: BinaryTarget,
|
||||
): string[] => {
|
||||
const universal = /^Mach-O universal \(([^)\r\n]+)\)$/u.exec(
|
||||
format ?? "",
|
||||
)?.[1];
|
||||
const declared =
|
||||
universal?.split(/\s+/u).filter((name) => name.length > 0) ?? [];
|
||||
const available =
|
||||
target.kind === "executable" && target.format === "mach-o"
|
||||
? target.availableArchitectures.map((name) =>
|
||||
name === "x86" ? "i386" : name,
|
||||
)
|
||||
: [];
|
||||
return [...new Set([...declared, ...available])];
|
||||
};
|
||||
|
||||
/** Aggregate signing knowledge, keeping inconclusive probes distinct from unsigned. */
|
||||
export const summarizeSignatureSlices = (input: {
|
||||
readonly signed: readonly string[];
|
||||
readonly unsigned: readonly string[];
|
||||
readonly unclassified: readonly string[];
|
||||
readonly postures: ReadonlyMap<string, string>;
|
||||
}): {
|
||||
readonly signed: boolean | undefined;
|
||||
readonly mixed: boolean;
|
||||
readonly postureDiffers: boolean;
|
||||
readonly classificationUnknown: boolean;
|
||||
} => {
|
||||
const classificationUnknown = input.unclassified.length > 0;
|
||||
const postureDiffers = new Set(input.postures.values()).size > 1;
|
||||
const signed =
|
||||
input.signed.length > 0
|
||||
? true
|
||||
: classificationUnknown || input.unsigned.length === 0
|
||||
? undefined
|
||||
: false;
|
||||
return {
|
||||
signed,
|
||||
classificationUnknown,
|
||||
postureDiffers,
|
||||
mixed:
|
||||
classificationUnknown ||
|
||||
(input.signed.length > 0 && input.unsigned.length > 0) ||
|
||||
postureDiffers,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { notarizationTicketFixture } from "../../tests/fixtures/notarizationTicket.js";
|
||||
import { ticketStructureIssue } from "./NotarizationTicket.js";
|
||||
|
||||
const inspect = (bytes: Uint8Array) =>
|
||||
ticketStructureIssue(
|
||||
async (offset, length) => bytes.subarray(offset, offset + length),
|
||||
bytes.length,
|
||||
);
|
||||
|
||||
it("recognizes local ticket framing without claiming cryptographic validity", async () => {
|
||||
expect(await inspect(notarizationTicketFixture())).toBeNull();
|
||||
});
|
||||
|
||||
it("rejects empty, arbitrary, truncated and contradictory ticket containers", async () => {
|
||||
expect(await inspect(new Uint8Array())).toContain("Not a recognized");
|
||||
expect(await inspect(Buffer.from("stapled ticket bytes"))).toContain(
|
||||
"Not a recognized",
|
||||
);
|
||||
const ticket = Buffer.from(notarizationTicketFixture());
|
||||
expect(await inspect(ticket.subarray(0, ticket.length - 1))).toContain(
|
||||
"signature",
|
||||
);
|
||||
ticket.writeUInt32LE(2, 16 + 4 + 8);
|
||||
expect(await inspect(ticket)).toContain("hash records disagree");
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
/** Bounded positional reader used to inspect local ticket framing. */
|
||||
export type TicketReadAt = (
|
||||
offset: number,
|
||||
length: number,
|
||||
) => Promise<Uint8Array>;
|
||||
|
||||
/**
|
||||
* Inspect the local s8ch/g8tk ticket framing. Observed in stapled app tickets;
|
||||
* see bytewitch's NotarizedTicket decoder and apple-platform-rs ticket_lookup.
|
||||
* This does not authenticate certificates, signatures, or notarized cdhashes.
|
||||
*/
|
||||
export const ticketStructureIssue = async (
|
||||
read: TicketReadAt,
|
||||
size: number,
|
||||
): Promise<string | null> => {
|
||||
const header = Buffer.from(await read(0, 16));
|
||||
if (header.length !== 16 || header.toString("ascii", 0, 4) !== "s8ch")
|
||||
return "Not a recognized s8ch notarization ticket container";
|
||||
if (header.readUInt32LE(4) !== 1)
|
||||
return `Unsupported notarization ticket container version ${header.readUInt32LE(4)}`;
|
||||
const certificateSize = header.readUInt32LE(8);
|
||||
const contentSize = header.readUInt32LE(12);
|
||||
const contentOffset = 16 + certificateSize;
|
||||
const signatureOffset = contentOffset + contentSize;
|
||||
if (certificateSize < 4 || contentSize < 24 || signatureOffset >= size)
|
||||
return "Ticket certificate, content, or signature extent is missing or truncated";
|
||||
const content = Buffer.from(await read(contentOffset, 24));
|
||||
if (content.length !== 24 || content.toString("ascii", 0, 4) !== "g8tk")
|
||||
return "Ticket content has no complete g8tk header";
|
||||
const hashSize = content.readUInt16LE(6);
|
||||
const hashCount = content.readUInt32LE(8);
|
||||
if (
|
||||
hashSize === 0 ||
|
||||
hashCount === 0 ||
|
||||
24 + (hashSize + 1) * hashCount !== contentSize
|
||||
)
|
||||
return "Ticket hash records disagree with the declared content length";
|
||||
const certificates = await derSequenceExtent(read, 16, certificateSize);
|
||||
if (certificates !== certificateSize)
|
||||
return "Ticket certificate block has malformed DER framing";
|
||||
const signatureSize = await derSequenceExtent(
|
||||
read,
|
||||
signatureOffset,
|
||||
size - signatureOffset,
|
||||
);
|
||||
if (signatureSize === null || signatureSize < 8)
|
||||
return "Ticket signature has malformed DER framing";
|
||||
// ECDSA encodings can be padded to 72 bytes; only zero padding is accepted.
|
||||
const paddingSize = size - signatureOffset - signatureSize;
|
||||
if (paddingSize > 2) return "Ticket has unrecognized trailing bytes";
|
||||
const padding = await read(signatureOffset + signatureSize, paddingSize);
|
||||
if (padding.byteLength !== paddingSize || padding.some((byte) => byte !== 0))
|
||||
return "Ticket has malformed signature padding";
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Read only a DER SEQUENCE tag/length and check its extent against its section. */
|
||||
const derSequenceExtent = async (
|
||||
read: TicketReadAt,
|
||||
offset: number,
|
||||
available: number,
|
||||
): Promise<number | null> => {
|
||||
const prefix = Buffer.from(await read(offset, Math.min(6, available)));
|
||||
if (prefix.length < 2 || prefix[0] !== 0x30) return null;
|
||||
const first = prefix[1] ?? 0;
|
||||
if (first < 128) return first + 2 <= available ? first + 2 : null;
|
||||
const width = first & 0x7f;
|
||||
if (width === 0 || width > 4 || prefix.length < width + 2 || prefix[2] === 0)
|
||||
return null;
|
||||
let length = 0;
|
||||
for (let index = 0; index < width; index++)
|
||||
length = length * 256 + (prefix[index + 2] ?? 0);
|
||||
return length >= 128 && length + width + 2 <= available
|
||||
? length + width + 2
|
||||
: null;
|
||||
};
|
||||
@@ -9,6 +9,7 @@ import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import { inspectSignatureSchema } from "../../../../src/domain/native/nativeInspection.js";
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { notarizationTicketFixture } from "../../../fixtures/notarizationTicket.js";
|
||||
import {
|
||||
NativeFixtureRunner as FixtureRunner,
|
||||
nativeMachoTarget as machoTarget,
|
||||
@@ -34,7 +35,7 @@ class TamperedRunner extends FixtureRunner {
|
||||
}
|
||||
}
|
||||
|
||||
const fixtureApp = async (ticket: string | undefined) => {
|
||||
const fixtureApp = async (ticket: string | Uint8Array | undefined) => {
|
||||
const directory = await createTestTempDirectory("rea-signature-posture-");
|
||||
const app = join(directory, "Fixture.app");
|
||||
const executable = join(app, "Contents/MacOS/Fixture");
|
||||
@@ -47,7 +48,7 @@ const fixtureApp = async (ticket: string | undefined) => {
|
||||
|
||||
describe("native signature posture", () => {
|
||||
it("verifies the opened bundle and reports a stapled ticket", async () => {
|
||||
const ticket = "stapled ticket bytes";
|
||||
const ticket = notarizationTicketFixture();
|
||||
const { app, executable } = await fixtureApp(ticket);
|
||||
const signature = await new NativeMacOSProvider(
|
||||
new FixtureRunner(),
|
||||
@@ -395,6 +396,44 @@ describe("native signature posture slice-aware cases", () => {
|
||||
});
|
||||
|
||||
describe("signature architecture coverage", () => {
|
||||
it("does not turn inconclusive slice probes into an unsigned claim", async () => {
|
||||
const { app, executable } = await fixtureApp(undefined);
|
||||
const signature = await new NativeMacOSProvider(
|
||||
new InconclusiveSlicesRunner(),
|
||||
"darwin",
|
||||
)
|
||||
.createClient(machoTarget(executable, app))
|
||||
.execute("inspect_signature", {});
|
||||
if (!signature.ok) throw signature.error;
|
||||
const result = inspectSignatureSchema.parse(signature.value.result);
|
||||
expect(result.signed).toBe(true);
|
||||
expect(result.verification?.status).toBe("unknown");
|
||||
expect(
|
||||
result.security_facets.every(({ state }) => state === "unknown"),
|
||||
).toBe(true);
|
||||
expect(result.limitations).toContainEqual(
|
||||
expect.stringContaining("could not be classified"),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not report arbitrary ticket-location bytes as a stapled ticket", async () => {
|
||||
const bytes = "stapled ticket bytes";
|
||||
const { app, executable } = await fixtureApp(bytes);
|
||||
const signature = await new NativeMacOSProvider(
|
||||
new FixtureRunner(),
|
||||
"darwin",
|
||||
)
|
||||
.createClient(machoTarget(executable, app))
|
||||
.execute("inspect_signature", {});
|
||||
if (!signature.ok) throw signature.error;
|
||||
const result = inspectSignatureSchema.parse(signature.value.result);
|
||||
expect(result.stapled_ticket).toMatchObject({
|
||||
status: "unreadable",
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
size: bytes.length,
|
||||
reason: "Not a recognized s8ch notarization ticket container",
|
||||
});
|
||||
});
|
||||
it("probes a valid x86_64h subtype rather than dropping it", async () => {
|
||||
const { app, executable } = await fixtureApp(undefined);
|
||||
const signature = await new NativeMacOSProvider(
|
||||
@@ -548,6 +587,25 @@ class UniversalMixedRunner extends FixtureRunner {
|
||||
}
|
||||
}
|
||||
|
||||
/** Aggregate display succeeds, but per-architecture probes and verification fail operationally. */
|
||||
class InconclusiveSlicesRunner extends FixtureRunner {
|
||||
override async run(tool: string, arguments_: readonly string[]) {
|
||||
const result = await super.run(tool, arguments_);
|
||||
if (!result.ok || tool !== "codesign") return result;
|
||||
if (!arguments_.includes("-a") && arguments_[0] !== "--verify")
|
||||
return result;
|
||||
const stderr = "I/O error reading signing data\n";
|
||||
return ok({
|
||||
...result.value,
|
||||
stdout: "",
|
||||
stderr,
|
||||
exitCode: 1,
|
||||
stdoutBytes: 0,
|
||||
stderrBytes: Buffer.byteLength(stderr),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** A nested helper whose file name ends in a carriage return. */
|
||||
class CarriageReturnPathRunner extends FixtureRunner {
|
||||
override async run(tool: string, arguments_: readonly string[]) {
|
||||
|
||||
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
/** Synthetic local ticket framing; it does not contain an authenticated certificate/signature. */
|
||||
export const notarizationTicketFixture = (): Uint8Array => {
|
||||
const certificates = Buffer.from([0x30, 2, 0x30, 0]);
|
||||
const content = Buffer.alloc(45);
|
||||
content.write("g8tk", 0, "ascii");
|
||||
content.writeUInt16LE(2, 4);
|
||||
content.writeUInt16LE(20, 6);
|
||||
content.writeUInt32LE(1, 8);
|
||||
content[24] = 2;
|
||||
content.fill(0xab, 25);
|
||||
const signature = Buffer.from([0x30, 6, 2, 1, 1, 2, 1, 1]);
|
||||
const header = Buffer.alloc(16);
|
||||
header.write("s8ch", 0, "ascii");
|
||||
header.writeUInt32LE(1, 4);
|
||||
header.writeUInt32LE(certificates.length, 8);
|
||||
header.writeUInt32LE(content.length, 12);
|
||||
return Buffer.concat([header, certificates, content, signature]);
|
||||
};
|
||||
Reference in New Issue
Block a user