feat(ghidra): admit explicit DOS COM analysis (#702)
* feat(ghidra): admit explicit DOS COM analysis Carry caller-selected COM interpretation through CLI, MCP and target identity, seed real-mode entry/context before Ghidra analysis, and verify complete loaded bytes, source mappings and measured register context. Keep original binaries unchanged and PSP/runtime coverage explicit. Assisted-by: Nitori (gensokyo-skills:nitori-reverse-engineering) * fix(verification): validate COM package selection before allocating fixtures
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import type { ExecutableFormatHint } from "../domain/dosCom.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import {
|
||||
@@ -17,6 +18,7 @@ import { SessionProviderRouter } from "./SessionProviderRouter.js";
|
||||
export interface BinarySessionOpenOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
}
|
||||
@@ -54,6 +56,7 @@ export const resolveSessionOpen = async (
|
||||
process.cwd(),
|
||||
process.arch,
|
||||
options.targetKind,
|
||||
options.formatHint,
|
||||
);
|
||||
if (!parsed.ok) return parsed;
|
||||
const target = parsed.value;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ExecutableFormatHint } from "../domain/dosCom.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
@@ -29,6 +30,7 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
options?: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
},
|
||||
|
||||
@@ -16,6 +16,10 @@ import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import { BinaryTargetError } from "../domain/configurationErrors.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
validateDosComLength,
|
||||
type ExecutableFormatHint,
|
||||
} from "../domain/dosCom.js";
|
||||
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
@@ -40,6 +44,7 @@ export const parseBinaryTarget = async (
|
||||
cwd = process.cwd(),
|
||||
hostArchitecture: NodeJS.Architecture = process.arch,
|
||||
targetKind?: BinaryTarget["kind"],
|
||||
formatHint?: ExecutableFormatHint,
|
||||
): Promise<Result<BinaryTarget, BinaryTargetError>> => {
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
@@ -52,6 +57,26 @@ export const parseBinaryTarget = async (
|
||||
try {
|
||||
if (!(await handle.stat()).isFile())
|
||||
return err(new BinaryTargetError(path, "target is not a regular file"));
|
||||
if (formatHint === "dos-com") {
|
||||
if (targetKind !== undefined && targetKind !== "executable")
|
||||
return err(
|
||||
new BinaryTargetError(
|
||||
path,
|
||||
"DOS COM format requires an executable target kind",
|
||||
),
|
||||
);
|
||||
const length = validateDosComLength((await handle.stat()).size);
|
||||
if (!length.ok) return err(new BinaryTargetError(path, length.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "executable",
|
||||
format: "dos-com",
|
||||
architecture: "x86",
|
||||
availableArchitectures: ["x86"],
|
||||
});
|
||||
}
|
||||
if (
|
||||
targetKind === "database" ||
|
||||
(targetKind === undefined && path.toLowerCase().endsWith(".hop"))
|
||||
@@ -126,7 +151,7 @@ const detectArtifactFormat = async (
|
||||
): Promise<
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz"
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
@@ -168,7 +193,7 @@ const namedArtifactFormat = (
|
||||
const isArchiveFormat = (
|
||||
format: Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz"
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
|
||||
>,
|
||||
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
|
||||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ExecutableFormatHint } from "../domain/dosCom.js";
|
||||
import { parseConfig } from "../config.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
@@ -75,6 +76,7 @@ export const runDirectAnalysis = async (
|
||||
readonly snapshotPath?: string | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
} = {},
|
||||
): Promise<JsonValue> =>
|
||||
withProcessCancellation(options.signal, (signal) =>
|
||||
@@ -82,6 +84,9 @@ export const runDirectAnalysis = async (
|
||||
logger: options.logger ?? silentLogger,
|
||||
snapshotPath: options.snapshotPath,
|
||||
signal,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
@@ -156,6 +161,7 @@ const runAnalysis = async (
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly signal: AbortSignal;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
/**
|
||||
* Environment the configuration is read from. Defaults to the process
|
||||
* environment so existing callers are unchanged, but a caller may supply
|
||||
@@ -174,11 +180,17 @@ const runAnalysis = async (
|
||||
const prepared = await prepareSnapshot({
|
||||
path,
|
||||
snapshotPath,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
const { snapshot } = prepared.value;
|
||||
const opened = await session.open(path, {
|
||||
signal,
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(snapshot === undefined ? {} : { snapshot }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
@@ -320,6 +332,7 @@ const withProcessCancellation = async <Value>(
|
||||
|
||||
const prepareSnapshot = async (options: {
|
||||
readonly path: string;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly snapshotPath: string | undefined;
|
||||
}): Promise<
|
||||
Result<{ readonly snapshot?: AnalysisSnapshot }, AnalysisError>
|
||||
@@ -329,7 +342,13 @@ const prepareSnapshot = async (options: {
|
||||
return ok({});
|
||||
const loaded = await readAnalysisSnapshot(snapshotPath);
|
||||
if (!loaded.ok) return loaded;
|
||||
const target = await parseBinaryTarget(path);
|
||||
const target = await parseBinaryTarget(
|
||||
path,
|
||||
process.cwd(),
|
||||
process.arch,
|
||||
undefined,
|
||||
options.formatHint,
|
||||
);
|
||||
if (!target.ok) return target;
|
||||
if (!snapshotMatchesTarget(loaded.value.target, target.value))
|
||||
return err(
|
||||
|
||||
+134
-21
@@ -6,7 +6,11 @@ import { runDirectAnalysis } from "../application/DirectAnalysis.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { directAnalysisOptions, providerSelectionOption } from "./options.js";
|
||||
import {
|
||||
directAnalysisOptions,
|
||||
formatSelectionOption,
|
||||
providerSelectionOption,
|
||||
} from "./options.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
|
||||
|
||||
@@ -19,14 +23,22 @@ export const registerCoreAnalysisCommands = (
|
||||
description:
|
||||
"Verify loaded native bytes, source mappings, relocations and entry",
|
||||
args: z.object({ path: z.string().describe("Local executable path") }),
|
||||
options: z.object({ provider: providerSelectionOption }),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectNativeLoadImage, () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"inspect_native_load_image",
|
||||
{},
|
||||
directAnalysisOptions(logger, undefined, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -43,6 +55,7 @@ export const registerCoreAnalysisCommands = (
|
||||
.min(1)
|
||||
.default(256)
|
||||
.describe("Requested byte count"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
@@ -51,7 +64,12 @@ export const registerCoreAnalysisCommands = (
|
||||
args.path,
|
||||
"read_bytes",
|
||||
{ address: args.address, length: options.length },
|
||||
directAnalysisOptions(logger, undefined, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -61,14 +79,22 @@ export const registerCoreAnalysisCommands = (
|
||||
path: z.string().describe("Local executable path"),
|
||||
address: z.string().describe("Exact provider memory address"),
|
||||
}),
|
||||
options: z.object({ provider: providerSelectionOption }),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.addressToFileOffset, () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
"address_to_file_offset",
|
||||
{ address: args.address },
|
||||
directAnalysisOptions(logger, undefined, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -129,6 +155,7 @@ export const registerCoreAnalysisCommands = (
|
||||
.max(5000)
|
||||
.default(1000)
|
||||
.describe("Maximum nodes on this page"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
alias: {
|
||||
@@ -153,7 +180,12 @@ export const registerCoreAnalysisCommands = (
|
||||
offset: options.offset,
|
||||
limit: options.limit,
|
||||
},
|
||||
directAnalysisOptions(logger, undefined, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -165,6 +197,7 @@ export const registerCoreAnalysisCommands = (
|
||||
options: z.object({
|
||||
type: z.string().optional().describe("Exact database type category path"),
|
||||
address: z.string().describe("Exact native address").optional(),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
@@ -178,7 +211,12 @@ export const registerCoreAnalysisCommands = (
|
||||
? {}
|
||||
: { address: options.address }),
|
||||
},
|
||||
directAnalysisOptions(logger, undefined, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -195,14 +233,22 @@ export const registerCoreAnalysisCommands = (
|
||||
path: z.string().describe("Local native executable or app path"),
|
||||
address: z.string().describe("Exact native address"),
|
||||
}),
|
||||
options: z.object({ provider: providerSelectionOption }),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, command, () =>
|
||||
runDirectAnalysis(
|
||||
args.path,
|
||||
operation,
|
||||
{ address: args.address },
|
||||
directAnalysisOptions(logger, undefined, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -239,6 +285,7 @@ const registerNativeDispatchMetadataCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load or update the local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
alias: { maxRecords: "max-records" },
|
||||
@@ -248,7 +295,12 @@ const registerNativeDispatchMetadataCommand = (
|
||||
args.path,
|
||||
"inspect_native_dispatch_metadata",
|
||||
{ max_records: options.maxRecords },
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -292,6 +344,7 @@ const registerNativeUiActionCommand = (
|
||||
.max(5_000)
|
||||
.default(500)
|
||||
.describe("Maximum returned graph edges"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
alias: {
|
||||
@@ -310,7 +363,12 @@ const registerNativeUiActionCommand = (
|
||||
max_nodes: options.maxNodes,
|
||||
max_edges: options.maxEdges,
|
||||
},
|
||||
directAnalysisOptions(logger, undefined, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -323,6 +381,7 @@ const registerCoreCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
});
|
||||
cli.command(CLI_COMMANDS.analyze, {
|
||||
@@ -348,7 +407,12 @@ const registerCoreCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
args.path,
|
||||
"binary_overview",
|
||||
{},
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -364,6 +428,7 @@ const registerCoreCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
@@ -372,7 +437,12 @@ const registerCoreCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
args.path,
|
||||
"procedure_pseudo_code",
|
||||
{ procedure: args.address },
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -382,6 +452,7 @@ const runRoutedOverview = async (
|
||||
path: string,
|
||||
options: {
|
||||
readonly snapshot?: string | undefined;
|
||||
readonly "target-format"?: "dos-com" | undefined;
|
||||
readonly provider?: string | undefined;
|
||||
},
|
||||
logger: Logger,
|
||||
@@ -389,6 +460,7 @@ const runRoutedOverview = async (
|
||||
if (
|
||||
options.provider === undefined &&
|
||||
options.snapshot === undefined &&
|
||||
options["target-format"] === undefined &&
|
||||
(await isJavaScriptApplicationPath(path))
|
||||
)
|
||||
return runCliJavaScriptApplicationAnalysis({
|
||||
@@ -398,7 +470,12 @@ const runRoutedOverview = async (
|
||||
path,
|
||||
"binary_overview",
|
||||
{},
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -429,6 +506,7 @@ const registerXrefsCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
@@ -437,7 +515,12 @@ const registerXrefsCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
args.path,
|
||||
"xrefs",
|
||||
{ address: args.address },
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -460,6 +543,7 @@ const registerTraceCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
alias: {
|
||||
@@ -474,7 +558,12 @@ const registerTraceCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
query: args.query,
|
||||
case_sensitive: options.caseSensitive,
|
||||
},
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -493,6 +582,7 @@ const registerFunctionCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
@@ -501,7 +591,12 @@ const registerFunctionCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
args.path,
|
||||
"analyze_function",
|
||||
{ procedure: args.address },
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -520,6 +615,7 @@ const registerNativeApiCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
@@ -528,7 +624,12 @@ const registerNativeApiCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
args.path,
|
||||
"inspect_native_api",
|
||||
{ procedure: args.address },
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -550,6 +651,7 @@ const registerInstructionsCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
@@ -560,7 +662,12 @@ const registerInstructionsCommand = (
|
||||
{
|
||||
procedure: args.address,
|
||||
},
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -591,6 +698,7 @@ const registerSearchCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
}),
|
||||
alias: { caseSensitive: "case-sensitive" },
|
||||
@@ -604,7 +712,12 @@ const registerSearchCommand = (cli: CliInstance, logger: Logger): void => {
|
||||
mode: options.mode,
|
||||
case_sensitive: options.caseSensitive,
|
||||
},
|
||||
directAnalysisOptions(logger, options.snapshot, options.provider),
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import {
|
||||
executableFormatHintSchema,
|
||||
type ExecutableFormatHint,
|
||||
} from "../domain/dosCom.js";
|
||||
import { analysisProviderSelectorSchema } from "../contracts/providerSelection.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -8,12 +12,19 @@ export const providerSelectionOption = analysisProviderSelectorSchema
|
||||
"Bind deep analysis to a provider ID or use deterministic auto selection",
|
||||
);
|
||||
|
||||
/** Explicit interpretation for headerless native executable formats. */
|
||||
export const formatSelectionOption = executableFormatHintSchema
|
||||
.optional()
|
||||
.describe("Explicit headerless DOS COM interpretation");
|
||||
|
||||
export const directAnalysisOptions = (
|
||||
logger: Logger,
|
||||
snapshotPath: string | undefined,
|
||||
providerId: AnalysisProviderSelector | undefined,
|
||||
formatHint?: ExecutableFormatHint,
|
||||
) => ({
|
||||
logger,
|
||||
snapshotPath,
|
||||
...(formatHint === undefined ? {} : { formatHint }),
|
||||
...(providerId === undefined ? {} : { providerId }),
|
||||
});
|
||||
|
||||
@@ -38,7 +38,7 @@ const official = <Name extends string, Schema extends z.ZodObject>(
|
||||
export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
official(
|
||||
"inspect_native_load_image",
|
||||
"Verify the provider's loaded DOS MZ image against its immutable target snapshot: complete original/modified source-byte digests, header/module file mappings and memory digests, relocations and external entry. Returns measured observations and independent checks with mismatch coordinates. Overlay and uninitialized coverage remain explicit; other formats return unsupported. Does not execute or modify the target.",
|
||||
"Verify the provider's loaded DOS MZ or explicitly selected COM image against its immutable target snapshot: complete original/modified source-byte digests, header/module file mappings and memory digests, relocations and external entry. Returns measured observations and independent checks with mismatch coordinates. COM verification includes its imposed entry register context and does not claim PSP/runtime coverage. Overlay and uninitialized coverage remain explicit; other formats return unsupported. Does not execute or modify the target.",
|
||||
z.strictObject({}),
|
||||
),
|
||||
official(
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { executableFormatHintSchema } from "../domain/dosCom.js";
|
||||
import { z } from "zod";
|
||||
import { analysisProviderSelectorSchema } from "./providerSelection.js";
|
||||
|
||||
/** Input contract for opening a target with an optional staged snapshot. */
|
||||
export const openBinaryInputSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
format: executableFormatHintSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Explicit headerless DOS COM interpretation; omission preserves header-based detection",
|
||||
),
|
||||
provider_id: analysisProviderSelectorSchema.optional(),
|
||||
snapshot_path: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
@@ -55,7 +55,7 @@ export const exportEvidenceBundleInputSchema = z.strictObject({
|
||||
export const SESSION_TOOL_CONTRACTS = [
|
||||
session(
|
||||
"open_binary",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or analysis database after validation. provider_id selects one deep provider or deterministic auto selection; the binding remains stable until close or an explicit switch, with no failure fallback. An optional analysis snapshot is imported atomically and must match the binary identity, concrete provider, and canonical analysis profile exactly.",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or analysis database after validation. format=dos-com explicitly interprets 1..65280 headerless bytes as a DOS COM analysis image; omission preserves header-based detection. provider_id selects one deep provider or deterministic auto selection; the binding remains stable until close or an explicit switch, with no failure fallback. An optional analysis snapshot is imported atomically and must match the binary identity, concrete provider, and canonical analysis profile exactly.",
|
||||
openBinaryInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -49,6 +49,7 @@ export const targetFormatSchema = z.enum([
|
||||
"elf",
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
|
||||
@@ -36,6 +36,7 @@ const formatSchema = z.enum([
|
||||
"elf",
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
|
||||
@@ -49,6 +49,7 @@ const artifactFormatSchema = z.enum([
|
||||
"elf",
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
|
||||
@@ -7,7 +7,7 @@ export type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
|
||||
/** Format and architecture facts recovered from an executable header. */
|
||||
export type ExecutableMetadata =
|
||||
| {
|
||||
readonly format: "mach-o" | "elf" | "dos-mz";
|
||||
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
|
||||
readonly architecture: BinaryArchitecture;
|
||||
readonly availableArchitectures: readonly BinaryArchitecture[];
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ type ExecutableTarget = BinaryTargetIdentity & {
|
||||
*/
|
||||
export type BinaryTarget =
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "mach-o" | "elf" | "dos-mz";
|
||||
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { executableFormatHintSchema, validateDosComLength } from "./dosCom.js";
|
||||
|
||||
describe("explicit DOS COM interpretation", () => {
|
||||
it.each([1, 0xff00])("admits the segment extent %i", (length) => {
|
||||
expect(validateDosComLength(length).ok).toBe(true);
|
||||
});
|
||||
it.each([0, -1, 0xff01, 1.5, NaN, Infinity])(
|
||||
"rejects invalid extent %i",
|
||||
(length) => {
|
||||
expect(validateDosComLength(length).ok).toBe(false);
|
||||
},
|
||||
);
|
||||
it("does not turn arbitrary format names into raw COM", () => {
|
||||
expect(executableFormatHintSchema.safeParse("dos-com").success).toBe(true);
|
||||
expect(executableFormatHintSchema.safeParse("raw").success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
import { z } from "zod";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Headerless DOS COM interpretation explicitly selected by the caller. */
|
||||
export const executableFormatHintSchema = z.literal("dos-com");
|
||||
/** Explicit executable interpretation for formats with no identifying header. */
|
||||
export type ExecutableFormatHint = z.infer<typeof executableFormatHintSchema>;
|
||||
|
||||
/** Validate the single 64 KiB COM segment, excluding its 256-byte PSP prefix. */
|
||||
export const validateDosComLength = (length: number): Result<null, string> =>
|
||||
Number.isSafeInteger(length) && length >= 1 && length <= 0xff00
|
||||
? ok(null)
|
||||
: err(
|
||||
"DOS COM requires 1..65280 file bytes (64 KiB segment minus the 256-byte PSP prefix)",
|
||||
);
|
||||
@@ -27,6 +27,7 @@ const subjectSchema = z.object({
|
||||
"elf",
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
|
||||
@@ -55,6 +55,20 @@ export const nativeLoadImageObservationSchema = z.strictObject({
|
||||
}),
|
||||
),
|
||||
entry_points: z.array(address),
|
||||
entry_context: z.array(
|
||||
z.strictObject({
|
||||
address,
|
||||
registers: z.array(
|
||||
z.strictObject({
|
||||
name: z.string().min(1),
|
||||
value_hex: z
|
||||
.string()
|
||||
.regex(/^0x[a-f0-9]+$/u)
|
||||
.nullable(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
/** Independent comparison, preserving both expectations and measured values. */
|
||||
@@ -77,7 +91,7 @@ export const nativeLoadImageSchema = z.discriminatedUnion("status", [
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.enum(["verified", "mismatch"]),
|
||||
format: z.literal("dos-mz"),
|
||||
format: z.enum(["dos-mz", "dos-com"]),
|
||||
target_sha256: digest,
|
||||
load_segment: integer.max(0xffff),
|
||||
header_bytes: integer,
|
||||
@@ -100,3 +114,5 @@ export type NativeLoadImage = z.infer<typeof nativeLoadImageSchema>;
|
||||
export type NativeLoadImageObservation = z.infer<
|
||||
typeof nativeLoadImageObservationSchema
|
||||
>;
|
||||
/** One independently compared native import fact. */
|
||||
export type NativeLoadImageCheck = z.infer<typeof nativeLoadImageCheckSchema>;
|
||||
|
||||
@@ -238,7 +238,11 @@ const familiesFor = (format: string, path: string): RuntimeFamily[] => {
|
||||
if (format === "javascript-bundle") families.add("javascript");
|
||||
if (format === "jvm-class" || /(?:^|\/)[^/]+\.class$/iu.test(path))
|
||||
families.add("jvm");
|
||||
if (["elf", "mach-o", "mach-o-universal", "pe", "dos-mz"].includes(format))
|
||||
if (
|
||||
["elf", "mach-o", "mach-o-universal", "pe", "dos-mz", "dos-com"].includes(
|
||||
format,
|
||||
)
|
||||
)
|
||||
families.add("native");
|
||||
if (format === "webassembly" || /(?:^|\/)[^/]+\.wasm$/iu.test(path))
|
||||
families.add("webassembly");
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
|
||||
serverSdkVersion: "2.3.1",
|
||||
clientSdkVersion: "2.3.1",
|
||||
coreSdkVersion: "2.3.1",
|
||||
skillVersion: "26",
|
||||
skillVersion: "27",
|
||||
} as const;
|
||||
|
||||
@@ -27,6 +27,8 @@ export const resolveGhidraAnalysisProfile = (
|
||||
);
|
||||
const provider = { ...identity, version: installation.providerVersion };
|
||||
const dosMz = target.format === "dos-mz";
|
||||
const dosCom = target.format === "dos-com";
|
||||
const dos = dosMz || dosCom;
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
profile: createAnalysisProfile(provider, {
|
||||
@@ -37,26 +39,47 @@ export const resolveGhidraAnalysisProfile = (
|
||||
...(target.availableArchitectures ?? []),
|
||||
].sort(),
|
||||
import_mode: "ephemeral-read-only",
|
||||
load_image_observations: "source-mappings-entry-context-v2",
|
||||
function_body_evidence: "complete-inclusive-ranges-v1",
|
||||
...(dosMz
|
||||
? { load_image_evidence: "independent-mz-mapping-relocations-v1" }
|
||||
...(dos
|
||||
? {
|
||||
load_image_evidence: dosCom
|
||||
? "independent-com-mapping-context-v1"
|
||||
: "independent-mz-mapping-relocations-v1",
|
||||
}
|
||||
: {}),
|
||||
jump_table_evidence: "typed-case-default-blocks-v1",
|
||||
decompiler_jump_loads: true,
|
||||
loader: dosMz ? "MzLoader" : "auto-from-header",
|
||||
language_id: dosMz ? "x86:LE:16:Real Mode" : "auto-from-header",
|
||||
compiler_spec_id: dosMz ? "default" : "auto-default",
|
||||
...(dosMz
|
||||
loader: dosMz
|
||||
? "MzLoader"
|
||||
: dosCom
|
||||
? "BinaryLoader"
|
||||
: "auto-from-header",
|
||||
language_id: dos ? "x86:LE:16:Real Mode" : "auto-from-header",
|
||||
compiler_spec_id: dos ? "default" : "auto-default",
|
||||
...(dos
|
||||
? {
|
||||
load_segment: "0x1000",
|
||||
address_coordinates: "linear-byte-offset",
|
||||
}
|
||||
: {}),
|
||||
...(dosCom
|
||||
? {
|
||||
entry_offset: "0x100",
|
||||
register_context: {
|
||||
CS: "0x1000",
|
||||
DS: "0x1000",
|
||||
ES: "0x1000",
|
||||
SS: "0x1000",
|
||||
},
|
||||
entry_seed: "external-entry-and-function-before-analysis-v1",
|
||||
}
|
||||
: {}),
|
||||
analyzer_preset: "ghidra-default",
|
||||
}),
|
||||
compatibility: {
|
||||
languageId: dosMz ? "x86:LE:16:Real Mode" : "auto",
|
||||
compilerSpecId: dosMz ? "default" : "auto",
|
||||
languageId: dos ? "x86:LE:16:Real Mode" : "auto",
|
||||
compilerSpecId: dos ? "default" : "auto",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { attestGhidraDosComLoadImage } from "./GhidraLoadImageValues.js";
|
||||
import { fixtureDosComLoadImage } from "./GhidraLoadImage.fixture.js";
|
||||
import type { NativeLoadImageObservation } from "../domain/nativeLoadImage.js";
|
||||
|
||||
const mutations: ReadonlyArray<
|
||||
readonly [string, (o: NativeLoadImageObservation) => void]
|
||||
> = [
|
||||
[
|
||||
"memory bytes",
|
||||
(o) => {
|
||||
if (o.mappings[0]) o.mappings[0].sha256 = "f".repeat(64);
|
||||
},
|
||||
],
|
||||
[
|
||||
"file mapping",
|
||||
(o) => {
|
||||
if (o.mappings[0]) o.mappings[0].file_offset = 1;
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing mapping",
|
||||
(o) => {
|
||||
o.mappings = [];
|
||||
},
|
||||
],
|
||||
[
|
||||
"duplicate mapping",
|
||||
(o) => {
|
||||
if (o.mappings[0]) o.mappings.push(structuredClone(o.mappings[0]));
|
||||
},
|
||||
],
|
||||
[
|
||||
"entry",
|
||||
(o) => {
|
||||
o.entry_points = ["0x10000"];
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing context",
|
||||
(o) => {
|
||||
o.entry_context = [];
|
||||
},
|
||||
],
|
||||
[
|
||||
"wrong context",
|
||||
(o) => {
|
||||
if (o.entry_context[0]?.registers[0])
|
||||
o.entry_context[0].registers[0].value_hex = "0x0";
|
||||
},
|
||||
],
|
||||
[
|
||||
"language",
|
||||
(o) => {
|
||||
o.language_id = "x86:LE:32:default";
|
||||
},
|
||||
],
|
||||
[
|
||||
"source identity",
|
||||
(o) => {
|
||||
if (o.source_files[0]) o.source_files[0].original_sha256 = "f".repeat(64);
|
||||
},
|
||||
],
|
||||
[
|
||||
"modified source",
|
||||
(o) => {
|
||||
if (o.source_files[0]) o.source_files[0].modified_sha256 = "f".repeat(64);
|
||||
},
|
||||
],
|
||||
[
|
||||
"unexpected fixup",
|
||||
(o) => {
|
||||
o.relocations.push({
|
||||
address: "0x10100",
|
||||
segment: 0x1000,
|
||||
offset: 0x100,
|
||||
status: "APPLIED",
|
||||
type: 0,
|
||||
values: [],
|
||||
original_bytes_hex: null,
|
||||
memory_bytes_hex: null,
|
||||
});
|
||||
},
|
||||
],
|
||||
];
|
||||
describe("COM independent load-image checks", () => {
|
||||
it("verifies all bytes and the imposed entry context without a PSP claim", () => {
|
||||
const f = fixtureDosComLoadImage();
|
||||
const result = attestGhidraDosComLoadImage(
|
||||
f.bytes,
|
||||
f.sha256,
|
||||
f.observation,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
status: "verified",
|
||||
format: "dos-com",
|
||||
header_bytes: 0,
|
||||
module_bytes: 4,
|
||||
overlay_bytes: 0,
|
||||
entry: {
|
||||
relative_segment: 0,
|
||||
offset: 0x100,
|
||||
linear_address: "0x10100",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
it.each(mutations)("retains mismatch evidence for %s", (_name, damage) => {
|
||||
const f = fixtureDosComLoadImage();
|
||||
damage(f.observation);
|
||||
const result = attestGhidraDosComLoadImage(
|
||||
f.bytes,
|
||||
f.sha256,
|
||||
f.observation,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { status: "mismatch", observations: f.observation },
|
||||
});
|
||||
});
|
||||
it("rejects stale snapshot identity", () => {
|
||||
const f = fixtureDosComLoadImage();
|
||||
expect(
|
||||
attestGhidraDosComLoadImage(f.bytes, "f".repeat(64), f.observation).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,7 @@ export interface GhidraHeadlessLauncherOptions {
|
||||
readonly comSpec?: string;
|
||||
/** Select the admitted 16-bit real-mode MZ import instead of auto-detection. */
|
||||
readonly dosMz?: true;
|
||||
readonly dosCom?: true;
|
||||
}
|
||||
|
||||
/** Launch Ghidra without copying scripts into or modifying its installation. */
|
||||
@@ -111,6 +112,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
descriptorPath: paths.descriptorPath,
|
||||
ghidraLogPath: paths.ghidraLogPath,
|
||||
scriptLogPath: paths.scriptLogPath,
|
||||
...(this.options.dosCom === undefined
|
||||
? {}
|
||||
: { dosCom: this.options.dosCom }),
|
||||
...(this.options.dosMz === undefined
|
||||
? {}
|
||||
: { dosMz: this.options.dosMz }),
|
||||
@@ -267,6 +271,7 @@ export interface GhidraHeadlessArgumentOptions {
|
||||
readonly ghidraLogPath: string;
|
||||
readonly scriptLogPath: string;
|
||||
readonly dosMz?: true;
|
||||
readonly dosCom?: true;
|
||||
}
|
||||
|
||||
/** Build the complete read-only headless invocation in deterministic order. */
|
||||
@@ -286,7 +291,18 @@ export const ghidraHeadlessArguments = (
|
||||
"-cspec",
|
||||
"default",
|
||||
]
|
||||
: []),
|
||||
: options.dosCom === true
|
||||
? [
|
||||
"-loader",
|
||||
"BinaryLoader",
|
||||
"-loader-baseAddr",
|
||||
"1000:0100",
|
||||
"-processor",
|
||||
"x86:LE:16:Real Mode",
|
||||
"-cspec",
|
||||
"default",
|
||||
]
|
||||
: []),
|
||||
"-readOnly",
|
||||
"-deleteProject",
|
||||
"-log",
|
||||
@@ -295,6 +311,9 @@ export const ghidraHeadlessArguments = (
|
||||
options.scriptLogPath,
|
||||
"-scriptPath",
|
||||
dirname(options.bridgeScriptPath),
|
||||
...(options.dosCom === true
|
||||
? ["-preScript", "ReaGhidraPrepareCom.java"]
|
||||
: []),
|
||||
"-postScript",
|
||||
basename(options.bridgeScriptPath),
|
||||
options.descriptorPath,
|
||||
|
||||
@@ -92,7 +92,63 @@ export const fixtureDosLoadImage = (): {
|
||||
memory_bytes_hex: "0410",
|
||||
},
|
||||
],
|
||||
entry_context: [],
|
||||
entry_points: ["0x10000"],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Source-owned headerless COM image and measured real-mode import facts. */
|
||||
export const fixtureDosComLoadImage = (): {
|
||||
bytes: Buffer;
|
||||
sha256: string;
|
||||
observation: NativeLoadImageObservation;
|
||||
} => {
|
||||
const bytes = Buffer.from("b83412c3", "hex");
|
||||
const digest = hash(bytes);
|
||||
return {
|
||||
bytes,
|
||||
sha256: digest,
|
||||
observation: {
|
||||
executable_format: "Raw Binary",
|
||||
language_id: "x86:LE:16:Real Mode",
|
||||
compiler_spec_id: "default",
|
||||
image_base: "0x0",
|
||||
default_address_space: "ram",
|
||||
source_files: [
|
||||
{
|
||||
name: "fixture.com",
|
||||
size: bytes.length,
|
||||
original_sha256: digest,
|
||||
modified_sha256: digest,
|
||||
},
|
||||
],
|
||||
mappings: [
|
||||
{
|
||||
block: "ram",
|
||||
start: "0x10100",
|
||||
end: "0x10103",
|
||||
address_space: "ram",
|
||||
initialized: true,
|
||||
loaded: true,
|
||||
overlay: false,
|
||||
length: bytes.length,
|
||||
source_file_index: 0,
|
||||
file_offset: 0,
|
||||
sha256: digest,
|
||||
},
|
||||
],
|
||||
relocations: [],
|
||||
entry_points: ["0x10100"],
|
||||
entry_context: [
|
||||
{
|
||||
address: "0x10100",
|
||||
registers: ["CS", "DS", "ES", "SS"].map((name) => ({
|
||||
name,
|
||||
value_hex: "0x1000",
|
||||
})),
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -2,10 +2,12 @@ import { createHash } from "node:crypto";
|
||||
import {
|
||||
nativeLoadImageSchema,
|
||||
type NativeLoadImage,
|
||||
type NativeLoadImageCheck,
|
||||
type NativeLoadImageObservation,
|
||||
} from "../domain/nativeLoadImage.js";
|
||||
import { parseDosMzHeader, type DosMzHeader } from "../domain/dosMz.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { validateDosComLength } from "../domain/dosCom.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
const sha256 = (bytes: Buffer): string =>
|
||||
@@ -58,7 +60,7 @@ export const attestGhidraDosLoadImage = (
|
||||
.toString("hex"),
|
||||
});
|
||||
}
|
||||
const checks: Extract<NativeLoadImage, { format: "dos-mz" }>["checks"] = [];
|
||||
const checks: NativeLoadImageCheck[] = [];
|
||||
const check = (
|
||||
name: string,
|
||||
expected: JsonValue,
|
||||
@@ -120,7 +122,7 @@ export const attestGhidraDosLoadImage = (
|
||||
rows(observations.relocations),
|
||||
);
|
||||
|
||||
checkMappings(header, loadSegment, bytes, modified, observations, check);
|
||||
checkMappings(header, loadSegment * 16, bytes, modified, observations, check);
|
||||
return ok(
|
||||
nativeLoadImageSchema.parse({
|
||||
status: checks.every((item) => item.matched) ? "verified" : "mismatch",
|
||||
@@ -143,8 +145,8 @@ export const attestGhidraDosLoadImage = (
|
||||
};
|
||||
|
||||
const checkMappings = (
|
||||
header: DosMzHeader,
|
||||
loadSegment: number,
|
||||
header: Pick<DosMzHeader, "headerBytes" | "imageBytes">,
|
||||
loadBase: number,
|
||||
bytes: Buffer,
|
||||
modified: Buffer,
|
||||
observations: NativeLoadImageObservation,
|
||||
@@ -212,19 +214,13 @@ const checkMappings = (
|
||||
? null
|
||||
: headerMapping
|
||||
? `HEADER:${address(start)}`
|
||||
: address(loadSegment * 16 + start - header.headerBytes);
|
||||
: address(loadBase + start - header.headerBytes);
|
||||
const expectedEnd =
|
||||
start === null
|
||||
? null
|
||||
: headerMapping
|
||||
? `HEADER:${address(start + mapping.length - 1)}`
|
||||
: address(
|
||||
loadSegment * 16 +
|
||||
start -
|
||||
header.headerBytes +
|
||||
mapping.length -
|
||||
1,
|
||||
);
|
||||
: address(loadBase + start - header.headerBytes + mapping.length - 1);
|
||||
check(`${at}.start`, expectedStart, mapping.start, start, mapping.start);
|
||||
check(`${at}.end`, expectedEnd, mapping.end, start, mapping.end);
|
||||
check(
|
||||
@@ -247,3 +243,85 @@ const checkMappings = (
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
/** Verify the explicit DOS COM interpretation against measured bytes and context. */
|
||||
export const attestGhidraDosComLoadImage = (
|
||||
bytes: Buffer,
|
||||
targetSha256: string,
|
||||
observations: NativeLoadImageObservation,
|
||||
): Result<NativeLoadImage, string> => {
|
||||
if (sha256(bytes) !== targetSha256)
|
||||
return err("Ghidra COM snapshot digest does not match the admitted target");
|
||||
const length = validateDosComLength(bytes.length);
|
||||
if (!length.ok) return length;
|
||||
const checks: NativeLoadImageCheck[] = [];
|
||||
const check = (
|
||||
name: string,
|
||||
expected: JsonValue,
|
||||
observed: JsonValue,
|
||||
fileOffset: number | null = null,
|
||||
location: string | null = null,
|
||||
): void => {
|
||||
checks.push({
|
||||
name,
|
||||
matched: JSON.stringify(expected) === JSON.stringify(observed),
|
||||
expected,
|
||||
observed,
|
||||
file_offset: fileOffset,
|
||||
address: location,
|
||||
});
|
||||
};
|
||||
const source = observations.source_files[0];
|
||||
check("executable_format", "Raw Binary", observations.executable_format);
|
||||
check("language_id", "x86:LE:16:Real Mode", observations.language_id);
|
||||
check("compiler_spec_id", "default", observations.compiler_spec_id);
|
||||
check("image_base", "0x0", observations.image_base);
|
||||
check("default_address_space", "ram", observations.default_address_space);
|
||||
check("source_file_count", 1, observations.source_files.length);
|
||||
check("source_file_size", bytes.length, source?.size ?? null);
|
||||
check("original_file_sha256", targetSha256, source?.original_sha256 ?? null);
|
||||
check("modified_file_sha256", targetSha256, source?.modified_sha256 ?? null);
|
||||
check("entry_points", ["0x10100"], [...observations.entry_points].sort());
|
||||
check(
|
||||
"entry_context",
|
||||
[
|
||||
{
|
||||
address: "0x10100",
|
||||
registers: ["CS", "DS", "ES", "SS"].map((name) => ({
|
||||
name,
|
||||
value_hex: "0x1000",
|
||||
})),
|
||||
},
|
||||
],
|
||||
observations.entry_context,
|
||||
);
|
||||
check("relocation_records", [], observations.relocations);
|
||||
checkMappings(
|
||||
{ headerBytes: 0, imageBytes: bytes.length },
|
||||
0x10100,
|
||||
bytes,
|
||||
bytes,
|
||||
observations,
|
||||
check,
|
||||
);
|
||||
return ok(
|
||||
nativeLoadImageSchema.parse({
|
||||
status: checks.every((item) => item.matched) ? "verified" : "mismatch",
|
||||
format: "dos-com",
|
||||
target_sha256: targetSha256,
|
||||
load_segment: 0x1000,
|
||||
header_bytes: 0,
|
||||
module_bytes: bytes.length,
|
||||
overlay_bytes: 0,
|
||||
entry: { relative_segment: 0, offset: 0x100, linear_address: "0x10100" },
|
||||
observations,
|
||||
checks,
|
||||
limitations: [
|
||||
"DOS COM is a headerless interpretation explicitly selected by the caller, not format identification from file bytes.",
|
||||
"Verification covers complete original/modified source identity, mapped file bytes, entry and measured CS/DS/ES/SS entry context. Context 0x1000 is imposed for analysis; it is not an observed running process.",
|
||||
"The PSP, initial stack contents/registers, DOS interrupts, PC-98 devices and runtime behavior are not modeled or verified. No original executable bytes are changed.",
|
||||
"Mapping ends are inclusive; a mismatching digest identifies its source range, not the first differing byte.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -20,7 +20,10 @@ import {
|
||||
nativeLoadImageObservationSchema,
|
||||
nativeLoadImageSchema,
|
||||
} from "../domain/nativeLoadImage.js";
|
||||
import { attestGhidraDosLoadImage } from "./GhidraLoadImageValues.js";
|
||||
import {
|
||||
attestGhidraDosLoadImage,
|
||||
attestGhidraDosComLoadImage,
|
||||
} from "./GhidraLoadImageValues.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
@@ -219,6 +222,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
new URL("../../bridge/ghidra/ReaGhidraBridge.java", import.meta.url),
|
||||
),
|
||||
...(target.format === "dos-mz" ? { dosMz: true } : {}),
|
||||
...(target.format === "dos-com" ? { dosCom: true } : {}),
|
||||
platform: installation.platform,
|
||||
}),
|
||||
targetPath: target.path,
|
||||
@@ -229,7 +233,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
: "unix-socket",
|
||||
providerVersion: prerequisites.value.providerVersion,
|
||||
profileDigest: committedProfile.digest,
|
||||
...(target.format === "dos-mz"
|
||||
...(["dos-mz", "dos-com"].includes(target.format)
|
||||
? {
|
||||
expectedLanguageId: "x86:LE:16:Real Mode",
|
||||
expectedCompilerSpecId: "default",
|
||||
@@ -287,12 +291,12 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
const observations = nativeLoadImageObservationSchema.parse(
|
||||
result.value,
|
||||
);
|
||||
if (target.format !== "dos-mz") {
|
||||
if (target.format !== "dos-mz" && target.format !== "dos-com") {
|
||||
normalized = jsonValueSchema.parse(
|
||||
nativeLoadImageSchema.parse({
|
||||
status: "unsupported",
|
||||
reason:
|
||||
"Independent load-image verification currently supports DOS MZ targets only.",
|
||||
"Independent load-image verification currently supports DOS MZ and explicit DOS COM targets only.",
|
||||
observations,
|
||||
limitations: [
|
||||
"Other formats expose measured mappings and source identities; no format-specific verification was performed.",
|
||||
@@ -312,11 +316,11 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
const snapshot = await client.readTargetSnapshot();
|
||||
if (!snapshot.ok)
|
||||
return err(projectSessionError(operation, snapshot.error));
|
||||
const attested = attestGhidraDosLoadImage(
|
||||
snapshot.value,
|
||||
target.sha256 ?? "",
|
||||
observations,
|
||||
);
|
||||
const attested = (
|
||||
target.format === "dos-com"
|
||||
? attestGhidraDosComLoadImage
|
||||
: attestGhidraDosLoadImage
|
||||
)(snapshot.value, target.sha256 ?? "", observations);
|
||||
if (!attested.ok)
|
||||
return err(
|
||||
new ProviderAdapterError("ghidra", operation, {
|
||||
|
||||
@@ -57,7 +57,7 @@ export const limitationsFor = (operation: string): readonly string[] => {
|
||||
case "inspect_native_load_image":
|
||||
return [
|
||||
...common,
|
||||
"Independent verification currently supports DOS MZ only. Measured source mappings use inclusive end addresses and complete region digests; no target execution or project mutation occurs.",
|
||||
"Independent verification supports DOS MZ and explicitly selected COM, including measured COM entry context. Measured source mappings use inclusive end addresses and complete region digests; no target execution or project mutation occurs.",
|
||||
];
|
||||
case "read_bytes":
|
||||
return [
|
||||
|
||||
@@ -89,6 +89,7 @@ export const hopperLoaderArgsForTarget = (
|
||||
case "pe":
|
||||
return ok(["-l", "WinPE", flag]);
|
||||
case "dos-mz":
|
||||
case "dos-com":
|
||||
return err(
|
||||
new ProviderAdapterError("hopper", "resolve_analysis_profile"),
|
||||
);
|
||||
|
||||
@@ -157,11 +157,12 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
reason: null,
|
||||
diagnostics,
|
||||
};
|
||||
if (target.format === "dos-mz")
|
||||
if (target.format === "dos-mz" || target.format === "dos-com")
|
||||
return {
|
||||
status: "unsupported",
|
||||
code: "target_format_unsupported",
|
||||
reason: "DOS MZ analysis requires the Ghidra 16-bit real-mode adapter.",
|
||||
reason:
|
||||
"DOS MZ/COM analysis requires the Ghidra 16-bit real-mode adapter.",
|
||||
diagnostics,
|
||||
};
|
||||
return {
|
||||
|
||||
@@ -173,6 +173,7 @@ const registerOpenLifecycleTool = ({
|
||||
const opened = await logToolExecution(logger, openContract.name, () =>
|
||||
session.open(input.path, {
|
||||
signal: context.mcpReq.signal,
|
||||
...(input.format === undefined ? {} : { formatHint: input.format }),
|
||||
...(input.provider_id === undefined
|
||||
? {}
|
||||
: { providerId: input.provider_id }),
|
||||
|
||||
Reference in New Issue
Block a user