feat(native): admit raw binaries with caller-supplied architecture and entry (#1868)

* feat(native): admit raw binaries with caller-supplied architecture and entry

* fix(native): honor raw-binary preparation and entry identity

* fix(ghidra): stream raw snapshot attestation with cancellation

* fix(native): preserve and validate raw lifecycle entries

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Matt Van Horn
2026-10-12 00:06:29 +08:00
committed by GitHub
co-authored by morluto
parent d3e83b0899
commit 7c207c7951
57 changed files with 2453 additions and 336 deletions
+50
View File
@@ -8,6 +8,7 @@ import {
snapshotBinding,
snapshotEvidenceForQuery,
snapshotTarget,
snapshotMatchesTarget,
} from "./analysisSnapshot.js";
import {
ANALYSIS_SNAPSHOT_PROFILE,
@@ -16,6 +17,7 @@ import {
} from "./analysisSnapshot.fixture.js";
import { createEvidence } from "./evidence.js";
import { createEvidenceBundle } from "./evidenceBundle.js";
import type { BinaryTarget } from "./binaryTargetTypes.js";
const snapshotWithHistoricalEvidence = () => {
const target = snapshotTarget(ANALYSIS_SNAPSHOT_TARGET);
@@ -68,6 +70,54 @@ const snapshotWithHistoricalEvidence = () => {
};
describe("analysis snapshot contract", () => {
it("partitions raw snapshots and query identities by the canonical entry", () => {
const target: BinaryTarget = {
path: "/fixture/image.bin",
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
kind: "executable",
format: "raw-binary",
architecture: "arm",
availableArchitectures: ["arm"],
entryPoint: "0x8000000",
entryPointSource: "0x08000000",
};
const snapshot = snapshotTarget(target);
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
const changed = {
...target,
entryPoint: "0x9000000",
entryPointSource: "0x09000000",
};
expect(
snapshotMatchesTarget(snapshot, {
...target,
entryPointSource: "0x8000000",
}),
).toBe(true);
expect(snapshotMatchesTarget(snapshot, changed)).toBe(false);
expect(analysisQueryId(snapshot, binding, "list_procedures", {})).not.toBe(
analysisQueryId(snapshotTarget(changed), binding, "list_procedures", {}),
);
const parsed = analysisSnapshotSchema.parse({
target: snapshot,
binding,
entries: [],
workflow_entries: [],
evidence_bundle: createEvidenceBundle([]),
});
expect(parsed.target).toHaveProperty("entry_point", target.entryPoint);
const { entry_point: _entry, ...legacy } = {
...snapshot,
entry_point: target.entryPoint,
};
expect(
analysisSnapshotSchema.safeParse({ ...parsed, target: legacy }).success,
).toBe(false);
expect(snapshotTarget(ANALYSIS_SNAPSHOT_TARGET)).not.toHaveProperty(
"entry_point",
);
});
it("preserves DOS MZ target and subject formats with the x86 family", () => {
const target = {
path: ANALYSIS_SNAPSHOT_TARGET.path,
+28 -9
View File
@@ -40,6 +40,7 @@ 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";
const architectureSchema = z.enum(BINARY_ARCHITECTURES);
const formatSchema = z.enum([
@@ -49,6 +50,7 @@ const formatSchema = z.enum([
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
@@ -80,12 +82,22 @@ const subjectSchema = z.object({
]),
architecture: architectureSchema.nullable(),
});
const targetSchema = z.object({
const targetIdentitySchema = z.object({
sha256: digestSchema,
kind: kindSchema,
format: formatSchema,
architecture: architectureSchema.nullable(),
});
const targetSchema = z.discriminatedUnion("format", [
targetIdentitySchema.extend({
format: z.enum(
formatSchema.options.filter((format) => format !== "raw-binary"),
),
}),
targetIdentitySchema.extend({
format: z.literal("raw-binary"),
entry_point: rawBinaryEntryPointSchema,
}),
]);
const bindingSchema = z
.object({
provider: committedProviderSchema,
@@ -311,12 +323,16 @@ const canonicalJson = (value: unknown): string => {
/** Project a binary into the path-free identity used for cache invalidation. */
export const snapshotTarget = (
target: BinaryTarget,
): AnalysisSnapshotTarget => ({
sha256: target.sha256,
kind: target.kind,
format: target.format,
architecture: target.architecture ?? null,
});
): 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 };
};
/** Build the immutable provider/profile binding used by a cached snapshot. */
export const snapshotBinding = (
@@ -335,7 +351,10 @@ export const snapshotMatchesTarget = (
snapshot.sha256 === target.sha256 &&
snapshot.kind === target.kind &&
snapshot.format === target.format &&
snapshot.architecture === (target.architecture ?? null);
snapshot.architecture === (target.architecture ?? null) &&
(snapshot.format !== "raw-binary" ||
(target.format === "raw-binary" &&
snapshot.entry_point === target.entryPoint));
/** Compare a snapshot binding with the selected concrete analysis profile. */
export const snapshotMatchesProfile = (
+1
View File
@@ -50,6 +50,7 @@ const artifactFormatSchema = z.enum([
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"hopper",
"analysis-database",
"ipa",
+7
View File
@@ -78,6 +78,13 @@ export type BinaryTarget =
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "raw-binary";
readonly entryPoint: string;
readonly entryPointSource: string;
readonly executableRole?: never;
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "pe";
/** Provider-neutral PE image role observed from COFF characteristics. */
+2 -2
View File
@@ -1,8 +1,8 @@
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");
/** Headerless executable interpretation explicitly selected by the caller. */
export const executableFormatHintSchema = z.enum(["dos-com", "raw-binary"]);
/** Explicit executable interpretation for formats with no identifying header. */
export type ExecutableFormatHint = z.infer<typeof executableFormatHintSchema>;
+1
View File
@@ -44,6 +44,7 @@ const subjectSchema = z.object({
"pe",
"dos-mz",
"dos-com",
"raw-binary",
"zip",
"ipa",
"apk",
+18 -1
View File
@@ -84,7 +84,7 @@ export const nativeLoadImageCheckSchema = z.strictObject({
});
/** Read-only native image verification; verified applies only to declared coverage. */
export const nativeLoadImageSchema = z.discriminatedUnion("status", [
export const nativeLoadImageSchema = z.union([
z.strictObject({
status: z.literal("unsupported"),
reason: z.string().min(1),
@@ -108,6 +108,23 @@ export const nativeLoadImageSchema = z.discriminatedUnion("status", [
checks: z.array(nativeLoadImageCheckSchema),
limitations: z.array(z.string().min(1)),
}),
z.strictObject({
status: z.enum(["verified", "mismatch"]),
format: z.literal("raw-binary"),
target_sha256: digest,
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
language_id: z.string().min(1),
compiler_spec_id: z.string().min(1),
base_address: address,
file_bytes: integer.min(1),
entry: z.strictObject({
address: address,
file_offset: z.literal(0),
}),
observations: nativeLoadImageObservationSchema,
checks: z.array(nativeLoadImageCheckSchema),
limitations: z.array(z.string().min(1)),
}),
]);
/** Provider-neutral native load-image result. */
+135
View File
@@ -0,0 +1,135 @@
import { describe, expect, it } from "vitest";
import { executableFormatHintSchema } from "./dosCom.js";
import {
admitRawBinary,
parseRawBinaryEntryPoint,
rawBinarySelectionError,
validateRawBinaryLength,
} from "./rawBinary.js";
describe("headerless format hints", () => {
it("admits dos-com and raw-binary names only", () => {
expect(executableFormatHintSchema.safeParse("dos-com").success).toBe(true);
expect(executableFormatHintSchema.safeParse("raw-binary").success).toBe(
true,
);
expect(executableFormatHintSchema.safeParse("raw").success).toBe(false);
});
});
describe("raw-binary entry addresses", () => {
it("canonicalizes equivalent hex spellings without dropping the source", () => {
const parsed = parseRawBinaryEntryPoint("0x08000000");
expect(parsed).toEqual({
ok: true,
value: {
source: "0x08000000",
canonical: "0x8000000",
value: 0x8000000n,
},
});
});
it.each(["8000000", "0x", "0xgg", "0X8000000", ""])(
"rejects malformed entry %s",
(value) => {
expect(parseRawBinaryEntryPoint(value).ok).toBe(false);
},
);
});
describe("raw-binary admission", () => {
it("admits a little-endian ARM image mapped at the caller entry", () => {
expect(
admitRawBinary({
architecture: "arm",
entryPoint: "0x8000000",
fileBytes: 4,
}),
).toEqual({
ok: true,
value: {
architecture: "arm",
entryPoint: "0x8000000",
entryPointSource: "0x8000000",
},
});
});
it("rejects an empty file", () => {
expect(validateRawBinaryLength(0).ok).toBe(false);
expect(
admitRawBinary({
architecture: "x86",
entryPoint: "0x1000",
fileBytes: 0,
}).ok,
).toBe(false);
});
it("rejects a 32-bit mapping that exceeds the architecture width", () => {
const result = admitRawBinary({
architecture: "arm",
entryPoint: "0xfffffffc",
fileBytes: 8,
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("expected overflow rejection");
expect(result.error).toContain("arm address width");
});
it("allows a 64-bit mapping that would overflow 32-bit ARM", () => {
expect(
admitRawBinary({
architecture: "arm64",
entryPoint: "0xfffffffc",
fileBytes: 8,
}).ok,
).toBe(true);
});
it.each(["arm", "arm64"])(
"rejects unaligned %s entries before provider selection",
(architecture) => {
for (const entryPoint of ["0x8000001", "0x8000002", "0x8000003"]) {
expect(
admitRawBinary({ architecture, entryPoint, fileBytes: 4 }),
).toEqual({
ok: false,
error: `raw-binary ${architecture} entry_point ${entryPoint} must be 4-byte aligned`,
});
}
},
);
it.each(["x86", "x86_64"])(
"admits byte-aligned %s entries",
(architecture) => {
const admitted = admitRawBinary({
architecture,
entryPoint: "0x1001",
fileBytes: 1,
});
if (!admitted.ok) throw new Error(admitted.error);
expect(admitted.value.entryPoint).toBe("0x1001");
},
);
});
describe("raw-binary selection pairing", () => {
it("requires architecture and entry with format=raw-binary", () => {
expect(rawBinarySelectionError({ format: "raw-binary" })).toBe(
"format=raw-binary requires architecture and entry_point",
);
expect(
rawBinarySelectionError({
format: "raw-binary",
architecture: "arm",
entryPoint: "0x8000000",
}),
).toBeUndefined();
});
it("rejects architecture or entry without format=raw-binary", () => {
expect(
rawBinarySelectionError({ architecture: "arm", entryPoint: "0x1" }),
).toBe("architecture and entry_point apply only with format=raw-binary");
expect(
rawBinarySelectionError({ format: "dos-com", architecture: "x86" }),
).toBe("architecture and entry_point apply only with format=raw-binary");
});
});
+123
View File
@@ -0,0 +1,123 @@
import { z } from "zod";
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
import type { ExecutableFormatHint } from "./dosCom.js";
import { err, ok, type Result } from "./result.js";
/** Caller-visible CPU families admitted for headerless raw binaries. */
export const BINARY_ARCHITECTURES = [
"x86",
"x86_64",
"arm",
"arm64",
] as const satisfies readonly BinaryArchitecture[];
/** Provider-neutral CPU family for a caller-supplied raw-binary load. */
export const binaryArchitectureSchema = z.enum(BINARY_ARCHITECTURES);
const RAW_BINARY_ENTRY_POINT = /^0x[0-9A-Fa-f]{1,16}$/u;
/** Hexadecimal load and entry address; file offset 0 is mapped here. */
export const rawBinaryEntryPointSchema = z
.string()
.regex(RAW_BINARY_ENTRY_POINT, {
message: "entry_point must be a hexadecimal address of the form 0x…",
});
/** Canonicalized caller-supplied raw-binary entry with the original spelling. */
export interface CanonicalRawBinaryEntry {
readonly source: string;
readonly canonical: string;
readonly value: bigint;
}
/** Parse a caller-supplied hex entry while preserving the source spelling. */
export const parseRawBinaryEntryPoint = (
value: string,
): Result<CanonicalRawBinaryEntry, string> => {
if (!RAW_BINARY_ENTRY_POINT.test(value))
return err("entry_point must be a hexadecimal address of the form 0x…");
const parsed = BigInt(value);
return ok({
source: value,
canonical: `0x${parsed.toString(16)}`,
value: parsed,
});
};
/** Reject empty or non-integral file extents for a headerless image. */
export const validateRawBinaryLength = (
length: number,
): Result<null, string> =>
Number.isSafeInteger(length) && length >= 1
? ok(null)
: err("raw-binary requires at least one file byte");
/** Admitted headerless load identity used by target resolution and profiles. */
export interface RawBinaryAdmission {
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly entryPoint: string;
readonly entryPointSource: string;
}
const addressWidth = (architecture: BinaryArchitecture): bigint =>
architecture === "x86" || architecture === "arm"
? 0xffffffffn
: 0xffffffffffffffffn;
/** Validate architecture, entry, and that the mapped image fits the CPU width. */
export const admitRawBinary = (input: {
readonly architecture: unknown;
readonly entryPoint: unknown;
readonly fileBytes: number;
}): Result<RawBinaryAdmission, string> => {
const architecture = binaryArchitectureSchema.safeParse(input.architecture);
if (!architecture.success)
return err(
"raw-binary format requires architecture (x86, x86_64, arm, or arm64)",
);
if (typeof input.entryPoint !== "string")
return err(
"raw-binary format requires entry_point as a hexadecimal address of the form 0x…",
);
const entry = parseRawBinaryEntryPoint(input.entryPoint);
if (!entry.ok) return entry;
if (
(architecture.data === "arm" || architecture.data === "arm64") &&
entry.value.value % 4n !== 0n
)
return err(
`raw-binary ${architecture.data} entry_point ${entry.value.canonical} must be 4-byte aligned`,
);
const length = validateRawBinaryLength(input.fileBytes);
if (!length.ok) return length;
const last = entry.value.value + BigInt(input.fileBytes) - 1n;
const max = addressWidth(architecture.data);
if (entry.value.value > max || last > max)
return err(
`raw-binary mapping from ${entry.value.canonical} must fit in the ${architecture.data} address width`,
);
return ok({
architecture: architecture.data,
entryPoint: entry.value.canonical,
entryPointSource: entry.value.source,
});
};
/** Describe the format/architecture/entry pairing without performing I/O. */
export const rawBinarySelectionError = (input: {
readonly format?: ExecutableFormatHint;
readonly architecture?: unknown;
readonly entryPoint?: unknown;
}): string | undefined => {
const hasArchitecture = input.architecture !== undefined;
const hasEntry = input.entryPoint !== undefined;
if (input.format === "raw-binary") {
if (!hasArchitecture || !hasEntry)
return "format=raw-binary requires architecture and entry_point";
return undefined;
}
if (hasArchitecture || hasEntry)
return "architecture and entry_point apply only with format=raw-binary";
return undefined;
};