feat(ghidra): support raw NMOS 6502 analysis (#2079)

* feat(ghidra): admit raw NMOS 6502 analysis

* test(ghidra): require verified POSIX verifier cleanup

* test(ghidra): verify 6502 low-memory raw imports

* docs(skill): document raw NMOS 6502 support

* fix(ghidra): preserve requested Windows raw source paths

* docs(ghidra): include raw 6502 in Windows installation scope

* test(ghidra): verify Windows raw junction rejection through CLI and MCP

* fix(validation): make fixtures portable and preserve explicit Codex home

* fix(ghidra): attest raw mapping state and address space

* fix(ghidra): align diagnostics and regression groups

* fix(ghidra): bind raw attestation to language address space

* chore(ghidra): avoid verifier insertion conflict

* docs(ghidra): align linked raw admission guides

* fix(ghidra): retain 6502 verifier workspace on failure

* test(ghidra): isolate Windows authority doctor fixture

* fix(binary): re-admit Windows raw paths on session reopen

* test(binary): require fresh provider execution after path change

* Constrain 6502 to raw lifecycle and snapshot targets

* Bypass saved reads for unadmitted Windows paths

* Guard direct CLI snapshot replay on Windows paths

* fix(snapshot): gate Windows Ghidra replay on native admission

* fix(snapshot): constrain nested 6502 subjects to raw images

* test: make dyld slice fixtures portable
This commit is contained in:
记得吃中饭
2026-10-13 21:13:01 +08:00
committed by GitHub
parent 352c46aa75
commit 9c14999efd
54 changed files with 1650 additions and 197 deletions
+7 -5
View File
@@ -76,6 +76,8 @@ export const parseBinaryTarget = async (
await access(candidate, constants.R_OK);
throwIfTargetResolutionCancelled(signal);
const canonical = await realpath(candidate);
// Windows native admission must inspect the caller-selected reparse components.
const sourcePath = process.platform === "win32" ? candidate : canonical;
throwIfTargetResolutionCancelled(signal);
const resolved = await resolveAppBundle(canonical);
throwIfTargetResolutionCancelled(signal);
@@ -113,7 +115,7 @@ export const parseBinaryTarget = async (
);
return ok({
path,
sourcePath: canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
format: "raw-binary",
@@ -152,7 +154,7 @@ export const parseBinaryTarget = async (
);
return ok({
path,
sourcePath: canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
format: "dos-com",
@@ -166,7 +168,7 @@ export const parseBinaryTarget = async (
)
return ok({
path,
sourcePath: process.platform === "win32" ? candidate : canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "database",
format: "analysis-database",
@@ -175,7 +177,7 @@ export const parseBinaryTarget = async (
if (artifactFormat !== undefined) {
const identity = {
path,
sourcePath: process.platform === "win32" ? candidate : canonical,
sourcePath,
sha256: await sha256Handle(handle, path, metadata, signal),
};
return isArchiveFormat(artifactFormat)
@@ -195,7 +197,7 @@ export const parseBinaryTarget = async (
);
return ok({
path,
sourcePath: process.platform === "win32" ? candidate : canonical,
sourcePath,
...bundle,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
+6
View File
@@ -23,6 +23,7 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { access } from "node:fs/promises";
import { readAnalysisSnapshot } from "./binary/AnalysisSnapshotFiles.js";
import { requiresNativeSourceAdmissionBeforeReplay } from "./binary/AnalysisSnapshotCache.js";
import { parseBinaryTarget } from "./BinaryTargetResolver.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
@@ -254,9 +255,14 @@ const runAnalysis = async (
const route = preview.value.route;
const bindingProfile = route.profile ?? undefined;
const evidenceProfile = analysisProfileForRoute(route, tool);
// A parsed Windows path does not prove Ghidra's native snapshot owner
// admitted the selected source; CLI replay must wait for that client.
if (
bindingProfile !== undefined &&
evidenceProfile !== undefined &&
!requiresNativeSourceAdmissionBeforeReplay(
route.binding?.identity.id,
) &&
allowsSnapshotReplay(route, tool)
) {
const cached = snapshotEvidenceForQuery(snapshot, {
@@ -84,6 +84,11 @@ export const isSnapshotCacheable = (
descriptor.effects.mayWriteFilesystem === false) &&
descriptor.effects.changesPermissions === false;
/** Windows Ghidra must admit the selected source through its native snapshot owner. */
export const requiresNativeSourceAdmissionBeforeReplay = (
providerId: string | undefined,
): boolean => process.platform === "win32" && providerId === "ghidra";
/** Bounded in-memory cache for one immutable binary identity. */
export class AnalysisSnapshotCache {
readonly #entries = new Map<string, AnalysisSnapshotEntry>();
+12
View File
@@ -58,6 +58,7 @@ interface SessionBinding {
readonly profile: AnalysisProfileCommitment | null;
readonly route: SessionProviderRoute;
readonly runId: string;
nativeSourceAdmitted: boolean;
}
/**
@@ -323,6 +324,7 @@ export class BinarySession
profile,
route,
runId,
nativeSourceAdmitted: false,
};
this.#clearRuntimeAvailability();
this.resetSnapshotInvalidation();
@@ -609,6 +611,7 @@ export class BinarySession
active: this.#active,
operation: name,
parameters: arguments_,
nativeSourceAdmitted: this.#active?.nativeSourceAdmitted === true,
unboundOperationError: (operation, route) =>
this.#providerRouter.unboundOperationError(operation, route),
lookupSnapshot: (target, profile, operation, parameters) =>
@@ -645,6 +648,14 @@ export class BinarySession
},
})
: profiled;
// A successful Ghidra operation proves this client's native source snapshot
// was admitted; a composite health response and parsed path do not.
if (
execution.ok &&
capability.provider.id === "ghidra" &&
this.#active === active
)
this.#active.nativeSourceAdmitted = true;
this.#observeRuntimeAvailability(name, execution);
if (
execution.ok &&
@@ -838,6 +849,7 @@ export class BinarySession
profile: previous.profile,
route: previous.route,
runId,
nativeSourceAdmitted: false,
};
return ok(null);
}
@@ -13,7 +13,10 @@ import type {
AnalysisOperation,
CapabilityDescriptor,
} from "../AnalysisProvider.js";
import { isSnapshotCacheable } from "./AnalysisSnapshotCache.js";
import {
isSnapshotCacheable,
requiresNativeSourceAdmissionBeforeReplay,
} from "./AnalysisSnapshotCache.js";
import type { SessionProviderRoute } from "./SessionProviderRouter.js";
interface ActiveExecutionBinding {
@@ -35,6 +38,7 @@ interface PrepareSessionExecutionInput {
readonly active: ActiveExecutionBinding | undefined;
readonly operation: AnalysisOperation;
readonly parameters: Readonly<Record<string, JsonValue>>;
readonly nativeSourceAdmitted: boolean;
readonly unboundOperationError: (
operation: AnalysisOperation,
route: SessionProviderRoute,
@@ -55,6 +59,7 @@ export const prepareSessionExecution = (
active,
operation,
parameters,
nativeSourceAdmitted,
unboundOperationError,
lookupSnapshot,
} = input;
@@ -79,9 +84,12 @@ export const prepareSessionExecution = (
const cacheable =
profile !== undefined &&
isSnapshotCacheable(operation, capability, parameters);
const cached = cacheable
? lookupSnapshot(active.target, profile, operation, parameters)
: undefined;
const cached =
cacheable &&
(!requiresNativeSourceAdmissionBeforeReplay(capability.provider.id) ||
nativeSourceAdmitted)
? lookupSnapshot(active.target, profile, operation, parameters)
: undefined;
return ok({ active, capability, profile, cacheable, cached });
};
+12 -6
View File
@@ -92,9 +92,7 @@ export const resolveSessionTarget = async (
input: ResolveSessionTargetInput,
): Promise<Result<ResolvedSessionOpen, AnalysisError>> => {
const { router, current, target, options } = input;
const sameTarget =
current?.target.path === target.path &&
snapshotMatchesTarget(snapshotTarget(current.target), target);
const sameTarget = sameSessionTarget(current?.target, target);
const resolvedRoute =
sameTarget && options.providerId === undefined && current !== undefined
? ({ ok: true, value: current.route } as const)
@@ -113,9 +111,7 @@ export const validateResolvedSessionTarget = (
},
): Result<ResolvedSessionOpen, AnalysisError> => {
const { current, target, route, options, stagedSnapshotMatches } = input;
const sameTarget =
current?.target.path === target.path &&
snapshotMatchesTarget(snapshotTarget(current.target), target);
const sameTarget = sameSessionTarget(current?.target, target);
const snapshotError = validateSnapshot({
snapshot: options.snapshot,
target,
@@ -127,6 +123,16 @@ export const validateResolvedSessionTarget = (
return { ok: true, value: { target, route, sameTarget } };
};
const sameSessionTarget = (
current: BinaryTarget | undefined,
target: BinaryTarget,
): boolean =>
current !== undefined &&
current.path === target.path &&
// Native admission is bound to the requested path, not just its realpath.
(current.sourcePath ?? current.path) === (target.sourcePath ?? target.path) &&
snapshotMatchesTarget(snapshotTarget(current), target);
interface ValidateSnapshotInput {
readonly snapshot: AnalysisSnapshot | undefined;
readonly target: BinaryTarget;
@@ -6,6 +6,34 @@ import { z } from "zod";
import { toolContract } from "./toolContracts.js";
import { toolOutputSchemaWithMetadata } from "./toolSchemaMetadata.js";
import { createEvidence } from "../domain/evidence.js";
it.each(["draft-2020-12", "draft-07"] as const)(
"advertises the raw-only 6502 Evidence subject constraint in %s",
(target) => {
const valid = createEvidence(
{
path: "/fixture/image.bin",
sha256: "a".repeat(64),
format: "raw-binary",
architecture: "6502",
},
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "address_name", parameters: {}, result: "entry" },
);
const advertised = toolOutputSchemaWithMetadata(
toolContract("address_name"),
)["~standard"].jsonSchema.output({ target });
const validate = new AjvJsonSchemaValidator().getValidator(advertised);
expect(validate(valid).valid).toBe(true);
expect(
validate({
...valid,
subject: { ...valid.subject, format: "pe" },
}).valid,
).toBe(false);
},
);
it("keeps dialect-specific validators distinct after JSON schema serialization", () => {
const contract = {
+1 -1
View File
@@ -444,11 +444,11 @@ const lifecycleTargetFields = {
path: z.string(),
kind: targetKindSchema,
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
};
const detectedLifecycleTargetSchema = z.object({
...lifecycleTargetFields,
format: targetFormatSchema.exclude(["raw-binary"]),
architecture: z.enum(BINARY_ARCHITECTURES).exclude(["6502"]).nullable(),
});
const rawLifecycleTargetSchema = z.object({
...lifecycleTargetFields,
+65 -2
View File
@@ -52,7 +52,7 @@ const snapshotWithHistoricalEvidence = () => {
};
return {
current,
snapshot: {
snapshot: analysisSnapshotSchema.parse({
target,
binding,
entries: [entry],
@@ -66,11 +66,32 @@ const snapshotWithHistoricalEvidence = () => {
result: { summary: "unprofiled" },
}),
]),
} satisfies AnalysisSnapshot,
}),
};
};
describe("analysis snapshot target identity", () => {
it("keeps 6502 confined to executable raw snapshots", () => {
const target = {
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
kind: "executable",
architecture: "6502",
};
expect(
analysisSnapshotSchema.shape.target.safeParse({
...target,
format: "pe",
}).success,
).toBe(false);
expect(
analysisSnapshotSchema.shape.target.safeParse({
...target,
format: "raw-binary",
entry_point: "0x8001",
}).success,
).toBe(true);
});
it("partitions raw snapshots and query identities by the canonical entry", () => {
const target: BinaryTarget = {
path: "/fixture/image.bin",
@@ -120,6 +141,48 @@ describe("analysis snapshot target identity", () => {
});
});
describe("analysis snapshot nested subject contract", () => {
it("rejects raw-only 6502 in nested detected execution subjects", () => {
const { snapshot } = snapshotWithHistoricalEvidence();
const entry = snapshot.entries[0];
if (entry === undefined) throw new Error("Fixture has no snapshot entry");
const malformedSubject = {
...entry.execution.subject,
format: "pe",
architecture: "6502",
};
expect(
analysisSnapshotSchema.safeParse({
...snapshot,
entries: [
{
...entry,
execution: {
...entry.execution,
subject: malformedSubject,
},
},
],
}).success,
).toBe(false);
expect(
analysisSnapshotSchema.safeParse({
...snapshot,
workflow_entries: [
{
...entry,
execution: {
...entry.execution,
analysis_profile: snapshot.binding.analysis_profile,
subject: malformedSubject,
},
},
],
}).success,
).toBe(false);
});
});
describe("analysis snapshot contract", () => {
it.each([
["dos-mz", "x86"],
+47 -28
View File
@@ -41,7 +41,10 @@ import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
import { rawBinaryEntryPointSchema } from "./rawBinary.js";
import {
binaryArchitectureSchema,
rawBinaryEntryPointSchema,
} from "./rawBinary.js";
import {
relationshipCoverageSchema,
type RelationshipCoverage,
@@ -73,20 +76,30 @@ const formatSchema = z.enum([
"source-map",
]);
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
const subjectSchema = z.object({
const subjectBaseSchema = z.object({
path: localPathStringSchema,
sha256: digestSchema,
format: z.enum([
...formatSchema.options,
"hopper",
"directory",
"file",
"unknown",
"javascript-bundle",
"entitlements",
]),
architecture: architectureSchema.nullable(),
});
const subjectFormatSchema = z.enum([
...formatSchema.options,
"hopper",
"directory",
"file",
"unknown",
"javascript-bundle",
"entitlements",
]);
// Snapshot entries retain the same raw-only architecture boundary as targets.
const subjectSchema = z.discriminatedUnion("format", [
subjectBaseSchema.extend({
format: subjectFormatSchema.exclude(["raw-binary"]),
architecture: architectureSchema.exclude(["6502"]).nullable(),
}),
subjectBaseSchema.extend({
format: z.literal("raw-binary"),
architecture: architectureSchema.nullable(),
}),
]);
const targetIdentitySchema = z.object({
sha256: digestSchema,
kind: kindSchema,
@@ -97,9 +110,12 @@ const targetSchema = z.discriminatedUnion("format", [
format: z.enum(
formatSchema.options.filter((format) => format !== "raw-binary"),
),
architecture: architectureSchema.exclude(["6502"]).nullable(),
}),
targetIdentitySchema.extend({
format: z.literal("raw-binary"),
kind: z.literal("executable"),
architecture: binaryArchitectureSchema,
entry_point: rawBinaryEntryPointSchema,
}),
]);
@@ -332,18 +348,21 @@ const canonicalJson = (value: unknown): string => {
};
/** Project a binary into the path-free identity used for cache invalidation. */
export const snapshotTarget = (
target: BinaryTarget,
): AnalysisSnapshotTarget => {
const identity = {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture ?? null,
};
return target.format === "raw-binary"
? { ...identity, format: target.format, entry_point: target.entryPoint }
: { ...identity, format: target.format };
};
export const snapshotTarget = (target: BinaryTarget): AnalysisSnapshotTarget =>
target.format === "raw-binary"
? {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture,
format: target.format,
entry_point: target.entryPoint,
}
: {
sha256: target.sha256,
kind: target.kind,
architecture: target.architecture ?? null,
format: target.format,
};
/** Build the immutable provider/profile binding used by a cached snapshot. */
export const snapshotBinding = (
@@ -475,10 +494,10 @@ export const createAnalysisSnapshotWorkflowEntry = (input: {
subject:
execution.subject === null
? null
: {
: subjectSchema.parse({
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
}),
},
};
};
@@ -538,10 +557,10 @@ export const createAnalysisSnapshotEntry = (input: {
subject:
execution.subject === null
? null
: {
: subjectSchema.parse({
...execution.subject,
architecture: execution.subject.architecture ?? null,
},
}),
},
};
};
+3 -1
View File
@@ -351,7 +351,9 @@ const machArchitecture = (cpu: number): HeaderArchitecture | undefined => {
return undefined;
};
const elfArchitecture = (machine: number): BinaryArchitecture | undefined => {
const elfArchitecture = (
machine: number,
): Exclude<BinaryArchitecture, "6502"> | undefined => {
switch (machine) {
case 3:
return "x86";
+13 -3
View File
@@ -1,12 +1,13 @@
import type { ZipPackageFormat } from "./zipPackageFormat.js";
/** Provider-neutral CPU families detected from supported executable headers. */
/** Provider-neutral CPU families detected from headers or explicitly selected raw loads. */
export const BINARY_ARCHITECTURES = [
"x86",
"x86_64",
"arm",
"arm64",
"mips",
"6502",
"riscv",
] as const;
export type BinaryArchitecture = (typeof BINARY_ARCHITECTURES)[number];
@@ -40,7 +41,7 @@ export const isElfMetadataArchitecture = (
/** Recognized family with no ELF metadata member; the header alone is the fact. */
export type HeaderArchitecture = Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
ElfMetadataArchitecture | "6502"
>;
/** Raw ELF facts; family recognition does not establish ISA or ABI support. */
@@ -144,8 +145,17 @@ export type BinaryTarget =
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
| (BinaryTargetIdentity & {
readonly kind: "executable";
readonly format: "raw-binary";
readonly architecture: Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
>;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
ElfMetadataArchitecture
>[];
readonly entryPoint: string;
readonly entryPointSource: string;
readonly executableRole?: never;
+27
View File
@@ -19,6 +19,33 @@ const TARGET: BinaryTarget = {
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
it("rejects a detected Evidence subject with the raw-only 6502 architecture", () => {
const selected = {
path: TARGET.path,
sha256: TARGET.sha256,
format: "raw-binary" as const,
architecture: "6502" as const,
};
expect(
createEvidence(selected, PROVIDER, {
operation: "inspect",
parameters: {},
result: null,
}).subject,
).toMatchObject({ format: "raw-binary", architecture: "6502" });
const malformed = {
...selected,
format: "pe" as const,
};
expect(() =>
createEvidence(malformed, PROVIDER, {
operation: "inspect",
parameters: {},
result: null,
}),
).toThrow();
});
it("preserves omitted relationship diagnostics and authenticates reported diagnostics", () => {
const observation = {
operation: "procedure_callees",
+43 -33
View File
@@ -38,42 +38,52 @@ export const providerSchema = z.strictObject({
name: z.string().min(1),
version: z.string().nullable(),
});
const subjectSchema = z.strictObject({
const subjectFormatSchema = z.enum([
"hopper",
"analysis-database",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"dmg",
"pkg",
"plist",
"javascript",
"source-map",
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]);
const subjectBaseSchema = z.strictObject({
name: z.string().min(1),
digest: z.strictObject({ sha256: digestSchema }),
format: z.enum([
"hopper",
"analysis-database",
"mach-o",
"elf",
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
"msix",
"appx",
"hap",
"hsp",
"app-pack",
"asar",
"dmg",
"pkg",
"plist",
"javascript",
"source-map",
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
local_path: nulFreeStringSchema,
});
// The format owns the architecture claim, including nested Evidence subjects.
const subjectSchema = z.discriminatedUnion("format", [
subjectBaseSchema.extend({
format: subjectFormatSchema.exclude(["raw-binary"]),
architecture: z.enum(BINARY_ARCHITECTURES).exclude(["6502"]).nullable(),
}),
subjectBaseSchema.extend({
format: z.literal("raw-binary"),
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
}),
]);
/** Source location attached to an evidence observation. */
/** Source-location schema shared by evidence-bearing persistence formats. */
export const evidenceLocationSchema = z.discriminatedUnion("kind", [
@@ -186,7 +196,7 @@ const immutableResultSchema = z
});
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
/** Minimal immutable local artifact identity accepted by Evidence. */
/** Candidate local artifact identity validated by the Evidence subject schema. */
export interface EvidenceSubjectTarget {
readonly path: string;
readonly sha256: string;
+13 -10
View File
@@ -16,14 +16,17 @@ import {
} from "./residualUnknown.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
const artifactManifestSchema = evidenceSchema.shape.subject
.unwrap()
.pick({
digest: true,
format: true,
architecture: true,
})
.strict();
const [detectedSubjectSchema, rawSubjectSchema] =
evidenceSchema.shape.subject.unwrap().options;
const manifestFields = {
digest: true,
format: true,
architecture: true,
} as const;
const artifactManifestSchema = z.discriminatedUnion("format", [
detectedSubjectSchema.pick(manifestFields),
rawSubjectSchema.pick(manifestFields),
]);
const providerManifestSchema = providerSchema;
const environmentManifestSchema = evidenceSchema.shape.environment.unwrap();
const scenarioManifestSchema = z.strictObject({
@@ -85,11 +88,11 @@ export const createEvidenceBundle = (
subject === null
? []
: [
{
artifactManifestSchema.parse({
digest: subject.digest,
format: subject.format,
architecture: subject.architecture,
},
}),
],
),
),
+2 -1
View File
@@ -1,6 +1,7 @@
import { z } from "zod";
import { nativeMetadataRecoverySummarySchema } from "./nativeMetadataRecovery.js";
import { jsonValueSchema } from "../jsonValue.js";
import { binaryArchitectureSchema } from "../rawBinary.js";
const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
@@ -112,7 +113,7 @@ export const nativeLoadImageSchema = z.union([
status: z.enum(["verified", "mismatch"]),
format: z.literal("raw-binary"),
target_sha256: digest,
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
architecture: binaryArchitectureSchema,
language_id: z.string().min(1),
compiler_spec_id: z.string().min(1),
base_address: address,
+38
View File
@@ -39,6 +39,44 @@ describe("raw-binary entry addresses", () => {
});
describe("raw-binary admission", () => {
it("admits byte-aligned 6502 images up to the 16-bit address boundary", () => {
for (const [entryPoint, fileBytes] of [
["0x8001", 8],
["0xffff", 1],
["0x0", 65536],
] as const) {
const result = admitRawBinary({
architecture: "6502",
entryPoint,
fileBytes,
});
if (!result.ok) throw new Error(result.error.reason);
expect(result.value).toEqual({
architecture: "6502",
entryPoint,
entryPointSource: entryPoint,
});
}
});
it.each([
["0x10000", 1],
["0xffff", 2],
["0x0", 65537],
])(
"rejects a 6502 mapping at %s with %i bytes that exceeds 16 bits",
(entryPoint, fileBytes) => {
const result = admitRawBinary({
architecture: "6502",
entryPoint,
fileBytes,
});
if (result.ok) throw new Error("expected 16-bit overflow rejection");
expect(result.error).toEqual({
reason: `raw-binary mapping from ${entryPoint} must fit in the 6502 address width`,
constraint: "load_selection_rejected",
});
},
);
it("admits a little-endian ARM image mapped at the caller entry", () => {
expect(
admitRawBinary({
+8 -5
View File
@@ -13,6 +13,7 @@ export const BINARY_ARCHITECTURES = [
"x86_64",
"arm",
"arm64",
"6502",
] as const satisfies readonly BinaryArchitecture[];
/** Provider-neutral CPU family for a caller-supplied raw-binary load. */
@@ -58,7 +59,7 @@ export const validateRawBinaryLength = (
/** Admitted headerless load identity used by target resolution and profiles. */
export interface RawBinaryAdmission {
readonly architecture: HeaderArchitecture;
readonly architecture: HeaderArchitecture | "6502";
readonly entryPoint: string;
readonly entryPointSource: string;
}
@@ -74,9 +75,11 @@ export interface RawBinaryAdmissionRejection {
}
const addressWidth = (architecture: BinaryArchitecture): bigint =>
architecture === "x86" || architecture === "arm"
? 0xffffffffn
: 0xffffffffffffffffn;
architecture === "6502"
? 0xffffn
: architecture === "x86" || architecture === "arm"
? 0xffffffffn
: 0xffffffffffffffffn;
/** Validate architecture, entry, and that the mapped image fits the CPU width. */
export const admitRawBinary = (input: {
@@ -88,7 +91,7 @@ export const admitRawBinary = (input: {
if (!architecture.success)
return err({
reason:
"raw-binary format requires architecture (x86, x86_64, arm, or arm64)",
"raw-binary format requires architecture (x86, x86_64, arm, arm64, or 6502)",
constraint: "load_selection_rejected",
});
if (typeof input.entryPoint !== "string")
+1 -1
View File
@@ -136,7 +136,7 @@ export const resolveGhidraAnalysisProfile = async (
installation.platform === "win32"
? "official-headless-script-v1"
: "inspected-jvm-launch-support-v1",
load_image_evidence: "independent-raw-mapping-context-v2",
load_image_evidence: "independent-raw-mapping-context-v4",
jump_table_evidence: "typed-case-default-blocks-v1",
decompiler_jump_loads: true,
loader: "BinaryLoader",
+30 -3
View File
@@ -361,7 +361,10 @@ export const attestGhidraRawBinaryLoadImage = (
});
};
const source = observations.source_files[0];
const mapping = observations.mappings[0];
const fileMappings = observations.mappings.filter(
(item) => item.source_file_index !== null,
);
const mapping = fileMappings[0];
check("executable_format", "Raw Binary", observations.executable_format);
check("language_id", language.languageId, observations.language_id);
check(
@@ -371,11 +374,34 @@ export const attestGhidraRawBinaryLoadImage = (
);
// BinaryLoader's block base is independent of the Program image base.
check("image_base", "0x0", observations.image_base);
check(
"default_address_space",
language.defaultAddressSpace,
observations.default_address_space,
);
check("source_file_count", 1, observations.source_files.length);
check("source_file_size", snapshot.bytes, source?.size ?? null);
check("original_file_sha256", target.sha256, source?.original_sha256 ?? null);
check("modified_file_sha256", target.sha256, source?.modified_sha256 ?? null);
check("mapping_count", 1, observations.mappings.length);
// Language-defined uninitialized zero page/stack blocks are observations, not file bytes.
check("mapping_count", 1, fileMappings.length);
check(
"initialized_unbacked_mappings",
0,
observations.mappings.filter(
(item) => item.initialized && item.source_file_index === null,
).length,
);
check("mapping.source_file_index", 0, mapping?.source_file_index ?? null);
// Matching bytes alone do not establish the admitted default-space load.
check("mapping.initialized", true, mapping?.initialized ?? null);
check("mapping.loaded", true, mapping?.loaded ?? null);
check("mapping.overlay", false, mapping?.overlay ?? null);
check(
"mapping.address_space",
observations.default_address_space,
mapping?.address_space ?? null,
);
check(
"mapping.file_offset",
0,
@@ -427,8 +453,9 @@ export const attestGhidraRawBinaryLoadImage = (
checks,
limitations: [
"Raw binary 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, the caller-supplied entry, and the bound little-endian Ghidra language. File offset 0 is mapped at the entry address.",
"Verification covers complete original/modified source identity, initialized and loaded non-overlay file bytes in the default address space, the caller-supplied entry, and the bound little-endian Ghidra language. File offset 0 is mapped at the entry address.",
"Ghidra may report additional language-defined external entries outside the mapped image. They are preserved as observations; verification requires the caller-supplied entry and does not attest other entries.",
"Language-defined uninitialized memory, such as 6502 zero page and stack, is preserved as observations but is not attested as file-backed bytes.",
"Reset vectors, memory-mapped I/O, big-endian and Thumb-only variants, and runtime boot 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.",
],
+68 -5
View File
@@ -8,7 +8,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { describe, expect, it, onTestFinished, vi } from "vitest";
import { fixtureDosLoadImage } from "./GhidraLoadImage.fixture.js";
import { fixtureRawBinaryLoadImage } from "./GhidraRawBinaryLoadImage.fixture.js";
import {
@@ -30,6 +30,8 @@ import { err, ok } from "../domain/result.js";
import type { Result } from "../domain/result.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
import { silentLogger } from "../logger.js";
import * as WindowsNativeLoader from "../windows/WindowsNativeLoader.js";
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../process/WindowsAuthority.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
@@ -190,6 +192,36 @@ describe("Ghidra provider", () => {
});
describe("Ghidra raw-binary profile", () => {
it("admits raw 6502 on Windows and binds its 16-bit language without mutation authority", async () => {
const ghidra = provider({ ...installationHost(), platform: "win32" });
const target: BinaryTarget = {
path: "/tmp/6502.bin",
sha256: "a".repeat(64),
kind: "executable",
format: "raw-binary",
architecture: "6502",
availableArchitectures: ["6502"],
entryPoint: "0x8001",
entryPointSource: "0x008001",
};
expect(ghidra.inspectTargetSupport(target).status).toBe("supported");
const resolved = await ghidra.resolveAnalysisProfile(target);
if (!resolved.ok) throw resolved.error;
expect(resolved.value.profile?.parameters).toMatchObject({
architecture: "6502",
loader: "BinaryLoader",
language_id: "6502:LE:16:default",
compiler_spec_id: "default",
entry_point: "0x8001",
language_selection: "caller-supplied-v1",
load_image_evidence: "independent-raw-mapping-context-v4",
});
expect(
ghidra
.capabilities()
.some(({ available, effects }) => available && effects.mutatesArtifact),
).toBe(false);
});
it("commits BinaryLoader language and caller-supplied entry", async () => {
const ghidra = provider();
const target: BinaryTarget = {
@@ -324,6 +356,13 @@ describe("Ghidra platform support", () => {
});
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
const native = vi
.spyOn(WindowsNativeLoader, "systemWindowsNativeAuthority")
.mockReturnValue({
available: false,
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
});
onTestFinished(() => native.mockRestore());
const ghidra = provider({ ...installationHost(), platform: "win32" });
const nativeApplication = peTarget("x86_64");
@@ -812,11 +851,22 @@ describe("Ghidra relationship coverage", () => {
});
});
describe("Ghidra measured load-image projection", () => {
it.each(["verified", "changed-snapshot", "cancelled"] as const)(
describe("Ghidra measured raw load-image projection", () => {
it.each([
"verified",
"mapping-mismatch",
"changed-snapshot",
"cancelled",
] as const)(
"streams raw snapshot identity and preserves %s outcomes",
async (state) => {
const fixture = fixtureRawBinaryLoadImage();
if (state === "mapping-mismatch") {
const mapping = fixture.observation.mappings[0];
if (mapping === undefined)
throw new Error("Missing source mapping fixture");
mapping.overlay = true;
}
const controller = new AbortController();
const signals: (AbortSignal | undefined)[] = [];
const ghidra = provider(installationHost(), () => ({
@@ -872,12 +922,23 @@ describe("Ghidra measured load-image projection", () => {
{ signal: controller.signal },
);
expect(signals).toEqual([controller.signal]);
if (state === "verified") {
if (state === "verified" || state === "mapping-mismatch") {
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({
status: "verified",
status: state === "verified" ? "verified" : "mismatch",
observations: fixture.observation,
});
if (state === "mapping-mismatch") {
expect(result.value.result).toMatchObject({
checks: expect.arrayContaining([
expect.objectContaining({
name: "mapping.overlay",
observed: true,
matched: false,
}),
]),
});
}
} else {
expect(result).toMatchObject({
ok: false,
@@ -894,7 +955,9 @@ describe("Ghidra measured load-image projection", () => {
}
},
);
});
describe("Ghidra measured DOS load-image projection", () => {
it.each([
"verified",
"mismatch",
+7 -2
View File
@@ -66,6 +66,7 @@ const SUPPORTED_ARCHITECTURES = new Set([
"arm",
"arm64",
"mips",
"6502",
"riscv",
]);
@@ -184,7 +185,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
status: "unsupported",
code: "architecture_unsupported",
reason:
"Ghidra v1 requires a supported x86, x86_64, arm, arm64, or MIPS target profile.",
"Ghidra v1 requires a supported x86, x86_64, arm, arm64, MIPS, RISC-V, or raw 6502 target profile.",
diagnostics,
};
return {
@@ -304,11 +305,15 @@ const inspectWindowsP0TargetSupport = (
target: BinaryTarget,
diagnostics: Readonly<Record<string, JsonValue>>,
): ProviderTargetSupport => {
// The raw 6502 lane uses the same immutable snapshot and native ownership boundary.
if (target.format === "raw-binary" && target.architecture === "6502")
return { status: "supported", code: null, reason: null, diagnostics };
if (target.format !== "pe")
return {
status: "unsupported",
code: "target_format_unsupported",
reason: "Windows Ghidra P0 accepts PE targets only.",
reason:
"Windows Ghidra P0 accepts native PE and explicitly selected raw 6502 targets only.",
diagnostics,
};
if (target.architecture !== "x86" && target.architecture !== "x86_64")
+1 -1
View File
@@ -33,7 +33,7 @@ export const healthLimitations = Object.freeze([
/** Additional limitations applied to the experimental Windows x64 P0 boundary. */
export const windowsP0Limitations = Object.freeze([
"Windows Ghidra P0 accepts approved native x86 and x86-64 PE applications and DLLs; managed, hostile, sensitive, and mutable-path targets are unsupported.",
"Windows Ghidra P0 accepts native x86 and x86-64 PE applications and DLLs, and explicitly selected raw 6502 images; managed, hostile, sensitive, and mutable-path targets are unsupported.",
"The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.",
"Windows sessions require the matching packaged Windows x64 native addon, local NTFS targets and runtimes, and Windows 10 or later. Native handles enforce path admission, private DACLs, and Job Object ownership automatically.",
]);
+1 -1
View File
@@ -516,7 +516,7 @@ export const createGhidraProviderClient = (input: {
...(target.format === "raw-binary"
? [
"Headerless raw-binary analysis uses the caller-supplied architecture and entry address; file offset 0 is mapped at that address. Headers are not discovered from file bytes.",
"Little-endian generic Ghidra languages are used for x86, x86_64, arm, and arm64. Big-endian, Thumb-only, Cortex-M, and other processor variants are unsupported in this increment.",
"Little-endian generic Ghidra languages are used for x86, x86_64, arm, arm64, and NMOS 6502. Big-endian, Thumb-only, Cortex-M, 65C02, 65816, and other processor variants are unsupported in this increment.",
"Static analysis does not emulate reset vectors, memory-mapped I/O, or firmware boot sequences.",
]
: []),
+30 -7
View File
@@ -1,28 +1,51 @@
import type { HeaderArchitecture } from "../domain/binaryTargetTypes.js";
import type { RawBinaryAdmission } from "../domain/rawBinary.js";
/** Bound Ghidra language for a caller-supplied raw-binary architecture. */
export interface GhidraRawBinaryLanguage {
readonly languageId: string;
readonly compilerSpecId: "default" | "gcc";
readonly defaultAddressSpace: "ram" | "RAM";
}
/**
* Map the four caller-visible CPU families to little-endian generic Ghidra
* Map caller-visible CPU families to little-endian generic Ghidra
* languages with a supported generic compiler specification. These are
* analysis conventions, not evidence of the target's original compiler.
* Big-endian, Thumb-only, and Cortex-M variants are out of scope.
*/
export const ghidraRawBinaryLanguage = (
architecture: HeaderArchitecture,
architecture: RawBinaryAdmission["architecture"],
): GhidraRawBinaryLanguage => {
switch (architecture) {
case "6502":
return {
languageId: "6502:LE:16:default",
compilerSpecId: "default",
defaultAddressSpace: "RAM",
};
case "x86":
return { languageId: "x86:LE:32:default", compilerSpecId: "gcc" };
return {
languageId: "x86:LE:32:default",
compilerSpecId: "gcc",
defaultAddressSpace: "ram",
};
case "x86_64":
return { languageId: "x86:LE:64:default", compilerSpecId: "gcc" };
return {
languageId: "x86:LE:64:default",
compilerSpecId: "gcc",
defaultAddressSpace: "ram",
};
case "arm":
return { languageId: "ARM:LE:32:v7", compilerSpecId: "default" };
return {
languageId: "ARM:LE:32:v7",
compilerSpecId: "default",
defaultAddressSpace: "ram",
};
case "arm64":
return { languageId: "AARCH64:LE:64:v8A", compilerSpecId: "default" };
return {
languageId: "AARCH64:LE:64:v8A",
compilerSpecId: "default",
defaultAddressSpace: "ram",
};
}
};
+138
View File
@@ -9,23 +9,161 @@ describe("raw-binary Ghidra language binding", () => {
expect(ghidraRawBinaryLanguage("x86")).toEqual({
languageId: "x86:LE:32:default",
compilerSpecId: "gcc",
defaultAddressSpace: "ram",
});
expect(ghidraRawBinaryLanguage("x86_64")).toEqual({
languageId: "x86:LE:64:default",
compilerSpecId: "gcc",
defaultAddressSpace: "ram",
});
expect(ghidraRawBinaryLanguage("arm")).toEqual({
languageId: "ARM:LE:32:v7",
compilerSpecId: "default",
defaultAddressSpace: "ram",
});
expect(ghidraRawBinaryLanguage("arm64")).toEqual({
languageId: "AARCH64:LE:64:v8A",
compilerSpecId: "default",
defaultAddressSpace: "ram",
});
});
});
describe("raw-binary mapped-block state", () => {
it.each(["RAM", "ram"])(
"requires the bound 6502 address space for %s observations",
(space) => {
const f = fixtureRawBinaryLoadImage();
const target = {
...f.target,
architecture: "6502" as const,
availableArchitectures: ["6502" as const],
entryPoint: "0x8001",
entryPointSource: "0x8001",
};
f.observation.language_id = "6502:LE:16:default";
f.observation.default_address_space = space;
f.observation.entry_points = [target.entryPoint];
const mapping = f.observation.mappings[0];
if (mapping === undefined)
throw new Error("Missing source mapping fixture");
mapping.start = target.entryPoint;
mapping.end = "0x8004";
mapping.address_space = space;
expect(
attestGhidraRawBinaryLoadImage(f.snapshot, target, f.observation),
).toMatchObject({
ok: true,
value: {
status: space === "RAM" ? "verified" : "mismatch",
checks: expect.arrayContaining([
expect.objectContaining({
name: "default_address_space",
expected: "RAM",
observed: space,
matched: space === "RAM",
}),
]),
},
});
},
);
it.each([
["initialized", false],
["loaded", false],
["overlay", true],
["address_space", "overlay"],
] as const)(
"retains a mismatch when the file mapping declares %s=%s",
(property, value) => {
const f = fixtureRawBinaryLoadImage();
const mapping = f.observation.mappings[0];
if (mapping === undefined)
throw new Error("Missing source mapping fixture");
Object.assign(mapping, { [property]: value });
expect(
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
).toMatchObject({
ok: true,
value: {
status: "mismatch",
observations: f.observation,
checks: expect.arrayContaining([
expect.objectContaining({
name: `mapping.${property}`,
matched: false,
observed: value,
}),
]),
},
});
},
);
it("does not verify a foreign default address space even when its mapping agrees", () => {
const f = fixtureRawBinaryLoadImage();
f.observation.default_address_space = "foreign";
const mapping = f.observation.mappings[0];
if (mapping === undefined)
throw new Error("Missing source mapping fixture");
mapping.address_space = "foreign";
expect(
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
).toMatchObject({
ok: true,
value: {
status: "mismatch",
observations: f.observation,
checks: expect.arrayContaining([
expect.objectContaining({
name: "default_address_space",
matched: false,
observed: "foreign",
}),
]),
},
});
});
});
describe("raw-binary independent load-image checks", () => {
it("retains uninitialized language memory without treating it as file-backed bytes", () => {
const f = fixtureRawBinaryLoadImage();
const zeroPage = {
block: "ZERO_PAGE",
start: "0x0",
end: "0xff",
address_space: "ram",
initialized: false,
loaded: true,
overlay: false,
length: 256,
source_file_index: null,
file_offset: null,
sha256: null,
};
f.observation.mappings.unshift(zeroPage);
expect(
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
).toMatchObject({
ok: true,
value: { status: "verified", observations: f.observation },
});
zeroPage.initialized = true;
expect(
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
).toMatchObject({
ok: true,
value: {
status: "mismatch",
checks: expect.arrayContaining([
expect.objectContaining({
name: "initialized_unbacked_mappings",
matched: false,
}),
]),
},
});
});
it("verifies mapped bytes at the caller-supplied entry", () => {
const f = fixtureRawBinaryLoadImage();
const result = attestGhidraRawBinaryLoadImage(
+9 -2
View File
@@ -1,6 +1,6 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { join, parse, relative } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { parseConfig } from "../config/parseConfig.js";
import type {
@@ -92,7 +92,14 @@ const target = (change: Partial<RiscvElfMetadata> = {}): BinaryTarget => ({
let installDir = "";
beforeAll(async () => {
installDir = await mkdtemp(join(tmpdir(), "rea-ghidra-riscv-languages-"));
const root =
process.platform === "win32" ? join(process.cwd(), "build") : tmpdir();
await mkdir(root, { recursive: true });
installDir = await mkdtemp(join(root, "rea-ghidra-riscv-languages-"));
// The simulated Linux host needs a POSIX absolute path. A current-drive root
// path also reaches this real fixture on Windows without changing admission.
if (process.platform === "win32")
installDir = `/${relative(parse(installDir).root, installDir).replaceAll("\\", "/")}`;
const languages = join(installDir, "Ghidra/Processors/RISCV/data/languages");
await mkdir(languages, { recursive: true });
await writeFile(join(languages, "riscv.ldefs"), RISCV_LDEFS);
+2 -1
View File
@@ -123,6 +123,8 @@ export const hopperLoaderArgsForTarget = (
if (target.kind === "database") return ok([]);
if (target.kind !== "executable")
return err(new ProviderAdapterError("hopper", "resolve_analysis_profile"));
if (target.format === "raw-binary")
return err(new ProviderAdapterError("hopper", "resolve_analysis_profile"));
const architecture = target.architecture;
if (isElfMetadataArchitecture(architecture))
return err(
@@ -155,7 +157,6 @@ export const hopperLoaderArgsForTarget = (
return ok(["-l", "WinPE", flag]);
case "dos-mz":
case "dos-com":
case "raw-binary":
return err(
new ProviderAdapterError("hopper", "resolve_analysis_profile"),
);
+2 -9
View File
@@ -2,11 +2,7 @@ import { createHash } from "node:crypto";
import { open, type FileHandle } from "node:fs/promises";
import { z } from "zod";
import {
isMachOFormat,
isElfMetadataArchitecture,
type BinaryTarget,
} from "../domain/binaryTargetTypes.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { BinaryTargetError } from "../domain/configurationErrors.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
@@ -48,10 +44,7 @@ export const resolveHopperMachOImage = async (
),
);
if (signal?.aborted) return err(new AnalysisCancelledError("open_binary"));
if (
!isMachOFormat(target.format) ||
isElfMetadataArchitecture(target.architecture)
)
if (target.format !== "mach-o" && target.format !== "mach-o-universal")
return invalid("Hopper FAT64 image preparation requires a Mach-O target");
let file: FileHandle;
try {