Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(apple): distinguish JVM resources and UIKit event connections

morlutoceb77f669772
diff --git a/src/artifacts/apple/MachoLoadCommandReader.test.ts b/src/artifacts/apple/MachoLoadCommandReader.test.ts
index 3dc6334d7..f360dfecd 100644
--- a/src/artifacts/apple/MachoLoadCommandReader.test.ts
+++ b/src/artifacts/apple/MachoLoadCommandReader.test.ts
@@ -460,12 +460,26 @@ describe("Mach-O load command reader inputs", () => {
"i386",
);
// A Java class file shares the FAT magic; version fields are not a slice count.
- const javaClasses = [javaClassFile(), javaClassFile(4000)];
- expect(javaClasses.map(({ length }) => length)).toEqual([57, 4060]);
+ const javaClasses = [
+ javaClassFile(),
+ javaClassFile(4000),
+ javaClassFile(4000, true),
+ ];
for (const javaClass of javaClasses) {
expect(hasMachoMagic(javaClass)).toBe(true);
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
}
+ const malformedFat = Buffer.alloc(28);
+ malformedFat.writeUInt32BE(0xcafebabe, 0);
+ malformedFat.writeUInt32BE(1, 4);
+ malformedFat.writeUInt32BE(0x0100000c, 8);
+ malformedFat.writeUInt32BE(4096, 16);
+ malformedFat.writeUInt32BE(32, 20);
+ malformedFat.writeUInt32BE(12, 24);
+ expect(await read(malformedFat)).toMatchObject({
+ status: "malformed",
+ reason: expect.stringContaining("slice range extends beyond the file"),
+ });
expect(await read(new TextEncoder().encode("#!/bin/sh\n"))).toEqual({
status: "not-mach-o",
});
@@ -477,6 +491,35 @@ describe("Mach-O load command reader inputs", () => {
await read(Uint8Array.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0x00])),
).toEqual({ status: "malformed", reason: "Mach-O header is truncated" });
});
+
+ it("keeps oversized CAFEBABE identity unknown when class payload is sparse", async () => {
+ const classPrefix = Buffer.from(javaClassFile(4000, true));
+ const payloadBytes = MAX_LOAD_COMMAND_BYTES + 1;
+ const attributeHeader = Buffer.alloc(6);
+ attributeHeader.writeUInt16BE(5, 0);
+ attributeHeader.writeUInt32BE(payloadBytes, 2);
+ classPrefix.writeUInt16BE(1, classPrefix.length - 2);
+ const prefix = Buffer.concat([classPrefix, attributeHeader]);
+ const size = prefix.length + payloadBytes;
+ const sparseReadAt = async (offset: number, length: number) => {
+ const result = Buffer.alloc(Math.min(length, size - offset));
+ if (offset < prefix.length)
+ prefix.copy(
+ result,
+ 0,
+ offset,
+ Math.min(prefix.length, offset + length),
+ );
+ return result;
+ };
+
+ expect(await readMachoImage(sparseReadAt, size)).toEqual({
+ status: "unsupported",
+ reason: expect.stringContaining(
+ "class identity scan exceeds the 16 MiB limit",
+ ),
+ });
+ });
});
describe("Mach-O load command reader failures", () => {
diff --git a/src/artifacts/apple/MachoLoadCommandReader.ts b/src/artifacts/apple/MachoLoadCommandReader.ts
index 2c086ec0b..84267e7ed 100644
--- a/src/artifacts/apple/MachoLoadCommandReader.ts
+++ b/src/artifacts/apple/MachoLoadCommandReader.ts
@@ -141,7 +141,14 @@ export const readMachoImage = async (
: { status: "not-mach-o" };
const view = viewOf(head);
const magic = view.getUint32(0, false);
- let header = readFatContainerHeader(head, size);
+ let header: ReturnType<typeof readFatContainerHeader>;
+ if (magic === FAT_MAGIC && size <= MAX_LOAD_COMMAND_BYTES) {
+ const complete = await readAt(0, size);
+ header =
+ complete.byteLength === size
+ ? readFatContainerHeader(complete, size)
+ : readFatContainerHeader(head, size);
+ } else header = readFatContainerHeader(head, size);
if (header.state !== "not-fat") {
if (header.state === "needs-data") {
header = readFatContainerHeader(
@@ -169,8 +176,17 @@ export const readMachoImage = async (
);
}
if (identity.state === "not-mach-o") return { status: "not-mach-o" };
- if (identity.state === "malformed")
+ if (identity.state === "malformed") {
+ // A large CAFEBABE input whose bounded prefix resembles an invalid
+ // known-CPU FAT table remains unknown until its JVM identity can be
+ // checked; do not turn the resource limit into a malformed claim.
+ if (magic === FAT_MAGIC && size > MAX_LOAD_COMMAND_BYTES)
+ throw new MachoFormatIssue(
+ "unsupported",
+ "FAT/JVM identity is unresolved because the class identity scan exceeds the 16 MiB limit",
+ );
throw new MachoFormatIssue(identity.category, identity.reason);
+ }
if (identity.state === "needs-slice-header")
return { status: "not-mach-o" };
return {
diff --git a/src/domain/apple/appleApplication.test.ts b/src/domain/apple/appleApplication.test.ts
index 23eb46b46..f4610dc3c 100644
--- a/src/domain/apple/appleApplication.test.ts
+++ b/src/domain/apple/appleApplication.test.ts
@@ -138,7 +138,7 @@ const inventoryEvidence = (
occurrences: sortedOccurrences,
edges: [],
provenance: [],
- coverage_status: "complete",
+ coverage: { scope: "container-entries", status: "complete" },
limitations: [],
}),
},
diff --git a/src/domain/apple/interfaceBuilderGraph.test.ts b/src/domain/apple/interfaceBuilderGraph.test.ts
index e3702fbb1..84a8ea493 100644
--- a/src/domain/apple/interfaceBuilderGraph.test.ts
+++ b/src/domain/apple/interfaceBuilderGraph.test.ts
@@ -590,9 +590,11 @@ describe("AppKit keyed archive connectors", () => {
});
describe("keyed archive unresolved connectors", () => {
- // A rooted UIKit archive whose only connector is UID 3, with UID 1 as the
- // owner, UID 2 as the destination and UID 7 as the "view" label.
- const rootedOutletArchive = (connection: Record<string, unknown>) => ({
+ const rootedOutletArchive = (
+ connection: Record<string, unknown>,
+ connectionClass = "UIRuntimeOutletConnection",
+ label = "view",
+ ) => ({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
@@ -606,14 +608,10 @@ describe("keyed archive unresolved connectors", () => {
},
{ $classname: "UIView", $classes: ["UIView", "UIResponder", "NSObject"] },
{
- $classname: "UIRuntimeOutletConnection",
- $classes: [
- "UIRuntimeOutletConnection",
- "UIRuntimeConnection",
- "NSObject",
- ],
+ $classname: connectionClass,
+ $classes: [connectionClass, "UIRuntimeConnection", "NSObject"],
},
- "view",
+ label,
{
$class: { CF$UID: 11 },
"NS.objects": [{ CF$UID: 1 }, { CF$UID: 2 }, { CF$UID: 3 }],
@@ -664,6 +662,43 @@ describe("keyed archive unresolved connectors", () => {
}),
);
});
+ it("projects keyed UIKit event connections as actions and retains the mask", () => {
+ const raw = rootedOutletArchive(
+ {
+ UISource: { CF$UID: 1 },
+ UIDestination: { CF$UID: 2 },
+ UILabel: { CF$UID: 7 },
+ UIEventMask: 64,
+ },
+ "UIRuntimeEventConnection",
+ "tapped:",
+ );
+ expect(parseInterfaceBuilderRecords(raw).connections[0]).toMatchObject({
+ kind: "action",
+ source_id: "1",
+ destination_id: "2",
+ label: "tapped:",
+ attributes: { UIEventMask: 64 },
+ });
+ const analysis = project(raw);
+ expect(analysis.graph.nodes).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ kind: "action", name: "tapped:" }),
+ expect.objectContaining({ kind: "objc_selector", name: "tapped:" }),
+ ]),
+ );
+ expect(analysis.graph.edges).toContainEqual(
+ expect.objectContaining({ relation: "target_action" }),
+ );
+ expect(analysis.graph.coverage).toContainEqual(
+ expect.objectContaining({
+ facet: "connections:Main.nib",
+ status: "complete",
+ examined: 1,
+ omitted: 0,
+ }),
+ );
+ });
it("reports a recognized connector with no resolvable owner as unresolved", () => {
const raw = rootedOutletArchive({
@@ -686,6 +721,27 @@ describe("keyed archive unresolved connectors", () => {
}),
);
expect(analysis.graph.truncated).toBe(true);
+
+ const eventWithoutSource = rootedOutletArchive(
+ {
+ UIDestination: { CF$UID: 2 },
+ UILabel: { CF$UID: 7 },
+ UIEventMask: 64,
+ },
+ "UIRuntimeEventConnection",
+ "tapped:",
+ );
+ expect(
+ parseInterfaceBuilderRecords(eventWithoutSource).unresolvedConnections,
+ ).toBe(1);
+ expect(project(eventWithoutSource).graph.coverage).toContainEqual(
+ expect.objectContaining({
+ facet: "connections:Main.nib",
+ status: "partial",
+ reason: "connection_unresolved",
+ omitted: 1,
+ }),
+ );
});
});
diff --git a/src/domain/apple/interfaceBuilderKeyedArchive.ts b/src/domain/apple/interfaceBuilderKeyedArchive.ts
index 57ebda803..3c0e97749 100644
--- a/src/domain/apple/interfaceBuilderKeyedArchive.ts
+++ b/src/domain/apple/interfaceBuilderKeyedArchive.ts
@@ -523,7 +523,8 @@ const classifyConnection = (
): InterfaceBuilderConnection["kind"] => {
const value = type.toLowerCase();
if (value.includes("outlet")) return "outlet";
- if (value.includes("action")) return "action";
+ if (value.includes("action") || value.includes("eventconnection"))
+ return "action";
if (value.includes("segue")) return "segue";
return "other";
};
diff --git a/src/domain/apple/jvmClassFile.ts b/src/domain/apple/jvmClassFile.ts
new file mode 100644
index 000000000..adcc8f942
--- /dev/null
+++ b/src/domain/apple/jvmClassFile.ts
@@ -0,0 +1,261 @@
+/** Class-file identity used to disambiguate JVM CAFEBABE from Mach-O FAT. */
+class ClassFileCursor {
+ private offset = 0;
+ private readonly view: DataView;
+
+ constructor(private readonly bytes: Uint8Array) {
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ }
+
+ get atEnd(): boolean {
+ return this.offset === this.bytes.byteLength;
+ }
+
+ u1(): number | null {
+ if (!this.has(1)) return null;
+ return this.bytes[this.offset++]!;
+ }
+
+ u2(): number | null {
+ if (!this.has(2)) return null;
+ const value = this.view.getUint16(this.offset, false);
+ this.offset += 2;
+ return value;
+ }
+
+ u4(): number | null {
+ if (!this.has(4)) return null;
+ const value = this.view.getUint32(this.offset, false);
+ this.offset += 4;
+ return value;
+ }
+
+ skip(length: number): boolean {
+ if (!Number.isSafeInteger(length) || length < 0 || !this.has(length))
+ return false;
+ this.offset += length;
+ return true;
+ }
+
+ private has(length: number): boolean {
+ return this.offset <= this.bytes.byteLength - length;
+ }
+}
+
+interface ConstantPool {
+ readonly tags: (number | null)[];
+ readonly first: (number | null)[];
+ readonly second: (number | null)[];
+}
+
+const readConstantPool = (
+ cursor: ClassFileCursor,
+ count: number,
+): ConstantPool | null => {
+ const pool: ConstantPool = {
+ tags: Array.from({ length: count }, () => null),
+ first: Array.from({ length: count }, () => null),
+ second: Array.from({ length: count }, () => null),
+ };
+ for (let index = 1; index < count; index += 1) {
+ const tag = cursor.u1();
+ if (tag === null) return null;
+ if (!readConstant(cursor, tag, index, pool)) return null;
+ if (tag === 5 || tag === 6) index += 1;
+ }
+ return pool;
+};
+
+const readConstant = (
+ cursor: ClassFileCursor,
+ tag: number,
+ index: number,
+ pool: ConstantPool,
+): boolean => {
+ switch (tag) {
+ case 1: {
+ const length = cursor.u2();
+ if (length === null || !cursor.skip(length)) return false;
+ break;
+ }
+ case 3:
+ case 4:
+ if (cursor.u4() === null) return false;
+ break;
+ case 5:
+ case 6:
+ if (index + 1 >= pool.tags.length || !cursor.skip(8)) return false;
+ break;
+ case 7:
+ case 8:
+ case 16:
+ case 19:
+ case 20:
+ pool.first[index] = cursor.u2();
+ if (pool.first[index] === null) return false;
+ break;
+ case 9:
+ case 10:
+ case 11:
+ case 12:
+ case 17:
+ case 18:
+ pool.first[index] = cursor.u2();
+ pool.second[index] = cursor.u2();
+ if (pool.first[index] === null || pool.second[index] === null)
+ return false;
+ break;
+ case 15:
+ pool.first[index] = cursor.u1();
+ pool.second[index] = cursor.u2();
+ if (pool.first[index] === null || pool.second[index] === null)
+ return false;
+ break;
+ default:
+ return false;
+ }
+ pool.tags[index] = tag;
+ return true;
+};
+
+const poolHasTag = (
+ pool: ConstantPool,
+ index: number,
+ ...tags: number[]
+): boolean =>
+ Number.isInteger(index) && index > 0 && tags.includes(pool.tags[index] ?? -1);
+
+const hasValidPoolReferences = (pool: ConstantPool, major: number): boolean => {
+ for (let index = 1; index < pool.tags.length; index += 1) {
+ const tag = pool.tags[index] ?? null;
+ const first = pool.first[index] ?? null;
+ const second = pool.second[index] ?? null;
+ if ([7, 8, 16, 19, 20].includes(tag ?? -1)) {
+ if (first === null || !poolHasTag(pool, first, 1)) return false;
+ if (
+ (tag === 16 && major < 51) ||
+ ((tag === 19 || tag === 20) && major < 53)
+ )
+ return false;
+ } else if ([9, 10, 11].includes(tag ?? -1)) {
+ if (
+ first === null ||
+ second === null ||
+ !poolHasTag(pool, first, 7) ||
+ !poolHasTag(pool, second, 12)
+ )
+ return false;
+ } else if (tag === 12) {
+ if (
+ first === null ||
+ second === null ||
+ !poolHasTag(pool, first, 1) ||
+ !poolHasTag(pool, second, 1)
+ )
+ return false;
+ } else if (tag === 15 && !validMethodHandle(pool, first, second, major)) {
+ return false;
+ } else if (tag === 17 || tag === 18) {
+ if (
+ second === null ||
+ !poolHasTag(pool, second, 12) ||
+ major < (tag === 17 ? 55 : 51)
+ )
+ return false;
+ }
+ }
+ return true;
+};
+
+const validMethodHandle = (
+ pool: ConstantPool,
+ kind: number | null,
+ reference: number | null,
+ major: number,
+): boolean => {
+ if (kind === null || reference === null || kind < 1 || kind > 9 || major < 51)
+ return false;
+ if (kind <= 4) return poolHasTag(pool, reference, 9);
+ if (kind === 5 || kind === 8) return poolHasTag(pool, reference, 10);
+ if (kind === 6 || kind === 7)
+ return poolHasTag(pool, reference, ...(major >= 52 ? [10, 11] : [10]));
+ return poolHasTag(pool, reference, 11);
+};
+
+const readAttributes = (
+ cursor: ClassFileCursor,
+ pool: ConstantPool,
+ count: number,
+): boolean => {
+ for (let index = 0; index < count; index += 1) {
+ const name = cursor.u2();
+ const length = cursor.u4();
+ if (
+ name === null ||
+ !poolHasTag(pool, name, 1) ||
+ length === null ||
+ !cursor.skip(length)
+ )
+ return false;
+ }
+ return true;
+};
+
+const readMembers = (cursor: ClassFileCursor, pool: ConstantPool): boolean => {
+ const count = cursor.u2();
+ if (count === null) return false;
+ for (let index = 0; index < count; index += 1) {
+ if (cursor.u2() === null) return false;
+ const name = cursor.u2();
+ const descriptor = cursor.u2();
+ const attributes = cursor.u2();
+ if (
+ name === null ||
+ descriptor === null ||
+ !poolHasTag(pool, name, 1) ||
+ !poolHasTag(pool, descriptor, 1) ||
+ attributes === null ||
+ !readAttributes(cursor, pool, attributes)
+ )
+ return false;
+ }
+ return true;
+};
+
+/** Validate class-file framing and constant-pool references before FAT parsing. */
+export const isJvmClassFile = (bytes: Uint8Array): boolean => {
+ const cursor = new ClassFileCursor(bytes);
+ if (cursor.u4() !== 0xcafebabe) return false;
+ const minor = cursor.u2();
+ const major = cursor.u2();
+ const poolCount = cursor.u2();
+ if (
+ minor === null ||
+ major === null ||
+ major < 45 ||
+ poolCount === null ||
+ poolCount === 0
+ )
+ return false;
+ const pool = readConstantPool(cursor, poolCount);
+ if (pool === null || !hasValidPoolReferences(pool, major)) return false;
+ if (cursor.u2() === null) return false;
+ const thisClass = cursor.u2();
+ const superClass = cursor.u2();
+ if (
+ thisClass === null ||
+ !poolHasTag(pool, thisClass, 7) ||
+ superClass === null ||
+ (superClass !== 0 && !poolHasTag(pool, superClass, 7))
+ )
+ return false;
+ const interfaces = cursor.u2();
+ if (interfaces === null || !cursor.skip(interfaces * 2)) return false;
+ if (!readMembers(cursor, pool) || !readMembers(cursor, pool)) return false;
+ const attributes = cursor.u2();
+ return (
+ attributes !== null &&
+ readAttributes(cursor, pool, attributes) &&
+ cursor.atEnd
+ );
+};
diff --git a/src/domain/apple/machoContainer.ts b/src/domain/apple/machoContainer.ts
index c23cf7f64..2102d6c8e 100644
--- a/src/domain/apple/machoContainer.ts
+++ b/src/domain/apple/machoContainer.ts
@@ -1,3 +1,5 @@
+import { isJvmClassFile } from "./jvmClassFile.js";
+
/** Physical facts for one entry in a Mach-O FAT architecture table. */
export interface FatSliceDeclaration {
readonly index: number;
@@ -68,6 +70,8 @@ export const readFatContainerHeader = (
state: "malformed",
reason: "FAT file size is invalid or contradicts retained bytes",
};
+ if (bytes.byteLength === fileSize && isJvmClassFile(bytes))
+ return { state: "not-fat" };
if (bytes.byteLength < 8) {
return fileSize < 8
? { state: "malformed", reason: "FAT header is truncated" }
@@ -257,3 +261,5 @@ export const validateFatSliceIdentity = (
const safeNumber = (value: bigint): number | null =>
value > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(value);
+
+export { isJvmClassFile } from "./jvmClassFile.js";
diff --git a/tests/boundary/filesystem/appleApplication.test.ts b/tests/boundary/filesystem/appleApplication.test.ts
index 31c395b55..b067342d3 100644
--- a/tests/boundary/filesystem/appleApplication.test.ts
+++ b/tests/boundary/filesystem/appleApplication.test.ts
@@ -93,7 +93,7 @@ describe("Apple application projection", () => {
await runProviderAnalysis(path, "inventory_artifact", {}),
);
expect(inventory.normalized_result).toMatchObject({
- coverage_status: "complete",
+ coverage: { scope: "container-entries", status: "complete" },
});
const result = projectAppleApplicationEvidence({
inventory_evidence: [inventory],