Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(apple): refuse invalid binary dates and unknown sub-millisecond instants (#5786)

morlutoa00e4ac36306
diff --git a/docs/native-investigation.md b/docs/native-investigation.md
index 60105b42c..6d6fd4d32 100644
--- a/docs/native-investigation.md
+++ b/docs/native-investigation.md
@@ -714,7 +714,12 @@ leap seconds) and out-of-range dates remain explicit unknowns. REA does not
emulate CoreFoundation's normalization of overflowing calendar fields. Invalid
dates returned by other decoders retain `{ "$plist_type": "date", "iso8601": null }`
with a counted limitation. `inspect_plist` and Interface Builder decoding use
-the same projection.
+the same projection. Binary keyed-archive and Interface Builder plist decoding
+refuse a reachable date whose marker is not `0x33`. A valid `0x33` date is
+reported with an ISO-8601 timestamp only when its float64 seconds are exactly
+the canonical encoding of that millisecond instant. Any other finite binary
+date uses `{ "$plist_type": "date", "iso8601": null }` and the counted
+limitation; the archive bytes remain the source of the instant.
A negative-zero real is reported as `{ "$plist_type": "real", "value": "-0" }`
because a JSON number cannot carry the sign of zero. `inspect_plist` and
diff --git a/src/artifacts/apple/BinaryPlistDate.test.ts b/src/artifacts/apple/BinaryPlistDate.test.ts
new file mode 100644
index 000000000..c8cd376d1
--- /dev/null
+++ b/src/artifacts/apple/BinaryPlistDate.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+
+import { binaryPlistDateRepresentable } from "./BinaryPlistDate.js";
+
+describe("binary plist date instants", () => {
+ it("keeps canonical millisecond encodings and rejects nearby floats", () => {
+ expect(binaryPlistDateRepresentable(0.1)).toBe(true);
+ expect(binaryPlistDateRepresentable(0)).toBe(true);
+ expect(binaryPlistDateRepresentable(0.001)).toBe(true);
+ expect(binaryPlistDateRepresentable(-0)).toBe(true);
+ expect(binaryPlistDateRepresentable(0.1005)).toBe(false);
+ expect(binaryPlistDateRepresentable(0.1004)).toBe(false);
+ const next = Buffer.alloc(8);
+ next.writeDoubleBE(0.1);
+ next.writeBigUInt64BE(next.readBigUInt64BE(0) + 1n);
+ expect(binaryPlistDateRepresentable(next.readDoubleBE(0))).toBe(false);
+ expect(binaryPlistDateRepresentable(Number.NaN)).toBe(false);
+ expect(binaryPlistDateRepresentable(Number.POSITIVE_INFINITY)).toBe(false);
+ });
+});
diff --git a/src/artifacts/apple/BinaryPlistDate.ts b/src/artifacts/apple/BinaryPlistDate.ts
new file mode 100644
index 000000000..cfa512885
--- /dev/null
+++ b/src/artifacts/apple/BinaryPlistDate.ts
@@ -0,0 +1,18 @@
+/**
+ * Milliseconds between 1970-01-01 and 2001-01-01.
+ * Matches plist@5 `parse-binary.js` `EPOCH_2001`.
+ */
+const APPLE_REFERENCE_EPOCH_MILLISECONDS = 978_307_200_000;
+
+/**
+ * Whether plist@5's `new Date(seconds * 1000 + epoch)` denotes the same
+ * float64 seconds. Each source payload is judged on its own; distinct
+ * instants can share one rounded millisecond.
+ */
+export const binaryPlistDateRepresentable = (seconds: number): boolean => {
+ if (!Number.isFinite(seconds)) return false;
+ const decoded = new Date(seconds * 1000 + APPLE_REFERENCE_EPOCH_MILLISECONDS);
+ const time = Date.prototype.getTime.call(decoded);
+ if (!Number.isFinite(time)) return false;
+ return (time - APPLE_REFERENCE_EPOCH_MILLISECONDS) / 1000 === seconds;
+};
diff --git a/src/artifacts/apple/InterfaceBuilderAnalysis.ts b/src/artifacts/apple/InterfaceBuilderAnalysis.ts
index 26efffab2..1b04451cd 100644
--- a/src/artifacts/apple/InterfaceBuilderAnalysis.ts
+++ b/src/artifacts/apple/InterfaceBuilderAnalysis.ts
@@ -118,6 +118,7 @@ export const analyzeInterfaceBuilderBundle = async (input: {
let nib: ReturnType<typeof projectNibArchive> | null = null;
let xmlText: string | undefined;
let binaryPrototypeKeyObserved = false;
+ let binaryDatePayloadOffsets: readonly number[] = [];
if (isNibArchive) {
const documentBudget = new InterfaceBuilderDecodeBudget(
decodeBudget.remainingBytes,
@@ -147,6 +148,8 @@ export const analyzeInterfaceBuilderBundle = async (input: {
plistReservation = decodedReservation.estimatedBytes;
binaryPrototypeKeyObserved =
decodedReservation.binaryPrototypeKeyObserved;
+ binaryDatePayloadOffsets =
+ decodedReservation.binaryDatePayloadOffsets;
}
const {
value: raw,
@@ -155,7 +158,12 @@ export const analyzeInterfaceBuilderBundle = async (input: {
unknownScalarCount,
numberLiterals,
} = nib === null
- ? decodePlist(bytes, xmlText, binaryPrototypeKeyObserved)
+ ? decodePlist(
+ bytes,
+ xmlText,
+ binaryPrototypeKeyObserved,
+ binaryDatePayloadOffsets,
+ )
: {
value: nib.raw,
omittedPrototypeKeys: 0,
@@ -759,6 +767,7 @@ const decodePlist = (
bytes: Buffer,
xmlText: string | undefined,
binaryPrototypeKeyObserved: boolean,
+ binaryDatePayloadOffsets: readonly number[],
): {
readonly value: JsonValue;
readonly omittedPrototypeKeys: number | null;
@@ -773,7 +782,11 @@ const decodePlist = (
const { value, omittedPrototypeKeys, numberLiterals } = binary
? {
value: parseBinary(
- decodeBinaryPlistNumbers(bytes, binaryNumberMetadata!),
+ decodeBinaryPlistNumbers(
+ bytes,
+ binaryNumberMetadata!,
+ binaryDatePayloadOffsets,
+ ),
),
omittedPrototypeKeys: binaryPrototypeKeyObserved ? null : 0,
numberLiterals: binaryNumberMetadata!.literals,
diff --git a/src/artifacts/apple/InterfaceBuilderDecodeBudget.test.ts b/src/artifacts/apple/InterfaceBuilderDecodeBudget.test.ts
index 61492d69d..4354db08d 100644
--- a/src/artifacts/apple/InterfaceBuilderDecodeBudget.test.ts
+++ b/src/artifacts/apple/InterfaceBuilderDecodeBudget.test.ts
@@ -7,6 +7,7 @@ import { describe, expect, it } from "vitest";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import { preflightPropertyListDecode } from "./InterfaceBuilderDecodeBudget.js";
+import { unknownDateLimitation } from "../../domain/apple/plistValue.js";
import { parseXmlPropertyList } from "../../domain/propertyListKeys.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
@@ -141,3 +142,52 @@ describe("inert XML declaration examples in Interface Builder archives", () => {
).toMatchObject({ binaryPrototypeKeyObserved: false });
});
});
+
+describe("binary Interface Builder plist dates", () => {
+ const control = Buffer.from(
+ "62706c6973743030d4010203040506090c5924617263686976657258246f626a656374735424746f70582476657273696f6e5f100f4e534b657965644172636869766572a2070855246e756c6c333fb999999999999ad10a0b54726f6f74800112000186a008111b24293244474d56595e600000000000000101000000000000000d00000000000000000000000000000065",
+ "hex",
+ );
+ const marker = Buffer.alloc(9);
+ marker[0] = 0x33;
+ marker.writeDoubleBE(0.1, 1);
+
+ const nib = async (bytes: Buffer, name: string) => {
+ const root = await createTestTempDirectory(`rea-ib-date-${name}-`);
+ const bundle = join(root, "Example.app");
+ await mkdir(bundle);
+ await writeFile(join(bundle, "Panel.nib"), bytes);
+ return analyzeInterfaceBuilderBundle({
+ bundlePath: bundle,
+ targetSha256: "a".repeat(64),
+ });
+ };
+
+ it("refuses an invalid reachable date marker without projecting a timestamp", async () => {
+ const bytes = Buffer.from(control);
+ const offset = bytes.indexOf(marker);
+ bytes[offset] = 0x30;
+ const result = await nib(bytes, "marker");
+ expect(JSON.stringify(result)).not.toContain("2001-01-01T00:00:00.100Z");
+ expect(result.limitations.join("\n")).toContain(
+ "binary plist date marker 0x30 is invalid",
+ );
+ });
+
+ it("counts a sub-millisecond date as unknown and keeps the canonical control known", async () => {
+ const submillisecond = Buffer.from(control);
+ const offset = submillisecond.indexOf(marker);
+ submillisecond.writeDoubleBE(0.1005, offset + 1);
+ const unknown = await nib(submillisecond, "subms");
+ expect(unknown.limitations).toContain(
+ `Panel.nib: ${unknownDateLimitation(1)}`,
+ );
+ expect(JSON.stringify(unknown)).not.toContain("2001-01-01T00:00:00.100Z");
+
+ const known = await nib(Buffer.from(control), "known");
+ expect(known.limitations.join("\n")).not.toContain("date value(s)");
+ expect(known.limitations.join("\n")).not.toContain(
+ "binary plist date marker",
+ );
+ });
+});
diff --git a/src/artifacts/apple/InterfaceBuilderDecodeBudget.ts b/src/artifacts/apple/InterfaceBuilderDecodeBudget.ts
index fe813e8a9..4d47b5fdd 100644
--- a/src/artifacts/apple/InterfaceBuilderDecodeBudget.ts
+++ b/src/artifacts/apple/InterfaceBuilderDecodeBudget.ts
@@ -115,6 +115,7 @@ export const preflightPropertyListDecode = (
numberProjection,
),
binaryPrototypeKeyObserved: false,
+ binaryDatePayloadOffsets: [],
};
if (expansion.estimatedBytes > maxBytes)
throw new InterfaceBuilderDecodeBudgetExceeded(
@@ -225,6 +226,8 @@ export interface BinaryPlistExpansionOptions {
export interface PlistDecodePreflight {
readonly estimatedBytes: number;
readonly binaryPrototypeKeyObserved: boolean;
+ /** Offsets of reachable `0x33` date payloads. Empty for XML. */
+ readonly binaryDatePayloadOffsets: readonly number[];
}
const PROTOTYPE_KEY = "__proto__";
@@ -232,7 +235,8 @@ const PROTOTYPE_KEY = "__proto__";
/**
* 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`.
+ * structure, including a reachable date marker other than `0x33`, throws
+ * TypeError; budget, depth, and cycle failures use `fail`.
*/
export const estimateBinaryPlistExpansion = (
bytes: Buffer,
@@ -277,11 +281,14 @@ export const estimateBinaryPlistExpansion = (
// Metadata covers the full object table; projected values may repeat through references.
const objectBytes = numberProjection ? 144 : 16;
const expandedNodeBytes = numberProjection ? 224 : 96;
- // Number projection may require a same-sized parser-compatible input copy
- // for wide integers. Reserve for it before the caller allocates that copy.
+ // Number projection may require one same-sized parser-compatible input copy.
+ // That copy carries wide-integer rewrites and unrepresentable date payloads.
+ // Reserve for it before the caller allocates that copy.
let estimate =
bytes.length * (numberProjection ? 3 : 2) + objectCount * objectBytes;
let binaryPrototypeKeyObserved = false;
+ const datePayloadOffsets: number[] = [];
+ const recordedDateObjects = new Set<number>();
if (estimate > maxBytes)
throw fail("expansion", `binary plist object table exceeds ${budget}`);
@@ -366,6 +373,28 @@ export const estimateBinaryPlistExpansion = (
);
continue;
}
+ if (type === 3) {
+ // Binary plist dates are only marker 0x33 plus an 8-byte float inside
+ // the object region. Decoder bounds let other objects use trailing
+ // bytes; a date there would be parsed as a timestamp. The payload
+ // offset is retained so the decoder can judge that source instant
+ // without matching rounded timestamps across objects.
+ if (
+ offset >= offsetTable ||
+ !Number.isSafeInteger(cursor + 8) ||
+ cursor + 8 > offsetTable
+ )
+ throw new TypeError("binary plist date object is truncated");
+ if (marker !== 0x33)
+ throw new TypeError(
+ `binary plist date marker 0x${marker.toString(16)} is invalid`,
+ );
+ if (!recordedDateObjects.has(entry.object)) {
+ recordedDateObjects.add(entry.object);
+ datePayloadOffsets.push(cursor);
+ }
+ continue;
+ }
if (type !== 10 && type !== 13) continue;
const childCount = type === 13 ? size * 2 : size;
const refsEnd = cursor + childCount * referenceSize;
@@ -402,5 +431,9 @@ export const estimateBinaryPlistExpansion = (
}
pendingObjectCount += childCount;
}
- return { estimatedBytes: estimate, binaryPrototypeKeyObserved };
+ return {
+ estimatedBytes: estimate,
+ binaryPrototypeKeyObserved,
+ binaryDatePayloadOffsets: datePayloadOffsets,
+ };
};
diff --git a/src/artifacts/apple/KeyedArchiveReader.test.ts b/src/artifacts/apple/KeyedArchiveReader.test.ts
index 71f62c813..783dd7867 100644
--- a/src/artifacts/apple/KeyedArchiveReader.test.ts
+++ b/src/artifacts/apple/KeyedArchiveReader.test.ts
@@ -1,7 +1,17 @@
+import { createHash } from "node:crypto";
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
import { describe, expect, it } from "vitest";
import { build, buildBinary, type PlistValue } from "plist";
-import { decodeKeyedArchiveBytes } from "./KeyedArchiveReader.js";
+import { estimateBinaryPlistExpansion } from "./InterfaceBuilderDecodeBudget.js";
+import {
+ decodeKeyedArchiveBytes,
+ inspectBundleKeyedArchive,
+} from "./KeyedArchiveReader.js";
+import { unknownDateLimitation } from "../../domain/apple/plistValue.js";
import { deeplyNestedXmlPlist } from "../../../tests/fixtures/keyedArchiveXmlNesting.js";
+import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
const archive = {
$archiver: "NSKeyedArchiver",
@@ -375,6 +385,223 @@ describe("binary plist reference preflight", () => {
});
});
+/**
+ * Python `plistlib` binary NSKeyedArchiver with `$objects = ["$null", date]`
+ * and `$top.root` as UID 1. The date is marker `0x33` and float64 `0.1`
+ * seconds after the 2001 epoch (`2001-01-01T00:00:00.100Z`).
+ */
+const pythonBinaryDateControl = Buffer.from(
+ "62706c6973743030d4010203040506090c5924617263686976657258246f626a656374735424746f70582476657273696f6e5f100f4e534b657965644172636869766572a2070855246e756c6c333fb999999999999ad10a0b54726f6f74800112000186a008111b24293244474d56595e600000000000000101000000000000000d00000000000000000000000000000065",
+ "hex",
+);
+const canonicalDateMarker = Buffer.alloc(9);
+canonicalDateMarker[0] = 0x33;
+canonicalDateMarker.writeDoubleBE(0.1, 1);
+
+/** Copy the control and mutate its single canonical date marker. */
+const mutateCanonicalDate = (
+ mutate: (markerOffset: number, bytes: Buffer) => void,
+): Buffer => {
+ const bytes = Buffer.from(pythonBinaryDateControl);
+ const offset = bytes.indexOf(canonicalDateMarker);
+ if (offset < 0 || bytes.indexOf(canonicalDateMarker, offset + 1) !== -1)
+ throw new Error("expected one canonical binary date in the control");
+ mutate(offset, bytes);
+ return bytes;
+};
+
+const dateScalar = (iso8601: string | null) => ({
+ id: 1,
+ kind: "scalar" as const,
+ status: "observed" as const,
+ value: { $plist_type: "date", iso8601 },
+});
+
+describe("binary keyed archive dates", () => {
+ const selection = { offset: 0, limit: 10 };
+
+ it("keeps the canonical millisecond control as an observed timestamp", async () => {
+ const bytes = Buffer.from(pythonBinaryDateControl);
+ const graph = decodeKeyedArchiveBytes(bytes, selection);
+ expect(graph.objects[1]).toMatchObject(
+ dateScalar("2001-01-01T00:00:00.100Z"),
+ );
+ expect(graph.limitations).not.toContain(unknownDateLimitation(1));
+ expect(bytes).toEqual(pythonBinaryDateControl);
+ expect(createHash("sha256").update(bytes).digest("hex")).toBe(
+ "39f08db8341bd74220352dfd559485515cce1e6035e08f27a59ab8f856374a30",
+ );
+ const root = await createTestTempDirectory("rea-keyed-date-control-");
+ await writeFile(join(root, "archive.plist"), bytes);
+ const inspected = await inspectBundleKeyedArchive({
+ bundlePath: root,
+ targetSha256: createHash("sha256").update(bytes).digest("hex"),
+ parameters: { path: "archive.plist" },
+ });
+ expect(inspected.objects[1]).toMatchObject(
+ dateScalar("2001-01-01T00:00:00.100Z"),
+ );
+ expect(inspected.limitations).not.toContain(unknownDateLimitation(1));
+ expect(await readFile(join(root, "archive.plist"))).toEqual(bytes);
+ });
+
+ it.each(
+ [0x30, 0x31, 0x32, 0x34].map(
+ (marker) => [marker.toString(16), marker] as const,
+ ),
+ )(
+ "refuses reachable binary date marker 0x%s instead of projecting a timestamp",
+ async (_hex, marker) => {
+ const bytes = mutateCanonicalDate((offset, copy) => {
+ copy[offset] = marker;
+ });
+ const original = Buffer.from(bytes);
+ expect(() => decodeKeyedArchiveBytes(bytes, selection)).toThrow(
+ new TypeError(
+ `binary plist date marker 0x${marker.toString(16)} is invalid`,
+ ),
+ );
+ expect(bytes).toEqual(original);
+ if (marker === 0x30)
+ expect(createHash("sha256").update(bytes).digest("hex")).toBe(
+ "ac5696b866c312feb53c2e82edd8fea79dbeb572eb1b07e4291603faa41e8c0e",
+ );
+ const root = await createTestTempDirectory("rea-keyed-date-marker-");
+ const path = join(root, "archive.plist");
+ await writeFile(path, bytes);
+ await expect(
+ inspectBundleKeyedArchive({
+ bundlePath: root,
+ targetSha256: null,
+ parameters: { path: "archive.plist" },
+ }),
+ ).rejects.toMatchObject({
+ name: "ArtifactReaderFailure",
+ reason: "format",
+ message: `Cannot decode selected Foundation keyed archive: binary plist date marker 0x${marker.toString(16)} is invalid`,
+ });
+ expect(await readFile(path)).toEqual(bytes);
+ },
+ );
+
+ it("keeps a sub-millisecond instant unknown without changing the canonical sibling", async () => {
+ const submillisecond = mutateCanonicalDate((offset, copy) => {
+ copy.writeDoubleBE(0.1005, offset + 1);
+ });
+ const original = Buffer.from(submillisecond);
+ const graph = decodeKeyedArchiveBytes(submillisecond, selection);
+ expect(graph.objects[1]).toMatchObject(dateScalar(null));
+ expect(JSON.stringify(graph.objects[1]?.value)).not.toContain(
+ "2001-01-01T00:00:00.100Z",
+ );
+ expect(graph.limitations).toContain(unknownDateLimitation(1));
+ expect(graph.limitations.join("\n")).not.toContain(
+ "number metadata could not be completely observed",
+ );
+ expect(submillisecond).toEqual(original);
+ expect(createHash("sha256").update(submillisecond).digest("hex")).toBe(
+ "ab69ba6e8034c6f60b828ee323a5a3e81bae3e7657477e0ebfbfdb93d53ed2ce",
+ );
+ const root = await createTestTempDirectory("rea-keyed-date-subms-");
+ await writeFile(join(root, "archive.plist"), submillisecond);
+ const inspected = await inspectBundleKeyedArchive({
+ bundlePath: root,
+ targetSha256: createHash("sha256").update(submillisecond).digest("hex"),
+ parameters: { path: "archive.plist" },
+ });
+ expect(inspected.objects[1]).toMatchObject(dateScalar(null));
+ expect(inspected.limitations).toContain(unknownDateLimitation(1));
+ expect(await readFile(join(root, "archive.plist"))).toEqual(submillisecond);
+
+ const mixed = Buffer.from(
+ buildBinary({
+ $archiver: "NSKeyedArchiver",
+ $version: 100000,
+ $objects: [
+ "$null",
+ new Date("2001-01-01T00:00:00.100Z"),
+ new Date("2001-01-01T00:00:00.100Z"),
+ new Date("2001-01-01T00:00:00.100Z"),
+ ],
+ $top: { root: { UID: 1 } },
+ }),
+ );
+ const pattern = Buffer.from(canonicalDateMarker);
+ const offsets: number[] = [];
+ for (
+ let offset = mixed.indexOf(pattern);
+ offset !== -1;
+ offset = mixed.indexOf(pattern, offset + pattern.length)
+ )
+ offsets.push(offset);
+ expect(offsets).toHaveLength(3);
+ // 0.1004 and 0.1005 both round to the same millisecond as the control.
+ mixed.writeDoubleBE(0.1004, (offsets[1] ?? 0) + 1);
+ mixed.writeDoubleBE(0.1005, (offsets[2] ?? 0) + 1);
+ const mixedOriginal = Buffer.from(mixed);
+ const mixedGraph = decodeKeyedArchiveBytes(mixed, selection);
+ expect(mixedGraph.objects.slice(1).map(({ value }) => value)).toEqual([
+ { $plist_type: "date", iso8601: "2001-01-01T00:00:00.100Z" },
+ { $plist_type: "date", iso8601: null },
+ { $plist_type: "date", iso8601: null },
+ ]);
+ expect(mixedGraph.limitations).toContain(unknownDateLimitation(2));
+ expect(mixed).toEqual(mixedOriginal);
+ });
+});
+
+describe("binary plist date object region", () => {
+ it("refuses a binary date that extends past the object region", () => {
+ // Strict bounds end objects at the offset table. Four payload bytes
+ // remain before that table, short of the required eight.
+ const bytes = Buffer.alloc(8 + 5 + 1 + 32);
+ bytes.write("bplist00");
+ bytes[8] = 0x33;
+ const offsetTable = 13;
+ bytes[offsetTable] = 8;
+ const trailer = bytes.length - 32;
+ bytes[trailer + 6] = 1;
+ bytes[trailer + 7] = 1;
+ bytes.writeBigUInt64BE(1n, trailer + 8);
+ bytes.writeBigUInt64BE(0n, trailer + 16);
+ bytes.writeBigUInt64BE(BigInt(offsetTable), trailer + 24);
+ expect(() =>
+ estimateBinaryPlistExpansion(bytes, 1024 * 1024, { bounds: "strict" }),
+ ).toThrow(new TypeError("binary plist date object is truncated"));
+ // Decoder bounds extend other objects to the end of the file. The date
+ // payload still has to end at the offset table. The keyed-archive reader
+ // uses those bounds and must refuse the same payload.
+ expect(() =>
+ estimateBinaryPlistExpansion(bytes, 1024 * 1024, { bounds: "decoder" }),
+ ).toThrow(new TypeError("binary plist date object is truncated"));
+ expect(() =>
+ decodeKeyedArchiveBytes(bytes, { offset: 0, limit: 1 }),
+ ).toThrow(new TypeError("binary plist date object is truncated"));
+ });
+
+ it("refuses a decoder-bounds date whose marker sits past the offset table", () => {
+ // The one-byte offset table at byte 8 names an object at byte 9. That
+ // 0x33 marker and its eight payload bytes fit in the file, which decoder
+ // bounds would otherwise accept, but they are outside the object region.
+ const bytes = Buffer.alloc(64);
+ bytes.write("bplist00");
+ bytes[8] = 9;
+ bytes[9] = 0x33;
+ const trailer = bytes.length - 32;
+ bytes[trailer + 6] = 1;
+ bytes[trailer + 7] = 1;
+ bytes.writeBigUInt64BE(1n, trailer + 8);
+ bytes.writeBigUInt64BE(0n, trailer + 16);
+ bytes.writeBigUInt64BE(8n, trailer + 24);
+ expect(() =>
+ estimateBinaryPlistExpansion(bytes, 1024 * 1024, { bounds: "decoder" }),
+ ).toThrow(new TypeError("binary plist date object is truncated"));
+ expect(() =>
+ decodeKeyedArchiveBytes(bytes, { offset: 0, limit: 1 }),
+ ).toThrow(new TypeError("binary plist date object is truncated"));
+ });
+});
+
describe("XML plist nesting preflight", () => {
const selection = { offset: 0, limit: 1 };
diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts
index a15b8cfbe..3c5379f9e 100644
--- a/src/artifacts/apple/KeyedArchiveReader.ts
+++ b/src/artifacts/apple/KeyedArchiveReader.ts
@@ -79,7 +79,11 @@ export const decodeKeyedArchiveBytes = (
binaryExpansion !== undefined
? {
value: parseBinary(
- decodeBinaryPlistNumbers(bytes, binaryNumberMetadata!),
+ decodeBinaryPlistNumbers(
+ bytes,
+ binaryNumberMetadata!,
+ binaryExpansion.binaryDatePayloadOffsets,
+ ),
),
numberLiterals: binaryNumberMetadata!.literals,
omittedPrototypeKeys: binaryExpansion.binaryPrototypeKeyObserved
diff --git a/src/artifacts/apple/PlistNumberLiterals.test.ts b/src/artifacts/apple/PlistNumberLiterals.test.ts
index 103f28bed..3de13f51c 100644
--- a/src/artifacts/apple/PlistNumberLiterals.test.ts
+++ b/src/artifacts/apple/PlistNumberLiterals.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
+import type { PlistNumberLiterals } from "../../domain/apple/plistNumbers.js";
import {
decodeBinaryPlistNumbers,
scanBinaryPlistNumberLiterals,
@@ -37,4 +38,40 @@ describe("binary plist number rewriting", () => {
Buffer.from([0x14, ...Array<number>(16).fill(0xff)]),
);
});
+
+ it("applies wide-integer and date rewrites on one copy", () => {
+ const bytes = Buffer.alloc(34);
+ bytes[0] = 0x14;
+ bytes.writeBigUInt64BE(1n, 1);
+ bytes.writeBigUInt64BE(2n, 9);
+ bytes.writeDoubleBE(0.1, 18);
+ bytes.writeDoubleBE(0.1005, 26);
+ const original = Buffer.from(bytes);
+ const literals: PlistNumberLiterals = {
+ integers: new Map(),
+ reals: new Set(),
+ unsafeIntegerLiterals: 1,
+ incomplete: false,
+ };
+ const value = (1n << 64n) | 2n;
+ const decoded = decodeBinaryPlistNumbers(
+ bytes,
+ { literals, wideIntegers: [{ offset: 0, value }] },
+ [18, 26],
+ );
+ expect(decoded).not.toBe(bytes);
+ expect(bytes).toEqual(original);
+ expect(decoded[0]).toBe(0x23);
+ expect(decoded.readDoubleBE(1)).toBe(Number(value));
+ expect(decoded.readDoubleBE(18)).toBe(0.1);
+ expect(Number.isNaN(decoded.readDoubleBE(26))).toBe(true);
+ const representableOnly = {
+ literals: { ...literals, unsafeIntegerLiterals: 0 },
+ wideIntegers: [],
+ };
+ expect(decodeBinaryPlistNumbers(bytes, representableOnly, [18])).toBe(
+ bytes,
+ );
+ expect(decodeBinaryPlistNumbers(bytes, representableOnly, [])).toBe(bytes);
+ });
});
diff --git a/src/artifacts/apple/PlistNumberLiterals.ts b/src/artifacts/apple/PlistNumberLiterals.ts
index 12b55ecb9..33572a9fa 100644
--- a/src/artifacts/apple/PlistNumberLiterals.ts
+++ b/src/artifacts/apple/PlistNumberLiterals.ts
@@ -3,6 +3,7 @@ import {
type PlistNumberLiterals,
} from "../../domain/apple/plistNumbers.js";
import { hasBinaryPlistSignature } from "../../domain/apple/appleArchiveFormat.js";
+import { binaryPlistDateRepresentable } from "./BinaryPlistDate.js";
export interface BinaryPlistNumberMetadata {
readonly literals: PlistNumberLiterals;
@@ -139,12 +140,30 @@ export const scanBinaryPlistNumberLiterals = (
return { literals: output.result(), wideIntegers };
};
-/** Preserve 16-byte integers through plist@5's Number-only parser. */
+/**
+ * Preserve 16-byte integers and unrepresentable dates through plist@5.
+ * Both rewrites share one decoder-input copy. The caller's buffer stays
+ * unchanged, and it is returned when neither rewrite is needed.
+ * Date seconds are read from the original bytes before any rewrite.
+ */
export const decodeBinaryPlistNumbers = (
bytes: Buffer,
metadata: BinaryPlistNumberMetadata,
+ datePayloadOffsets: readonly number[] = [],
): Buffer => {
- if (metadata.wideIntegers.length === 0) return bytes;
+ const unrepresentableDates: number[] = [];
+ for (const offset of datePayloadOffsets) {
+ if (
+ !Number.isSafeInteger(offset) ||
+ offset < 0 ||
+ offset + 8 > bytes.length
+ )
+ throw new TypeError("binary plist date object is truncated");
+ if (!binaryPlistDateRepresentable(bytes.readDoubleBE(offset)))
+ unrepresentableDates.push(offset);
+ }
+ if (metadata.wideIntegers.length === 0 && unrepresentableDates.length === 0)
+ return bytes;
const compatible = Buffer.from(bytes);
for (const { offset, value } of metadata.wideIntegers) {
// Convert only the decoder's input copy to a double. Exact integer metadata
@@ -152,5 +171,7 @@ export const decodeBinaryPlistNumbers = (
compatible[offset] = 0x23;
compatible.writeDoubleBE(Number(value), offset + 1);
}
+ for (const offset of unrepresentableDates)
+ compatible.writeDoubleBE(Number.NaN, offset);
return compatible;
};