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:
N0zoM1z0
2026-10-06 16:26:40 +08:00
committed by GitHub
parent d565ecdc25
commit 5bcb6645b5
45 changed files with 1104 additions and 75 deletions
+31 -8
View File
@@ -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",
},
}),
);
+129
View File
@@ -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);
});
});
+20 -1
View File
@@ -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,
+56
View File
@@ -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",
})),
},
],
},
};
};
+90 -12
View File
@@ -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.",
],
}),
);
};
+13 -9
View File
@@ -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, {
+1 -1
View File
@@ -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 [