Files
rea/src/ghidra/GhidraInventoryValues.ts
T
2a78763e20 feat(native): search analyzed memory for masked byte patterns (#2341)
* feat(native): search analyzed memory for masked byte patterns

The diff adds search_bytes to the CLI, the shared MCP contract, Ghidra
inventory, and the headless bridge, and advertises the same operation on
Hopper as unavailable until that provider is verified. Patterns are
hexadecimal byte pairs with optional ?? wildcards and an optional
equal-length bit mask; the TypeScript boundary and the bridge both
require a nonempty pattern, equal lengths, and at least one constrained
bit. Ghidra walks initialized blocks in address order within inclusive
bounds, keeps overlapping matches inside a single block, and returns
each hit with its segment, unique source file offset, and containing
procedure, continuing through a cursor bound to the target, profile,
pattern, mask, and bounds. Each page reports the inclusive ranges
examined and the skipped uninitialized blocks; cancellation returns a
typed error and discards the active Ghidra database.
address_to_file_offset now uses the same unique-offset helper, which
rejects a mapping that is missing, ambiguous, or larger than a safe
integer.

* fix(native): limit unbounded byte search to loaded memory

Without start or end, search_bytes walked every Ghidra block, including
non-loaded file parts such as .symtab and overlay blocks, which the docs
call out of scope. Unbounded searches now skip those blocks and list them
in searched.skipped_not_loaded; explicit bounds in their address space
still search them. Document that a match must end at or before end.

* fix(native): preserve implicit address spaces in range consumers

* fix(native): reject present malformed byte search state

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-13 23:41:45 +08:00

362 lines
12 KiB
TypeScript

import { z } from "zod";
import {
bytePatternFields,
validateBytePattern,
byteSearchResultSchema,
} from "../domain/native/bytePattern.js";
import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
import {
type AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import {
functionBodySchema,
functionBodyEntryAgrees,
} from "../domain/hopperValues.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
/**
* Direct inventory operations admitted by the Ghidra adapter. All are reads
* except the naming operations, which edit the ephemeral session database.
*/
export const GHIDRA_INVENTORY_OPERATIONS = [
"inspect_native_load_image",
"read_bytes",
"search_bytes",
"address_to_file_offset",
"address_name",
"list_documents",
"list_names",
"list_procedures",
"list_segments",
"list_strings",
"procedure_address",
"resolve_containing_procedure",
"search_procedures",
"search_strings",
"set_address_name",
"set_addresses_names",
] as const;
/** Inventory operations that write analyst names into the session database. */
export const GHIDRA_NAMING_OPERATIONS = [
"set_address_name",
"set_addresses_names",
] as const satisfies readonly GhidraInventoryOperation[];
/** One direct inventory operation implemented by the packaged Java bridge. */
export type GhidraInventoryOperation =
(typeof GHIDRA_INVENTORY_OPERATIONS)[number];
const operationSet: ReadonlySet<string> = new Set(GHIDRA_INVENTORY_OPERATIONS);
/** Narrow an application operation to the Ghidra inventory surface. */
export const isGhidraInventoryOperation = (
operation: string,
): operation is GhidraInventoryOperation => operationSet.has(operation);
export const ghidraIdentifierSchema = z.string().min(1);
const identifier = ghidraIdentifierSchema;
const document = identifier.nullable().default(null);
/** Caller address spelling; the bridge resolves its space and emits canonical output. */
export const ghidraInputAddressSchema = z
.string()
.regex(
/^(?:(?:0[xX])?[0-9a-fA-F]+|(?:[A-Za-z0-9._~-]|%[0-9a-fA-F]{2})+:0[xX][0-9a-fA-F]+)$/u,
"Use hexadecimal digits, optionally prefixed with 0x, or an encoded address-space name followed by :0x and hexadecimal digits",
);
const explicitAddress = ghidraInputAddressSchema;
const filteredAddress = explicitAddress.nullable().default(null);
const searchInput = {
pattern: z.string().min(1),
mode: z.enum(["literal", "regex"]).default("literal"),
case_sensitive: z.boolean().default(false),
document,
};
const inputSchemas = {
search_bytes: z
.strictObject({
...bytePatternFields,
document,
start: explicitAddress.optional(),
end: explicitAddress.optional(),
limit: z.number().int().min(1).max(1000).default(100),
cursor: z.string().min(1).optional(),
})
.superRefine(validateBytePattern),
inspect_native_load_image: z.strictObject({}),
read_bytes: z.strictObject({
document,
address: explicitAddress,
length: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).default(256),
}),
address_to_file_offset: z.strictObject({
document,
address: explicitAddress,
}),
address_name: z.object({ document, address: explicitAddress }).strict(),
list_documents: z.object({}).strict(),
list_names: z.object({ document, address: filteredAddress }).strict(),
list_procedures: z.object({ document }).strict(),
list_segments: z.object({ document }).strict(),
list_strings: z.object({ document, address: filteredAddress }).strict(),
procedure_address: z.object({ document, procedure: identifier }).strict(),
resolve_containing_procedure: z
.object({ document, address: explicitAddress })
.strict(),
search_procedures: z.object(searchInput).strict(),
search_strings: z.object(searchInput).strict(),
set_address_name: z
.object({ document, address: explicitAddress, name: z.string().min(1) })
.strict(),
set_addresses_names: z
.object({
document,
names: z.record(explicitAddress, z.string().min(1)),
})
.strict()
.refine(
(value) => Object.keys(value.names).length > 0,
"Supply at least one address name",
),
} satisfies Readonly<Record<GhidraInventoryOperation, z.ZodType>>;
/** Validate and default one provider request before it crosses the socket. */
export const parseGhidraInventoryInput = (
operation: GhidraInventoryOperation,
value: Readonly<Record<string, JsonValue>>,
): Result<Readonly<Record<string, JsonValue>>, AnalysisInputError> => {
const parsed = inputSchemas[operation].safeParse(value);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(operation, parsed.error.issues, value, {
cause: parsed.error,
}),
);
return ok(parsed.data);
};
export const ghidraCanonicalAddressSchema = z
.string()
.regex(/^(?:0x[0-9a-f]+|(?:[A-Za-z0-9._~-]|%[0-9A-F]{2})+:0x[0-9a-f]+)$/u);
const canonicalAddress = ghidraCanonicalAddressSchema;
const symbolFacts = z
.object({
primary: z.boolean(),
dynamic: z.boolean(),
external: z.boolean(),
type: z.string().min(1),
source: z.enum(["default", "analysis", "ai", "imported", "user_defined"]),
})
.strict();
const procedureFacts = z
.object({
external: z.boolean(),
thunk: z.boolean(),
thunk_target: canonicalAddress.nullable(),
})
.strict();
/** Ghidra FunctionManager classification, independent of body ownership inference. */
export const ghidraFunctionClassificationSchema = procedureFacts
.extend({ provenance: z.literal("ghidra-function-manager") })
.strict();
/** Require complete canonical AddressSet evidence on every Ghidra function identity. */
export const ghidraFunctionBodySchema = functionBodySchema.superRefine(
(body, context) => {
if (
!body.available ||
body.provenance !== "ghidra-function-body-address-set" ||
body.ranges.some(
({ start, end }) =>
!ghidraCanonicalAddressSchema.safeParse(start).success ||
!ghidraCanonicalAddressSchema.safeParse(end).success,
)
)
context.addIssue({
code: "custom",
message:
"Ghidra omitted complete canonical function-body AddressSet evidence",
});
},
);
/** Strict provider identity shared by inventory and function-analysis results. */
export const ghidraProcedureIdentitySchema = z
.object({
address: ghidraCanonicalAddressSchema,
name: z.string().min(1),
classification: ghidraFunctionClassificationSchema,
body: ghidraFunctionBodySchema,
})
.strict()
.superRefine((value, context) => {
if (
!functionBodyEntryAgrees(value.body, value.address) ||
(value.body.available &&
!value.classification.external &&
!value.body.contains_entry)
)
context.addIssue({
code: "custom",
message: "Ghidra function body disagrees with its entry point",
});
});
const stringFacts = z
.object({
encoding: z.string().min(1),
termination: z.enum(["missing", "present_or_not_required"]),
byte_length: z.number().int().min(0),
})
.strict();
const baseItem = {
address: canonicalAddress,
value: z.string(),
};
const symbolItem = z.object({ ...baseItem, symbol: symbolFacts }).strict();
const procedureItem = z
.object({ ...baseItem, procedure: procedureFacts })
.strict();
const stringItem = z.object({ ...baseItem, string: stringFacts }).strict();
const searchItem = z.object(baseItem).strict();
const availablePermissions = z
.object({
available: z.literal(true),
source: z.literal("ghidra-memory-block"),
})
.strict();
const memoryRegion = z
.object({
name: z.string(),
start: canonicalAddress,
end: canonicalAddress,
readable: z.boolean(),
writable: z.boolean(),
executable: z.boolean(),
permissions: availablePermissions,
provenance: z.literal("ghidra-memory-block"),
address_space: z.string().min(1),
image_base: canonicalAddress,
initialized: z.boolean(),
overlay: z.boolean(),
})
.strict();
const segment = memoryRegion
.extend({ sections: z.array(memoryRegion) })
.strict();
const containingProcedure = z.discriminatedUnion("found", [
z
.object({
query_address: canonicalAddress,
found: z.literal(true),
procedure: ghidraProcedureIdentitySchema,
})
.strict()
.superRefine((value, context) => {
const body = value.procedure.body;
const exactExternalEntry =
value.procedure.classification.external &&
value.query_address === value.procedure.address;
if (
!exactExternalEntry &&
body.available &&
!functionBodyEntryAgrees(
{ ...body, contains_entry: true },
value.query_address,
)
)
context.addIssue({
code: "custom",
message:
"Found containing procedure body does not contain the query address",
});
}),
z
.object({
query_address: canonicalAddress,
found: z.literal(false),
procedure: z.null(),
reason: z.enum(["outside_segments", "not_in_procedure"]),
})
.strict(),
]);
const resultSchemas = {
search_bytes: byteSearchResultSchema.superRefine((value, context) => {
const addresses = [
...value.matches.flatMap((match) => [
match.address,
...(match.procedure === null ? [] : [match.procedure.address]),
]),
...[
...value.searched.blocks,
...value.searched.skipped_uninitialized,
...value.searched.skipped_not_loaded,
].flatMap((block) => [block.start, block.end]),
];
if (addresses.some((value) => !canonicalAddress.safeParse(value).success))
context.addIssue({
code: "custom",
message: "Byte search addresses must be canonical",
});
}),
inspect_native_load_image: nativeLoadImageObservationSchema,
read_bytes: z
.strictObject({
address: canonicalAddress,
requested_bytes: z.number().int().min(1),
returned_bytes: z.number().int().min(0),
bytes_hex: z.string().regex(/^(?:[a-f0-9]{2})*$/u),
complete: z.boolean(),
})
.superRefine((value, context) => {
if (
value.returned_bytes * 2 !== value.bytes_hex.length ||
value.returned_bytes > value.requested_bytes ||
value.complete !== (value.returned_bytes === value.requested_bytes)
)
context.addIssue({
code: "custom",
message: "Read-byte length and completeness disagree",
});
}),
address_to_file_offset: z.strictObject({
address: canonicalAddress,
file_offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
}),
address_name: z.string().nullable(),
list_documents: z.array(z.string().min(1)).length(1),
list_names: z.array(symbolItem),
list_procedures: z.array(procedureItem),
list_segments: z.array(segment),
list_strings: z.array(stringItem),
procedure_address: canonicalAddress,
resolve_containing_procedure: containingProcedure,
search_procedures: z.array(searchItem),
search_strings: z.array(searchItem),
set_address_name: z.boolean(),
set_addresses_names: z.record(z.string(), z.boolean()),
} satisfies Readonly<Record<GhidraInventoryOperation, z.ZodType>>;
/** Validate exact Java-bridge output before creating Evidence. */
export const parseGhidraInventoryResult = (
operation: GhidraInventoryOperation,
value: JsonValue,
): Result<JsonValue, AnalysisOutputError> => {
const parsed = resultSchemas[operation].safeParse(value);
return parsed.success
? ok(jsonValueSchema.parse(parsed.data))
: err(
new AnalysisOutputError(
operation,
"Ghidra bridge output did not match the inventory contract",
{ cause: parsed.error },
),
);
};