feat: add Frida instrumentation support (#1359)

* feat: add Frida instrumentation support

* fix: resolve Frida CI checks

* test: cover Frida contract validation branches

* docs: link Frida instrumentation guide

* fix(frida): handle cancellation cleanup safely

* fix(frida): address PR review findings

* fix(frida): preserve resume and message observations

* fix(ci): use canonical registry for rolldown

* fix(frida): declare foreign code effects

* fix(frida): retain failed startup resources for cleanup retries

Keep failed startup session and spawn handles owned until detach, resume,
and remote lease cleanup complete. Serialize retries and release each
remote reference once. Await CLI provider cleanup while preserving the
primary failure and any completed observations.

Add regressions for retained startup resources, concurrent cleanup,
shared remote leases, and CLI cleanup outcomes.

Validation: 41 focused tests pass on the PR head and its latest-main
integration; serial static and docs checks pass. Real Linux Frida 17.23.2
workflows and the native spawn/controlled-failure cleanup probe pass.

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)

---------

Co-authored-by: N0zoM1z0 <1705004398@qq.com>
This commit is contained in:
Daniel Gonçalves Araujo
2026-10-12 22:01:58 +08:00
committed by GitHub
co-authored by N0zoM1z0
parent 0b7145361e
commit 4a4ae9b2b9
34 changed files with 5845 additions and 148 deletions
+21
View File
@@ -0,0 +1,21 @@
/** Accept a Frida host address, optionally with a TCP port, without URL credentials or paths. */
export const isValidFridaRemoteAddress = (address: string): boolean => {
if (address.length === 0 || address.length > 2048) return false;
if (/[?@#\s\u0000-\u001f\u007f/]/u.test(address)) return false;
if (address.endsWith(":")) return false;
try {
const parsed = new URL(`tcp://${address}`);
const port = parsed.port === "" ? undefined : Number(parsed.port);
return (
parsed.hostname.length > 0 &&
(port === undefined || (port > 0 && port <= 65_535)) &&
parsed.username.length === 0 &&
parsed.password.length === 0 &&
(parsed.pathname === "" || parsed.pathname === "/") &&
parsed.search.length === 0 &&
parsed.hash.length === 0
);
} catch {
return false;
}
};
+170
View File
@@ -0,0 +1,170 @@
import { describe, expect, it } from "vitest";
import { TOOL_CONTRACTS } from "./toolContracts.js";
import { FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION } from "./fridaToolContracts.js";
import { isValidFridaRemoteAddress } from "./fridaRemoteAddress.js";
const contract = (name: string) => {
const found = TOOL_CONTRACTS.find((candidate) => candidate.name === name);
if (found === undefined) throw new Error(`Missing contract ${name}`);
return found.inputSchema;
};
describe("Frida tool contracts", () => {
it("documents Frida Core keepalive intervals in seconds", () => {
expect(FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION).toBe(
"Remote keepalive interval in seconds",
);
});
it("rejects incomplete or conflicting mode and source selectors", () => {
const start = contract("start_frida_session");
const load = contract("load_frida_script");
const instrument = contract("instrument_with_frida");
const processList = contract("list_frida_processes");
expect(start.safeParse({ mode: "attach", pid: 7 }).success).toBe(true);
expect(start.safeParse({ mode: "spawn", program: "app" }).success).toBe(
true,
);
for (const input of [
{ mode: "attach" },
{ mode: "attach", pid: 7, program: "app" },
{ mode: "spawn" },
{ mode: "spawn", program: "app", pid: 7 },
{
mode: "attach",
pid: 7,
device_id: "local",
remote: { address: "host" },
},
])
expect(start.safeParse(input).success).toBe(false);
expect(
load.safeParse({
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "inline",
source: "",
}).success,
).toBe(true);
expect(
load.safeParse({
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "file",
path: "script.js",
}).success,
).toBe(true);
for (const input of [
{
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "inline",
},
{
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "inline",
source: "",
path: "script.js",
},
{
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "file",
},
])
expect(load.safeParse(input).success).toBe(false);
expect(
instrument.safeParse({
mode: "attach",
pid: 7,
source_kind: "inline",
source: "",
}).success,
).toBe(true);
expect(
instrument.safeParse({
mode: "spawn",
program: "app",
source_kind: "file",
path: "script.js",
}).success,
).toBe(true);
for (const input of [
{
mode: "attach",
pid: 7,
source_kind: "file",
path: "script.js",
source: "",
},
{ mode: "spawn", program: "app", source_kind: "inline" },
{
mode: "spawn",
program: "app",
pid: 7,
source_kind: "inline",
source: "",
},
{
mode: "attach",
source_kind: "inline",
source: "",
device_id: "local",
remote: { address: "host" },
},
])
expect(instrument.safeParse(input).success).toBe(false);
expect(processList.safeParse({ device_id: "local" }).success).toBe(true);
expect(processList.safeParse({}).success).toBe(false);
expect(
processList.safeParse({ device_id: "local", remote: { address: "host" } })
.success,
).toBe(false);
});
it("publishes the Frida device, process, and session operations", () => {
expect(TOOL_CONTRACTS.map(({ name }) => name)).toEqual(
expect.arrayContaining([
"list_frida_devices",
"list_frida_processes",
"start_frida_session",
"load_frida_script",
"resume_frida_session",
"unload_frida_script",
"frida_session_status",
"close_frida_session",
"instrument_with_frida",
]),
);
});
it("declares target authority for every operation that changes instrumentation", () => {
for (const name of [
"start_frida_session",
"load_frida_script",
"resume_frida_session",
"unload_frida_script",
"close_frida_session",
"instrument_with_frida",
] as const) {
const contract = TOOL_CONTRACTS.find(
(candidate) => candidate.name === name,
);
expect(contract?.effects.mutatesTarget).toBe(true);
expect(contract?.effects.idempotent).toBe(false);
}
});
it("accepts Frida host addresses and rejects URL-like or malformed endpoints", () => {
expect(isValidFridaRemoteAddress("127.0.0.1:27042")).toBe(true);
expect(isValidFridaRemoteAddress("frida-target.example")).toBe(true);
expect(isValidFridaRemoteAddress("[::1]:27042")).toBe(true);
expect(isValidFridaRemoteAddress("tcp://127.0.0.1:27042")).toBe(false);
expect(isValidFridaRemoteAddress("127.0.0.1:70000")).toBe(false);
expect(isValidFridaRemoteAddress("127.0.0.1:0")).toBe(false);
expect(isValidFridaRemoteAddress("127.0.0.1:")).toBe(false);
expect(isValidFridaRemoteAddress("frida-target/path")).toBe(false);
expect(isValidFridaRemoteAddress("user@frida-target")).toBe(false);
});
});
+327
View File
@@ -0,0 +1,327 @@
import { z } from "zod";
import type { ToolContract } from "./toolContractTypes.js";
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
import { toolContractMetadata } from "./toolEffects.js";
import { isValidFridaRemoteAddress } from "./fridaRemoteAddress.js";
export const FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION =
"Remote keepalive interval in seconds";
const remoteConnection = z.strictObject({
address: z.string().min(1).max(2048).refine(isValidFridaRemoteAddress, {
message: "Expected a Frida host address, optionally followed by a port",
}),
token: z.string().min(1).optional(),
certificate: z.string().min(1).optional(),
origin: z.string().min(1).optional(),
keepalive_interval: z
.number()
.int()
.positive()
.describe(FRIDA_KEEPALIVE_INTERVAL_DESCRIPTION)
.optional(),
});
const deviceSelector = z.strictObject({
device_id: z.string().min(1).optional(),
remote: remoteConnection.optional(),
});
const exclusiveDeviceSelector = <Schema extends z.ZodTypeAny>(schema: Schema) =>
schema.refine(
(value) =>
!(
typeof value === "object" &&
value !== null &&
"device_id" in value &&
"remote" in value &&
value.device_id !== undefined &&
value.remote !== undefined
),
"Choose either device_id or remote, not both",
);
const sessionId = z.string().uuid();
const sessionOutput = z.strictObject({
session_id: sessionId,
device_id: z.string(),
target: z.string(),
pid: z.number().int().nonnegative(),
mode: z.enum(["attach", "spawn"]),
state: z.enum(["paused", "running", "detached"]),
});
const scriptOutput = z.strictObject({
script_id: z.string().uuid(),
source_kind: z.enum(["inline", "file"]),
source_path: z.string().nullable(),
source_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
messages: z.array(z.unknown()),
messages_truncated: z.boolean(),
});
/** Caller-facing Frida device, process, and instrumentation-session contracts. */
export const FRIDA_TOOL_CONTRACTS = [
{
name: "list_frida_devices",
...toolContractMetadata("list_frida_devices"),
kind: "native-provider",
description:
"List Frida devices currently available to this host, optionally connecting to the caller-selected remote Frida endpoint. Remote authentication options are used for this call only and are never returned or recorded.",
inputSchema: z.strictObject({ remote: remoteConnection.optional() }),
outputSchema: z.strictObject({
devices: z.array(
z.strictObject({
device_id: z.string(),
name: z.string(),
type: z.string(),
}),
),
cleanup_error: z.string().nullable(),
}),
examples: [{ title: "List Frida devices", input: {} }],
},
{
name: "list_frida_processes",
...toolContractMetadata("list_frida_processes"),
kind: "native-provider",
description:
"List processes observed on a selected Frida device or caller-supplied remote endpoint. A remote connection is closed after discovery; authentication values are never returned or recorded.",
inputSchema: exclusiveDeviceSelector(deviceSelector).refine(
(value) => value.device_id !== undefined || value.remote !== undefined,
"Select a device_id or a remote endpoint",
),
outputSchema: z.strictObject({
device_id: z.string(),
processes: z.array(
z.strictObject({
pid: z.number().int().nonnegative(),
name: z.string(),
identifier: z.string().nullable(),
}),
),
cleanup_error: z.string().nullable(),
}),
examples: [
{
title: "List local Frida processes",
input: { device_id: "local" },
},
],
},
{
name: "start_frida_session",
...toolContractMetadata("start_frida_session"),
kind: "native-provider",
description:
"Attach Frida to one selected process or spawn one selected target. Spawned targets remain paused until resume_frida_session, allowing scripts to load before execution. Closing a session detaches instrumentation; it does not kill the target.",
inputSchema: z
.strictObject({
mode: z.enum(["attach", "spawn"]),
...deviceSelector.shape,
pid: z.number().int().positive().optional(),
program: z.string().min(1).optional(),
argv: z.array(z.string()).optional(),
})
.refine(
(value) =>
((value.mode === "attach" &&
value.pid !== undefined &&
value.program === undefined &&
value.argv === undefined) ||
(value.mode === "spawn" &&
value.program !== undefined &&
value.pid === undefined)) &&
!(value.device_id !== undefined && value.remote !== undefined),
"Select one device; attach requires pid; spawn requires program and rejects pid",
),
outputSchema: sessionOutput,
examples: [
{
title: "Attach to a process",
input: { mode: "attach", device_id: "local", pid: 1234 },
},
],
},
{
name: "load_frida_script",
...toolContractMetadata("load_frida_script"),
kind: "native-provider",
description:
"Load caller-supplied JavaScript into a Frida session. Scripts can read or change target memory and behavior and can access the target process's capabilities. Messages and script errors are returned inline as Evidence; source content is not persisted.",
inputSchema: z
.strictObject({
session_id: sessionId,
source_kind: z.enum(["inline", "file"]),
source: z.string().optional(),
path: z.string().min(1).optional(),
})
.refine(
(value) =>
(value.source_kind === "inline" &&
value.source !== undefined &&
value.path === undefined) ||
(value.source_kind === "file" &&
value.path !== undefined &&
value.source === undefined),
"Inline source requires source; file source requires path",
),
outputSchema: evidenceResultOf(scriptOutput),
examples: [
{
title: "Load an inline Frida script",
input: {
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "inline",
source: "send(Process.id);",
},
},
],
},
{
name: "resume_frida_session",
...toolContractMetadata("resume_frida_session"),
kind: "native-provider",
description:
"Resume the process created by a paused Frida spawn session. Attached processes are already running and cannot be resumed through this operation.",
inputSchema: z.strictObject({ session_id: sessionId }),
outputSchema: z.strictObject({ state: z.literal("running") }),
examples: [
{
title: "Resume an instrumented process",
input: { session_id: "00000000-0000-4000-8000-000000000001" },
},
],
},
{
name: "unload_frida_script",
...toolContractMetadata("unload_frida_script"),
kind: "native-provider",
description:
"Unload one caller-selected Frida script from a live session. This removes that script's instrumentation from the target.",
inputSchema: z.strictObject({
session_id: sessionId,
script_id: z.string().uuid(),
}),
outputSchema: z.strictObject({ unloaded: z.literal(true) }),
examples: [
{
title: "Unload a script",
input: {
session_id: "00000000-0000-4000-8000-000000000001",
script_id: "00000000-0000-4000-8000-000000000002",
},
},
],
},
{
name: "frida_session_status",
...toolContractMetadata("frida_session_status"),
kind: "native-provider",
description:
"Return observed Frida session state and queued script messages. Message history is bounded by the provider capture budget and reports truncation.",
inputSchema: z.strictObject({ session_id: sessionId }),
outputSchema: evidenceResultOf(
z.strictObject({
session_id: sessionId,
device_id: z.string(),
state: z.enum(["paused", "running", "detached"]),
target: z.string(),
pid: z.number().int().nonnegative(),
mode: z.enum(["attach", "spawn"]),
scripts: z.array(
z.strictObject({ script_id: z.string().uuid(), name: z.string() }),
),
messages: z.array(z.unknown()),
messages_truncated: z.boolean(),
}),
),
examples: [
{
title: "Check Frida session",
input: { session_id: "00000000-0000-4000-8000-000000000001" },
},
],
},
{
name: "close_frida_session",
...toolContractMetadata("close_frida_session"),
kind: "native-provider",
description:
"Unload session scripts and detach REA's Frida session. If a spawned process is still paused, resume it before detaching so it is not left suspended. REA never kills the target; its final state is reported as unknown.",
inputSchema: z.strictObject({ session_id: sessionId }),
outputSchema: z.strictObject({ target_state: z.literal("unknown") }),
examples: [
{
title: "Close Frida session",
input: { session_id: "00000000-0000-4000-8000-000000000001" },
},
],
},
{
name: "instrument_with_frida",
...toolContractMetadata("instrument_with_frida"),
kind: "native-provider",
description:
"Run one caller-authored Frida script against an explicitly selected process and detach when the observation window ends. The CLI and MCP share this ephemeral workflow; use MCP session operations for persistent sessions. Remote authentication is used only for this call and excluded from Evidence.",
inputSchema: z
.strictObject({
mode: z.enum(["attach", "spawn"]),
...deviceSelector.shape,
pid: z.number().int().positive().optional(),
program: z.string().min(1).optional(),
argv: z.array(z.string()).optional(),
source_kind: z.enum(["inline", "file"]),
source: z.string().optional(),
path: z.string().min(1).optional(),
duration_ms: z.number().int().min(0).max(60_000).default(1_000),
})
.refine(
(value) =>
!(value.device_id !== undefined && value.remote !== undefined) &&
((value.mode === "attach" &&
value.pid !== undefined &&
value.program === undefined &&
value.argv === undefined) ||
(value.mode === "spawn" &&
value.program !== undefined &&
value.pid === undefined)) &&
((value.source_kind === "inline" &&
value.source !== undefined &&
value.path === undefined) ||
(value.source_kind === "file" &&
value.path !== undefined &&
value.source === undefined)),
"Select one device and provide fields matching the mode and source_kind",
),
outputSchema: evidenceResultOf(
z.strictObject({
...sessionOutput.shape,
scripts: z.array(
z.strictObject({ script_id: sessionId, name: z.string() }),
),
messages: z.array(z.unknown()),
messages_truncated: z.boolean(),
source_kind: z.enum(["inline", "file"]),
source_path: z.string().nullable(),
source_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
cleanup_error: z.string().nullable(),
}),
),
examples: [
{
title: "Instrument a selected process briefly",
input: {
mode: "attach",
device_id: "local",
pid: 1234,
source_kind: "inline",
source: "send(Process.id);",
duration_ms: 1_000,
},
},
],
},
] as const satisfies readonly ToolContract[];
+23
View File
@@ -81,4 +81,27 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
left_bundle_path: "/tmp/left-evidence.json",
right_bundle_path: "/tmp/right-evidence.json",
},
list_frida_devices: {},
list_frida_processes: { device_id: "local" },
start_frida_session: { mode: "attach", device_id: "local", pid: 1234 },
load_frida_script: {
session_id: "00000000-0000-4000-8000-000000000001",
source_kind: "inline",
source: "send(Process.id);",
},
resume_frida_session: { session_id: "00000000-0000-4000-8000-000000000001" },
unload_frida_script: {
session_id: "00000000-0000-4000-8000-000000000001",
script_id: "00000000-0000-4000-8000-000000000002",
},
frida_session_status: { session_id: "00000000-0000-4000-8000-000000000001" },
close_frida_session: { session_id: "00000000-0000-4000-8000-000000000001" },
instrument_with_frida: {
mode: "attach",
device_id: "local",
pid: 1234,
source_kind: "inline",
source: "send(Process.id);",
duration_ms: 1_000,
},
};
+2
View File
@@ -23,6 +23,7 @@ import { JAVASCRIPT_RECOVERY_TOOL_CONTRACTS } from "./javascript/javascriptRecov
import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
import { ENHANCED_TOOL_CONTRACTS } from "./enhancedToolContracts.js";
import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
import { FRIDA_TOOL_CONTRACTS } from "./fridaToolContracts.js";
/** Complete ordered public inventory used by registration and verification. */
export const TOOL_CONTRACTS = [
@@ -51,6 +52,7 @@ export const TOOL_CONTRACTS = [
...WEB_NETWORK_CAPTURE_TOOL_CONTRACTS,
...JAVASCRIPT_RECOVERY_TOOL_CONTRACTS,
...SESSION_TOOL_CONTRACTS,
...FRIDA_TOOL_CONTRACTS,
] as const;
/** Resolve a public contract by name while retaining its exact schema types. */
+5
View File
@@ -13,6 +13,8 @@ const EXECUTION_WORDING =
/\b(?:run|runs|running|launch|launches|launching|execute|executes|executing|execution|start|starts|install|installs|uninstall|uninstalls)\b/iu;
const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
start_frida_session:
"spawned targets remain suspended until resume_frida_session",
inspect_native_load_image: "states that it does not execute the target",
resolve_native_call_targets: "states that it does not execute code",
inspect_pe_resources: "states that it does not execute the image",
@@ -117,8 +119,11 @@ describe("tool effects", () => {
"capture_native_ui_scenario",
"capture_process_scenario",
"install_adb_package",
"instrument_with_frida",
"load_frida_script",
"observe_native_calls",
"push_adb_file",
"resume_frida_session",
"start_adb_activity",
"start_adb_app",
"stop_adb_app",
+51
View File
@@ -98,6 +98,57 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
writesFilesystem: true,
launchesProcess: true,
}),
list_frida_devices: effects({ launchesProcess: true, accessesNetwork: true }),
list_frida_processes: effects({
launchesProcess: true,
accessesNetwork: true,
}),
start_frida_session: effects({
mutatesTarget: true,
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
idempotent: false,
}),
load_frida_script: effects({
mutatesTarget: true,
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
executesForeignCode: true,
idempotent: false,
}),
resume_frida_session: effects({
mutatesTarget: true,
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
executesForeignCode: true,
idempotent: false,
}),
unload_frida_script: effects({
mutatesTarget: true,
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
idempotent: false,
}),
frida_session_status: effects(),
close_frida_session: effects({
mutatesTarget: true,
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
idempotent: false,
}),
instrument_with_frida: effects({
mutatesTarget: true,
mutatesSession: true,
launchesProcess: true,
accessesNetwork: true,
executesForeignCode: true,
idempotent: false,
}),
inspect_pe_resources: evidence,
inspect_analysis_view: evidence,
inspect_firmware_regions: effects({