Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(apple): bound binary plist expansion before decoding keyed archives (#1515)
Kaoru08222bf812772d72
diff --git a/src/artifacts/apple/InterfaceBuilderDecodeBudget.ts b/src/artifacts/apple/InterfaceBuilderDecodeBudget.tsindex d8b6f3a93..a43529634 100644--- a/src/artifacts/apple/InterfaceBuilderDecodeBudget.ts+++ b/src/artifacts/apple/InterfaceBuilderDecodeBudget.ts@@ -147,10 +147,45 @@ const estimateXmlPlistExpansion = (return decodedSourceBytes * 2 + elementCount * 128;};-/** Count every expanded binary-plist reference before calling plist.parseBinary. */-const estimateBinaryPlistExpansion = (+/** Resource a binary plist preflight found over its budget, or a malformed reference cycle. */+export type BinaryPlistExpansionFailure = "cycle" | "depth" | "expansion";++const interfaceBuilderBudgetFailure = (+ _kind: BinaryPlistExpansionFailure,+ message: string,+): Error =>+ new InterfaceBuilderDecodeBudgetExceeded(+ "aggregate_decode_budget_exhausted",+ message,+ );++/** How a caller names and reports binary plist expansion failures. */+export interface BinaryPlistExpansionOptions {+ /** Budget named in failure messages. */+ readonly budget?: string;+ /** Error for budget, depth, and reference-cycle failures. */+ readonly fail?: (kind: BinaryPlistExpansionFailure, message: string) => Error;+ /**+ * Structural bounds: "strict" keeps objects and the offset table before the+ * trailer; "decoder" admits exactly what plist.parseBinary can read, so+ * expansion is bounded without rejecting archives that decoder accepts.+ */+ readonly bounds?: "strict" | "decoder";+}++/**+ * Count every expanded binary-plist reference before calling plist.parseBinary,+ * which recurses on each reference and copies shared containers. Malformed+ * structure throws TypeError; budget, depth, and cycle failures use `fail`.+ */+export const estimateBinaryPlistExpansion = (bytes: Buffer,maxBytes: number,+ {+ budget = "the aggregate Interface Builder decode budget",+ fail = interfaceBuilderBudgetFailure,+ bounds = "strict",+ }: BinaryPlistExpansionOptions = {},): number => {if (bytes.length < 40)throw new TypeError("binary plist trailer is truncated");@@ -172,20 +207,19 @@ const estimateBinaryPlistExpansion = (const objectCount = readInteger(trailer + 8, 8);const topObject = readInteger(trailer + 16, 8);const offsetTable = readInteger(trailer + 24, 8);+ const tableEnd = bounds === "strict" ? trailer : bytes.length;+ const objectsEnd = bounds === "strict" ? offsetTable : bytes.length;if (objectCount < 1 ||topObject < 0 ||topObject >= objectCount ||offsetTable < 8 ||- offsetTable + objectCount * offsetSize > trailer+ offsetTable + objectCount * offsetSize > tableEnd)throw new TypeError("binary plist trailer or object table is invalid");let estimate = bytes.length * 2 + objectCount * 16;if (estimate > maxBytes)- throw new InterfaceBuilderDecodeBudgetExceeded(- "aggregate_decode_budget_exhausted",- "binary plist object table exceeds the aggregate Interface Builder decode budget",- );+ throw fail("expansion", `binary plist object table exceeds ${budget}`);const active = new Set<number>();const pending: Array<{ object: number; depth: number; exit: boolean }> = [@@ -201,26 +235,20 @@ const estimateBinaryPlistExpansion = (}pendingObjectCount -= 1;if (entry.depth > 128)- throw new InterfaceBuilderDecodeBudgetExceeded(- "aggregate_decode_budget_exhausted",- "binary plist nesting exceeds the aggregate Interface Builder decode budget",- );+ throw fail("depth", `binary plist nesting exceeds ${budget}`);if (active.has(entry.object))- throw new InterfaceBuilderDecodeBudgetExceeded(- "aggregate_decode_budget_exhausted",- "binary plist reference cycle exceeds the aggregate Interface Builder decode budget",- );+ throw fail("cycle", `binary plist reference cycle exceeds ${budget}`);estimate += 96;if (estimate > maxBytes)- throw new InterfaceBuilderDecodeBudgetExceeded(- "aggregate_decode_budget_exhausted",- "binary plist reference expansion exceeds the aggregate Interface Builder decode budget",+ throw fail(+ "expansion",+ `binary plist reference expansion exceeds ${budget}`,);const offset = readInteger(offsetTable + entry.object * offsetSize,offsetSize,);- if (offset < 8 || offset >= offsetTable)+ if (offset < 8 || offset >= objectsEnd)throw new TypeError("binary plist object offset is invalid");const marker = bytes[offset] ?? 0;const type = marker >> 4;@@ -234,31 +262,31 @@ const estimateBinaryPlistExpansion = (const integerSize = 1 << (extMarker & 0x0f);size = readInteger(cursor, integerSize);cursor += integerSize;- if (size < 0 || cursor > offsetTable)+ if (size < 0 || cursor > objectsEnd)throw new TypeError("binary plist extended object size is invalid");}if (type === 4 || type === 5 || type === 6) {const byteLength = type === 6 ? size * 2 : size;- if (cursor + byteLength > offsetTable)+ if (cursor + byteLength > objectsEnd)throw new TypeError("binary plist scalar object is truncated");estimate += type === 4 ? size + 4 * Math.ceil(size / 3) : byteLength * 2;if (estimate > maxBytes)- throw new InterfaceBuilderDecodeBudgetExceeded(- "aggregate_decode_budget_exhausted",- "binary plist scalar expansion exceeds the aggregate Interface Builder decode budget",+ throw fail(+ "expansion",+ `binary plist scalar expansion exceeds ${budget}`,);continue;}if (type !== 10 && type !== 13) continue;const childCount = type === 13 ? size * 2 : size;const refsEnd = cursor + childCount * referenceSize;- if (!Number.isSafeInteger(refsEnd) || refsEnd > offsetTable)+ if (!Number.isSafeInteger(refsEnd) || refsEnd > objectsEnd)throw new TypeError("binary plist reference table is truncated");const availableNodes = Math.floor((maxBytes - estimate) / 96);if (childCount > availableNodes - pendingObjectCount)- throw new InterfaceBuilderDecodeBudgetExceeded(- "aggregate_decode_budget_exhausted",- "binary plist reference expansion exceeds the aggregate Interface Builder decode budget",+ throw fail(+ "expansion",+ `binary plist reference expansion exceeds ${budget}`,);active.add(entry.object);pending.push({ object: entry.object, depth: entry.depth, exit: true });diff --git a/src/artifacts/apple/KeyedArchiveReader.test.ts b/src/artifacts/apple/KeyedArchiveReader.test.tsindex dd569a6e5..c6a1319f1 100644--- a/src/artifacts/apple/KeyedArchiveReader.test.ts+++ b/src/artifacts/apple/KeyedArchiveReader.test.ts@@ -103,3 +103,88 @@ describe("inert keyed archive decoding", () => {);});});++/** Encode a bplist00 whose objects reference each other by index. */+const binaryPlist = (objects: readonly Buffer[]): Buffer => {+ const header = Buffer.from("bplist00");+ const offsets: number[] = [];+ let position = header.length;+ for (const object of objects) {+ offsets.push(position);+ position += object.length;+ }+ const table = Buffer.alloc(objects.length * 4);+ offsets.forEach((offset, index) => table.writeUInt32BE(offset, index * 4));+ const trailer = Buffer.alloc(32);+ trailer[6] = 4;+ trailer[7] = 2;+ trailer.writeBigUInt64BE(BigInt(objects.length), 8);+ trailer.writeBigUInt64BE(0n, 16);+ trailer.writeBigUInt64BE(BigInt(position), 24);+ return Buffer.concat([header, ...objects, table, trailer]);+};+const plistArray = (references: readonly number[]): Buffer => {+ const bytes = Buffer.alloc(1 + references.length * 2);+ bytes[0] = 0xa0 | references.length;+ references.forEach((reference, index) =>+ bytes.writeUInt16BE(reference, 1 + index * 2),+ );+ return bytes;+};+const plistString = (value: string): Buffer =>+ Buffer.concat([Buffer.from([0x50 | value.length]), Buffer.from(value)]);+// {"$archiver": "NSKeyedArchiver", "$top": {"root": UID 1}, "$objects": object 8}+const keyedRoot = (payload: readonly Buffer[]): Buffer =>+ binaryPlist([+ Buffer.from([0xd3, 0, 1, 0, 3, 0, 4, 0, 2, 0, 8, 0, 5]),+ plistString("$archiver"),+ Buffer.concat([+ Buffer.from([0x5f, 0x10, 15]),+ Buffer.from("NSKeyedArchiver"),+ ]),+ plistString("$objects"),+ plistString("$top"),+ Buffer.from([0xd1, 0, 6, 0, 7]),+ plistString("root"),+ Buffer.from([0x80, 1]),+ ...payload,+ ]);++describe("binary plist reference preflight", () => {+ const selection = { offset: 0, limit: 10 };++ it("reports a reference cycle as malformed, not as an oversized archive", () => {+ expect(() =>+ decodeKeyedArchiveBytes(keyedRoot([plistArray([8])]), selection),+ ).toThrow(+ new TypeError(+ "binary plist object references form a cycle, which a property list cannot represent",+ ),+ );+ });++ it("rejects exponential shared-container expansion before decoding", () => {+ // Forty levels of [next, next] expand to 2^40 leaves in a few hundred bytes.+ const levels = Array.from({ length: 40 }, (_, index) =>+ plistArray([9 + index, 9 + index]),+ );+ expect(() =>+ decodeKeyedArchiveBytes(+ keyedRoot([...levels, plistString("x")]),+ selection,+ ),+ ).toThrow(RangeError);+ });++ it("decodes shared leaf references", () => {+ const decoded = decodeKeyedArchiveBytes(+ keyedRoot([plistArray([9, 9, 9]), plistString("$null")]),+ selection,+ );+ expect(decoded.objects.map(({ id, value }) => [id, value])).toEqual([+ [0, "$null"],+ [1, "$null"],+ [2, "$null"],+ ]);+ });+});diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.tsindex 729215929..fefc6d97a 100644--- a/src/artifacts/apple/KeyedArchiveReader.ts+++ b/src/artifacts/apple/KeyedArchiveReader.ts@@ -28,8 +28,11 @@ import { ArtifactReaderFailure } from "../ArtifactReader.js";import type { ArtifactEntry } from "../ArtifactReader.js";import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js";+import { estimateBinaryPlistExpansion } from "./InterfaceBuilderDecodeBudget.js";const MAX_BYTES = 64 * 1024 * 1024;+/** Decoded representation budget, the same 8:1 ratio Interface Builder uses. */+const MAX_DECODE_BYTES = 8 * MAX_BYTES;/** Parse inert plist bytes, preserving data and dates with explicit typed values. */export const decodeKeyedArchiveBytes = (@@ -45,6 +48,20 @@ export const decodeKeyedArchiveBytes = ();const binary = bytes.subarray(0, 8).toString("ascii") === "bplist00";const xmlText = binary ? undefined : decodeXmlPlistText(bytes);+ // plist.parseBinary recurses on every object reference and copies shared+ // containers, so a few hundred bytes can exhaust memory or the stack.+ // RangeError reports a resource limit; a reference cycle is malformed.+ if (binary)+ estimateBinaryPlistExpansion(bytes, MAX_DECODE_BYTES, {+ budget: "the keyed archive decode budget",+ fail: (kind, message) =>+ kind === "cycle"+ ? new TypeError(+ "binary plist object references form a cycle, which a property list cannot represent",+ )+ : new RangeError(message),+ bounds: "decoder",+ });const parsed = binary? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }: parseXmlPropertyList(xmlText ?? "");