diff --git a/docs/reverse-engineering-tools.md b/docs/reverse-engineering-tools.md index f2a880afa2..8cbfd51649 100644 --- a/docs/reverse-engineering-tools.md +++ b/docs/reverse-engineering-tools.md @@ -361,6 +361,9 @@ when the plugin did not declare them, for example when no reply was read, the reply was malformed, or an older plugin omitted them. A null generation means the document may have changed; list sessions again before choosing an `expected_generation`. Evidence carries a limitation for each unknown field. +With `json: true`, Cutter command output retains integer literals outside +JavaScript's safe integer range as decimal strings, so 64-bit addresses and +offsets keep their original digits. Each bridge request waits 25000 ms. The Cutter hello frame still must arrive within 1 second. The authenticated command frame is read with one second per mebibyte of `REA_BRIDGE_MAX_REQUEST_BYTES`, and that read never waits longer diff --git a/src/cutter/CutterBridgeClient.ts b/src/cutter/CutterBridgeClient.ts index 9c02606b76..83deda9523 100644 --- a/src/cutter/CutterBridgeClient.ts +++ b/src/cutter/CutterBridgeClient.ts @@ -53,6 +53,7 @@ import { cutterBridgeSourceRecovery, } from "./CutterBridgeSource.js"; import { CutterBridgeResponseFrames } from "./cutterAuthenticatedResponse.js"; +import { parseCutterCommandResponse } from "./cutterCommandResponse.js"; import { requireWindowsNativeAuthority } from "../windows/WindowsNativeLoader.js"; import { readBoundedFileBytes } from "../process/BoundedFileBytes.js"; import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js"; @@ -553,8 +554,11 @@ export class CutterBridgeClient { descriptor, commandRequest, input.signal, - (ordinal) => { - completionToken = ordinal; + { + json: input.json, + onAuthenticated: (ordinal) => { + completionToken = ordinal; + }, }, ); } catch (cause) { @@ -1136,7 +1140,10 @@ export class CutterBridgeClient { descriptor: z.infer, requestBytes: AuthenticatedRequestBytes, signal?: AbortSignal, - onAuthenticated?: (connectionOrdinal: string) => void, + command?: { + readonly json: boolean; + readonly onAuthenticated: (connectionOrdinal: string) => void; + }, ): Promise { return new Promise((resolve, reject) => { const connection = createConnection({ @@ -1203,7 +1210,7 @@ export class CutterBridgeClient { frame.value, ); connectionOrdinal = serverNonce.slice(0, 16); - onAuthenticated?.(connectionOrdinal); + command?.onAuthenticated(connectionOrdinal); const proof = cutterBridgeMac(descriptor.token, [ `rea-cutter-client-v2:${descriptor.session_id}:${clientNonce}:${serverNonce}:`, requestBytes, @@ -1222,7 +1229,9 @@ export class CutterBridgeClient { ]); if (!timingSafeEqual(expected, Buffer.from(frame.proof, "hex"))) throw new Error("response proof failed"); - const response: unknown = JSON.parse(frame.response); + const response: unknown = command?.json + ? parseCutterCommandResponse(frame.response) + : JSON.parse(frame.response); finish(() => resolve(response)); return false; }); diff --git a/src/cutter/CutterBridgeService.ts b/src/cutter/CutterBridgeService.ts index f3a6df505e..09a00e4aea 100644 --- a/src/cutter/CutterBridgeService.ts +++ b/src/cutter/CutterBridgeService.ts @@ -199,6 +199,11 @@ export class CutterBridgeService { "Document identity is partial: the bridge uses a plugin instance UUID and observed generation; a same-path tab switch or reload may not be distinguishable.", "Cutter command effects depend on the Rizin command and active plugins.", "The local IPC protocol is implemented by REA and is not an upstream Cutter API.", + ...(input.json + ? [ + "JSON integer literals outside JavaScript's safe integer range are retained as decimal strings.", + ] + : []), ...(output.executionState === "unknown" ? [ "Command completion or its output could not be confirmed; do not retry automatically because the command may have produced partial or persistent effects.", diff --git a/src/cutter/cutterCommandResponse.ts b/src/cutter/cutterCommandResponse.ts new file mode 100644 index 0000000000..b534ecb224 --- /dev/null +++ b/src/cutter/cutterCommandResponse.ts @@ -0,0 +1,75 @@ +import { visit } from "jsonc-parser"; +import { isInteger } from "lossless-json"; + +type Parent = { + readonly value: unknown[] | Record; + readonly commandOutput: boolean; +}; + +/** Decode authenticated JSON-mode command replies with exact output integers. */ +export const parseCutterCommandResponse = (text: string): unknown => { + // Integers outside the safe range need at least 16 digits. Keep ordinary + // replies on the native path and avoid a source reviver's per-node storage + // when a large output does contain an unsafe integer. + if (!/\d{16}/u.test(text)) return JSON.parse(text) as unknown; + + const parents: Parent[] = []; + let result: unknown; + let key = ""; + const inCommandOutput = (): boolean => + parents.at(-1)?.commandOutput === true || + (parents.length === 1 && key === "output"); + const append = (value: unknown): void => { + const parent = parents.at(-1)?.value; + if (parent === undefined) result = value; + else if (Array.isArray(parent)) parent.push(value); + else if (key === "__proto__") + Object.defineProperty(parent, key, { + value, + writable: true, + enumerable: true, + configurable: true, + }); + else parent[key] = value; + }; + const begin = (value: Parent["value"]): void => { + const commandOutput = inCommandOutput(); + append(value); + parents.push({ value, commandOutput }); + }; + visit( + text, + { + onObjectBegin: () => begin({}), + onObjectProperty: (name) => { + key = name; + }, + onObjectEnd: () => { + parents.pop(); + }, + onArrayBegin: () => begin([]), + onArrayEnd: () => { + parents.pop(); + }, + onLiteralValue: (value: unknown, offset, length) => { + if ( + typeof value === "number" && + !Number.isSafeInteger(value) && + inCommandOutput() + ) { + const source = text.slice(offset, offset + length); + if (isInteger(source)) { + append(source); + return; + } + } + append(value); + }, + onError: () => { + throw new SyntaxError("Invalid Cutter command response JSON"); + }, + }, + { disallowComments: true }, + ); + return result; +}; diff --git a/src/gdb/GdbMiRecord.ts b/src/gdb/GdbMiRecord.ts index 1395ecffc6..b7f6a94a9f 100644 --- a/src/gdb/GdbMiRecord.ts +++ b/src/gdb/GdbMiRecord.ts @@ -55,6 +55,7 @@ const MAX_GDB_MI_NESTED_VALUE_FRAMES = 256; const SIMPLE_ESCAPES: Readonly> = { a: 7, b: 8, + e: 0x1b, f: 12, n: 10, r: 13, diff --git a/tests/boundary/providers/CutterBridgeClient.test.ts b/tests/boundary/providers/CutterBridgeClient.test.ts index 2f735ce581..410f675e25 100644 --- a/tests/boundary/providers/CutterBridgeClient.test.ts +++ b/tests/boundary/providers/CutterBridgeClient.test.ts @@ -1027,7 +1027,10 @@ describe("CutterBridgeClient: scenario group 5", () => { respond({ ok: true, acknowledged: true }); return; } - if (malformed) respond("{", { raw: true }); + if (malformed) + respond('{"ok":true,"output":{18446744071578845304:0}}', { + raw: true, + }); else respond( { ok: true, execution_state: "complete", output: "split 雪 ☃️" }, @@ -1060,7 +1063,7 @@ describe("CutterBridgeClient: scenario group 5", () => { sessionId, expectedGeneration: 0, command: "pd 1", - json: false, + json: true, }), ).resolves.toMatchObject({ executionState: "unknown", @@ -1263,6 +1266,64 @@ describe("CutterBridgeClient: scenario group 7", () => { directory = undefined; }); + it("retains large JSON integer digits in authenticated command evidence", async () => { + directory = await mkdtemp(join(tmpdir(), "rea-cutter-json-output-")); + const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; + const token = "synthetic-cutter-bridge-token-for-test"; + server = authenticatedServer(token, sessionId, (request, respond) => { + if (request.kind === "ack") { + respond({ ok: true, acknowledged: true }); + return; + } + expect(request.json).toBe(true); + respond( + '{"ok":true,"execution_state":"complete","document_generation":2,"output":' + + '[{"offset":18446744071578845304,"maxbound":18446744071578845312,' + + '"size":8,"nested":[-9223372036854775808,9007199254740991,1.5,"18446744071578845304"],' + + '"__proto__":18446744071578845312}]}', + { raw: true }, + ); + }); + await writeDescriptor(directory, sessionId, await listen(server), token); + const service = new CutterBridgeService( + createClient({ REA_CUTTER_BRIDGE_DIR: directory }), + ); + const result = await service.execute({ + session_id: sessionId, + expected_generation: 0, + command: "aflj", + json: true, + }); + const output = [ + { + offset: "18446744071578845304", + maxbound: "18446744071578845312", + size: 8, + ["__proto__"]: "18446744071578845312", + nested: [ + "-9223372036854775808", + 9007199254740991, + 1.5, + "18446744071578845304", + ], + }, + ]; + expect(result).toMatchObject({ + ok: true, + value: { + normalized_result: { + output, + execution_state: "complete", + document_generation: 2, + }, + raw_result: output, + limitations: expect.arrayContaining([ + expect.stringContaining("decimal strings"), + ]), + }, + }); + }); + it("handles an abort detected immediately after listener registration", async () => { directory = await mkdtemp(join(tmpdir(), "rea-cutter-abort-race-")); const sessionId = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a"; diff --git a/tests/boundary/providers/GdbMiRecord.test.ts b/tests/boundary/providers/GdbMiRecord.test.ts index eab26acddf..0879b429e7 100644 --- a/tests/boundary/providers/GdbMiRecord.test.ts +++ b/tests/boundary/providers/GdbMiRecord.test.ts @@ -84,11 +84,11 @@ it("bounds value nesting", () => { it("decodes C-string escapes to bytes and text only when UTF-8", () => { const parsed = parseGdbMiResultRecord( - '1^done,a="\\x41\\101\\n\\\\\\"",b="\\xff",c="\\x1ff"', + '1^done,a="\\x41\\101\\n\\e\\\\\\"",b="\\xff",c="\\x1ff"', ); if (!parsed.ok) throw new Error(parsed.error.reason); const [a, b, c] = parsed.value.results; - expect(gdbMiConstText(a!.value)).toBe('AA\n\\"'); + expect(gdbMiConstText(a!.value)).toBe('AA\n\x1b\\"'); expect(gdbMiConstText(b!.value)).toBeUndefined(); expect(c!.value).toEqual({ kind: "const", bytes: Uint8Array.of(0xff) }); });