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>
This commit is contained in:
co-authored by
Matt Van Horn
morluto
parent
70611713e1
commit
2a78763e20
@@ -60,6 +60,7 @@ type DirectAnalysisTool =
|
||||
| "annotate_native_function"
|
||||
| "inspect_native_load_image"
|
||||
| "read_bytes"
|
||||
| "search_bytes"
|
||||
| "address_to_file_offset"
|
||||
| "binary_overview"
|
||||
| "procedure_pseudo_code"
|
||||
|
||||
@@ -17,6 +17,46 @@ export const registerCoreNativeCommands = (
|
||||
runDirectAnalysis: DirectAnalysis["runDirectAnalysis"],
|
||||
): void => {
|
||||
registerAnnotationCommand(cli, logger, runDirectAnalysis);
|
||||
cli.command(CLI_COMMANDS.searchBytes, {
|
||||
description: "Find masked byte patterns in initialized provider memory",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local executable path"),
|
||||
pattern: z.string().describe("Hexadecimal byte pairs with ?? wildcards"),
|
||||
}),
|
||||
options: z.object({
|
||||
mask: z.string().optional().describe("Equal-length hexadecimal bit mask"),
|
||||
start: z.string().optional().describe("Inclusive start address"),
|
||||
end: z.string().optional().describe("Inclusive end address"),
|
||||
cursor: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Continuation from the same query's next_cursor"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1000)
|
||||
.default(100)
|
||||
.describe("Maximum matches on this page"),
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.searchBytes, () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"search_bytes",
|
||||
{
|
||||
pattern: args.pattern,
|
||||
limit: options.limit,
|
||||
...(options.mask === undefined ? {} : { mask: options.mask }),
|
||||
...(options.start === undefined ? {} : { start: options.start }),
|
||||
...(options.end === undefined ? {} : { end: options.end }),
|
||||
...(options.cursor === undefined ? {} : { cursor: options.cursor }),
|
||||
},
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.inspectNativeLoadImage, {
|
||||
description:
|
||||
"Verify loaded native bytes, source mappings, relocations and entry",
|
||||
|
||||
@@ -39,6 +39,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
inspectNativeDataType: "inspect-native-data-type",
|
||||
inspectNativeLoadImage: "inspect-native-load-image",
|
||||
readBytes: "read-bytes",
|
||||
searchBytes: "search-bytes",
|
||||
addressToFileOffset: "address-to-file-offset",
|
||||
traceNativeValues: "trace-native-values",
|
||||
inspectNativeInstruction: "inspect-native-instruction",
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
import { z } from "zod";
|
||||
import { address, document } from "./toolContractHelpers.js";
|
||||
import {
|
||||
bytePatternFields,
|
||||
validateBytePattern,
|
||||
} from "../domain/native/bytePattern.js";
|
||||
|
||||
/** Hopper memory and file-mapping contracts. */
|
||||
export const HOPPER_MEMORY_TOOL_DEFINITIONS = [
|
||||
{
|
||||
name: "search_bytes",
|
||||
description:
|
||||
"Find masked byte signatures in initialized analyzed memory. Hex byte pairs and ?? wildcards are supported; an optional equal-length hex mask selects bits. Bounds are inclusive. Matches are ordered by provider address and never span blocks. Coverage describes this page; reuse the same query with next_cursor to continue. Uninitialized blocks are listed separately. Ghidra only; Hopper is unavailable.",
|
||||
inputSchema: z
|
||||
.strictObject({
|
||||
...bytePatternFields,
|
||||
document,
|
||||
start: address.optional(),
|
||||
end: address.optional(),
|
||||
limit: z.number().int().min(1).max(1000).default(100),
|
||||
cursor: z.string().min(1).optional(),
|
||||
})
|
||||
.superRefine(validateBytePattern),
|
||||
},
|
||||
{
|
||||
name: "read_bytes",
|
||||
description:
|
||||
|
||||
@@ -26,6 +26,7 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
resolve_native_call_targets: { address: "0x1000" },
|
||||
read_function_instructions: { procedure: "main" },
|
||||
read_bytes: { address: "0x1000", length: 16 },
|
||||
search_bytes: { pattern: "48 8B ?? ?? 89" },
|
||||
address_to_file_offset: { address: "0x1000" },
|
||||
procedure_references: { procedure: "main" },
|
||||
procedure_pseudo_code: { procedure: "main" },
|
||||
|
||||
@@ -438,6 +438,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
inspect_native_data_type: evidence,
|
||||
resolve_native_call_targets: evidence,
|
||||
read_bytes: evidence,
|
||||
search_bytes: evidence,
|
||||
address_to_file_offset: evidence,
|
||||
procedure_references: evidence,
|
||||
procedure_pseudo_code: evidence,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { byteSearchResultSchema } from "../domain/native/bytePattern.js";
|
||||
import {
|
||||
artifactInventorySummaryViewResultSchema,
|
||||
machoSummaryViewResultSchema,
|
||||
@@ -108,6 +109,7 @@ const bookmarkFacetSchema = z.discriminatedUnion("state", [
|
||||
|
||||
/** Exact structured-content schemas shared by direct analysis providers. */
|
||||
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
search_bytes: evidenceResultOf(byteSearchResultSchema),
|
||||
annotate_native_function: evidenceResultOf(nativeFunctionAnnotationsSchema),
|
||||
inspect_native_load_image: evidenceResultOf(nativeLoadImageSchema),
|
||||
inspect_native_data_type: evidenceResultOf(nativeDataTypeSchema),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { addressCoordinate } from "./native/addressCoordinate.js";
|
||||
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
@@ -38,16 +39,6 @@ export const addressDistance = (start: string, end: string): number => {
|
||||
);
|
||||
};
|
||||
|
||||
const addressCoordinate = (
|
||||
value: string,
|
||||
): { readonly space: string; readonly offset: bigint } | null => {
|
||||
const separator = value.lastIndexOf(":0x");
|
||||
const space = separator < 0 ? "default" : value.slice(0, separator);
|
||||
const offset = separator < 0 ? value : value.slice(separator + 1);
|
||||
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
|
||||
return { space, offset: BigInt(offset) };
|
||||
};
|
||||
|
||||
const procedureMapSchema = z.record(z.string(), z.string());
|
||||
const addressedNamesSchema = z.array(
|
||||
z.object({ address: z.string(), name: z.string() }),
|
||||
@@ -128,9 +119,9 @@ export const functionBodySchema = z.discriminatedUnion("available", [
|
||||
})
|
||||
.superRefine((body, context) => {
|
||||
let total = 0n;
|
||||
const bounds = new Map<string, { start: bigint; end: bigint }>();
|
||||
const closedSpaces = new Set<string>();
|
||||
let previousSpace: string | null = null;
|
||||
const bounds = new Map<string | null, { start: bigint; end: bigint }>();
|
||||
const closedSpaces = new Set<string | null>();
|
||||
let previousSpace: string | null | undefined;
|
||||
for (const range of body.ranges) {
|
||||
const start = addressCoordinate(range.start);
|
||||
const end = addressCoordinate(range.end);
|
||||
@@ -146,7 +137,7 @@ export const functionBodySchema = z.discriminatedUnion("available", [
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (previousSpace !== null && previousSpace !== start.space)
|
||||
if (previousSpace !== undefined && previousSpace !== start.space)
|
||||
closedSpaces.add(previousSpace);
|
||||
const previous = bounds.get(start.space);
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/** Parse canonical native offsets without discarding their address space. */
|
||||
export const addressCoordinate = (
|
||||
value: string,
|
||||
): { readonly space: string | null; readonly offset: bigint } | null => {
|
||||
const separator = value.lastIndexOf(":0x");
|
||||
if (separator === 0) return null;
|
||||
const space = separator < 0 ? null : value.slice(0, separator);
|
||||
const offset = separator < 0 ? value : value.slice(separator + 1);
|
||||
if (!/^0x[0-9a-f]+$/u.test(offset)) return null;
|
||||
return { space, offset: BigInt(offset) };
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseBytePattern } from "./bytePattern.js";
|
||||
|
||||
describe("masked byte patterns", () => {
|
||||
it("preserves whole-byte wildcards and combines explicit bit masks", () => {
|
||||
const parsed = parseBytePattern("48 8b\t??89", "ff f0 ff 0f");
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
expect(parsed.value).toEqual({
|
||||
bytes: [0x48, 0x8b, 0, 0x89],
|
||||
masks: [255, 240, 0, 15],
|
||||
});
|
||||
const exact = parseBytePattern("Aa\u00a000");
|
||||
if (!exact.ok) throw exact.error;
|
||||
expect(exact.value).toEqual({ bytes: [170, 0], masks: [255, 255] });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", undefined, "pattern"],
|
||||
["4", undefined, "pattern"],
|
||||
["4?", undefined, "pattern"],
|
||||
["gg", undefined, "pattern"],
|
||||
["?? ??", undefined, "pattern"],
|
||||
["ff", "00", "pattern"],
|
||||
["ffff", "ff", "mask"],
|
||||
["ff", "??", "mask"],
|
||||
])("rejects invalid pattern %s with typed issues", (pattern, mask, field) => {
|
||||
const parsed = parseBytePattern(pattern, mask);
|
||||
if (parsed.ok) throw new Error("Expected a rejected pattern");
|
||||
expect(parsed.error.issues).toMatchObject([
|
||||
{ path: [field], reason: "invalid_value" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { z } from "zod";
|
||||
import { addressCoordinate } from "./addressCoordinate.js";
|
||||
import { AnalysisInputError } from "../analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
|
||||
/** Byte pairs, with whole-byte wildcards; explicit masks can select individual bits. */
|
||||
export const bytePatternFields = {
|
||||
pattern: z
|
||||
.string()
|
||||
.regex(/^([0-9a-fA-F]{2}|\?\?)(\s*([0-9a-fA-F]{2}|\?\?))*$/u),
|
||||
mask: z
|
||||
.string()
|
||||
.regex(/^[0-9a-fA-F]{2}(\s*[0-9a-fA-F]{2})*$/u)
|
||||
.optional(),
|
||||
};
|
||||
|
||||
/** Parse once at the input boundary, retaining typed correction issues. */
|
||||
export const parseBytePattern = (
|
||||
pattern: string,
|
||||
mask?: string,
|
||||
): Result<{ bytes: number[]; masks: number[] }, AnalysisInputError> => {
|
||||
const invalid = (field: string, message: string) =>
|
||||
err(
|
||||
new AnalysisInputError("search_bytes", undefined, [
|
||||
{ path: [field], reason: "invalid_value", message },
|
||||
]),
|
||||
);
|
||||
if (!bytePatternFields.pattern.safeParse(pattern).success)
|
||||
return invalid("pattern", "Use hexadecimal byte pairs or ?? wildcards");
|
||||
if (mask !== undefined && !bytePatternFields.mask.safeParse(mask).success)
|
||||
return invalid("mask", "Use hexadecimal mask byte pairs");
|
||||
const pairs = pattern.replace(/\s/gu, "").match(/../gu) ?? [];
|
||||
const maskPairs = mask?.replace(/\s/gu, "").match(/../gu);
|
||||
if (maskPairs && maskPairs.length !== pairs.length)
|
||||
return invalid("mask", "Mask length must equal pattern length");
|
||||
const bytes = pairs.map((pair) =>
|
||||
pair === "??" ? 0 : Number.parseInt(pair, 16),
|
||||
);
|
||||
const masks = pairs.map((pair, index) =>
|
||||
pair === "??" ? 0 : Number.parseInt(maskPairs?.[index] ?? "ff", 16),
|
||||
);
|
||||
if (!masks.some((value) => value !== 0))
|
||||
return invalid("pattern", "Pattern must constrain at least one bit");
|
||||
return ok({ bytes, masks });
|
||||
};
|
||||
|
||||
/** Shared semantic validation for public and provider inputs. */
|
||||
export const validateBytePattern = (
|
||||
value: { pattern: string; mask?: string | undefined },
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
const parsed = parseBytePattern(value.pattern, value.mask);
|
||||
if (!parsed.ok)
|
||||
for (const issue of parsed.error.issues)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: [...issue.path],
|
||||
message: issue.message ?? "Invalid byte pattern",
|
||||
});
|
||||
};
|
||||
|
||||
const coverageBlock = z
|
||||
.strictObject({
|
||||
segment: z.string(),
|
||||
start: z.string(),
|
||||
end: z.string(),
|
||||
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
const start = addressCoordinate(value.start);
|
||||
const end = addressCoordinate(value.end);
|
||||
if (
|
||||
start === null ||
|
||||
end === null ||
|
||||
start.space !== end.space ||
|
||||
start.offset > end.offset ||
|
||||
end.offset - start.offset + 1n !== BigInt(value.bytes)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Byte coverage must equal its inclusive address range in one space",
|
||||
});
|
||||
});
|
||||
|
||||
/** Inclusive page coverage; matches never span memory blocks. */
|
||||
export const byteSearchResultSchema = z
|
||||
.strictObject({
|
||||
matches: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
address: z.string(),
|
||||
segment: z.string(),
|
||||
file_offset: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.nullable(),
|
||||
procedure: z
|
||||
.strictObject({ address: z.string(), name: z.string() })
|
||||
.nullable(),
|
||||
}),
|
||||
)
|
||||
.max(1000),
|
||||
searched: z.strictObject({
|
||||
blocks: z.array(coverageBlock),
|
||||
bytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
skipped_uninitialized: z.array(coverageBlock),
|
||||
skipped_not_loaded: z.array(coverageBlock),
|
||||
}),
|
||||
complete: z.boolean(),
|
||||
next_cursor: z.string().min(1).nullable(),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (
|
||||
value.complete !== (value.next_cursor === null) ||
|
||||
value.searched.bytes !==
|
||||
value.searched.blocks.reduce((sum, block) => sum + block.bytes, 0)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Byte search coverage and continuation disagree",
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,9 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
bytePatternFields,
|
||||
validateBytePattern,
|
||||
byteSearchResultSchema,
|
||||
} from "../domain/native/bytePattern.js";
|
||||
import { nativeLoadImageObservationSchema } from "../domain/native/nativeLoadImage.js";
|
||||
|
||||
import {
|
||||
@@ -20,6 +25,7 @@ import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js"
|
||||
export const GHIDRA_INVENTORY_OPERATIONS = [
|
||||
"inspect_native_load_image",
|
||||
"read_bytes",
|
||||
"search_bytes",
|
||||
"address_to_file_offset",
|
||||
"address_name",
|
||||
"list_documents",
|
||||
@@ -72,6 +78,16 @@ const searchInput = {
|
||||
};
|
||||
|
||||
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,
|
||||
@@ -271,6 +287,24 @@ const containingProcedure = z.discriminatedUnion("found", [
|
||||
]);
|
||||
|
||||
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({
|
||||
|
||||
@@ -90,6 +90,11 @@ export const limitationsFor = (operation: string): readonly string[] => {
|
||||
...common,
|
||||
"Bytes reflect Ghidra's initialized memory, including loader fixups. Reads stop at an unmapped or uninitialized byte and report completeness explicitly.",
|
||||
];
|
||||
case "search_bytes":
|
||||
return [
|
||||
...common,
|
||||
"Searches initialized loader-adjusted memory independently per block, in provider address order. Bounds and page coverage ends are inclusive. Uninitialized blocks are listed separately. Overlapping matches are included; patterns never cross block boundaries. A cursor resumes the same target, profile and query. Cancellation discards the active search and returns no successful partial page.",
|
||||
];
|
||||
case "address_to_file_offset":
|
||||
return [
|
||||
...common,
|
||||
|
||||
@@ -62,12 +62,16 @@ const MUTATING_OPERATIONS = new Set<string>([
|
||||
|
||||
/** Source-owned capabilities without acquiring or probing a Hopper session. */
|
||||
export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
HOPPER_OPERATIONS.map((operation) =>
|
||||
[...HOPPER_OPERATIONS, "search_bytes" as const].map((operation) =>
|
||||
Object.freeze({
|
||||
provider: HOPPER_PROVIDER_IDENTITY,
|
||||
operation,
|
||||
available: true,
|
||||
reason: null,
|
||||
...(operation === "search_bytes"
|
||||
? {
|
||||
available: false as const,
|
||||
reason: "Masked byte search has not been verified for Hopper.",
|
||||
}
|
||||
: { available: true as const, reason: null }),
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: MUTATING_OPERATIONS.has(operation),
|
||||
launchesProcess: true,
|
||||
|
||||
Reference in New Issue
Block a user