feat(go): inspect embedded binary build metadata (#1363)
* feat(go): inspect embedded binary build metadata * fix(go): preserve byte metadata and validate container mappings * fix(go): support moduleless legacy build metadata Recognize optional module string headers in declared zero-filled memory while rejecting ambiguous and unmapped pointers. Preserve the original module-pointer field as the zero-byte source anchor. Classify initial symlink-loop and overlong-path failures as invalid input, with CLI and MCP regressions. * fix(go): reject undersized PE optional headers * fix(native): stabilize ELF memory checks and clean up exec wrappers Use existing parent/group/run-token ownership for caller-selected Python launchers, which can exec through a shell or prlimit. Add cancellation regressions for the valid wrapper and wrong-parent/token cases. Replace the timing-dependent 30,000-section memory workload with a valid 32 MiB padded ELF under a 64 MiB address-space limit. Check the same image successfully through CLI and MCP before requiring a typed memory failure, preserving the production timeout and all error assertions. Validation: npm run check and check:fast passed; 61 focused tests passed including Go CLI/MCP and session snapshots. Real decoder probes with pinned packages passed on Python 3.12.3 and 3.12.14. The full local ELF verifier is blocked by this container's procps/process-ownership boundary; the exact pushed head requires GitHub's real-binary-layout lane. * test: repair Electron fixtures and stabilize catalog startup checks Declare Electron imports in option, preload override, and path-resolution fixtures after upstream began requiring proven API provenance. Retain all option and preload assertions and adjust exact source ranges for the added import line. Use the existing bounded acceptance timeout for the cold catalog lifecycle test instead of a separate 15-second ceiling. This retains the coverage allowance and all catalog, error, and cleanup assertions without retries. Validation: npm run check, final check:fast, formatting and diff checks passed. Source path regression and Go boundary/MCP/service checks passed. All 20 Go CLI cases and both supported-host runtime cases passed on rerun; two macOS-only cases skipped on Linux. A prior contended local run timed out once in a Go CLI diagnostic; that case passed on rerun. Electron process-boundary verification is blocked locally by procps namespace inspection and requires fresh CI. * test(mcp): isolate nested schema references between tool contracts Clear Ajv's non-meta schema registry after each root, including compilation failures. Disabling root registration alone leaves nested IDs available to later tools and can let a dangling reference pass the catalog gate. Add regressions for leakage after successful and failed compilation while retaining shared meta-schema validators. The regression failed before the fix; all 11 schema cases and full npm run check pass. Reviewed independently. * test(ci): align Go effects and source-map verification contracts Audit the Go inspector wording as static metadata inspection. Assert retained source declaration indexes in BOM reconstruction and the compiler-derived nested-map oracle. Keep a 45,000-map admission control below the 32 MiB output budget and the 50,000-map overflow case above it with the expanded representation. Validation: reproduced all four failing assertions, then passed 120 focused tests and the final admission suite. npm run check and real Chrome 154 / esbuild 0.25.10 source-map verification passed, including all four nested-map scenarios and verified process lineage. --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
@@ -334,6 +334,8 @@ const workflowAvailabilityFor = ({
|
||||
kind,
|
||||
policy,
|
||||
}: AvailabilityContext): Availability | null => {
|
||||
if (name === "inspect_go_binary")
|
||||
return { reason: "available", remediation: null };
|
||||
if (name === "trace_web_module_imports")
|
||||
return {
|
||||
reason: "available",
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type {
|
||||
GoBinary,
|
||||
InspectGoBinaryInput,
|
||||
} from "../../domain/go/goBinary.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Replaceable offline build-information reader with no target-execution authority. */
|
||||
export interface GoBinaryPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
inspect(
|
||||
input: InspectGoBinaryInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<GoBinary, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { GoBinaryService } from "./GoBinaryService.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import type { GoBinary } from "../../domain/go/goBinary.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
|
||||
const identity = {
|
||||
id: "fixture-go",
|
||||
name: "Source-owned Go reader seam",
|
||||
version: "1",
|
||||
};
|
||||
const report: GoBinary = {
|
||||
artifact: { path: "/artifacts/program", sha256: "a".repeat(64), bytes: 1024 },
|
||||
format: "elf",
|
||||
architecture: "riscv64",
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
build_info: null,
|
||||
limitations: ["Build information unavailable."],
|
||||
};
|
||||
|
||||
it("rejects invalid paths and extra caller arguments before invoking the reader", async () => {
|
||||
let calls = 0;
|
||||
const service = new GoBinaryService({
|
||||
identity,
|
||||
inspect: () => {
|
||||
calls += 1;
|
||||
return Promise.resolve(ok(report));
|
||||
},
|
||||
});
|
||||
for (const input of [
|
||||
{ path: "relative" },
|
||||
{ path: "/artifacts/\0program" },
|
||||
{ path: report.artifact.path, execute: true },
|
||||
]) {
|
||||
const result = await service.inspect(input);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
}
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves unsupported subject architectures and does not duplicate metadata", async () => {
|
||||
const service = new GoBinaryService({
|
||||
identity,
|
||||
inspect: () => Promise.resolve(ok(report)),
|
||||
});
|
||||
const result = await service.inspect({ path: report.artifact.path });
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.subject).toMatchObject({
|
||||
architecture: null,
|
||||
local_path: report.artifact.path,
|
||||
digest: { sha256: report.artifact.sha256 },
|
||||
});
|
||||
expect(result.value.normalized_result).toEqual(report);
|
||||
expect(result.value.raw_result).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves byte-valued build metadata and validates compiler source lengths", async () => {
|
||||
const moduleBytes = Buffer.concat([
|
||||
Buffer.from("3077af0c9274080241e1c107e6d618e6", "hex"),
|
||||
Buffer.from([0xff, 10]),
|
||||
Buffer.from("f932433186182072008242104116d8f2", "hex"),
|
||||
]);
|
||||
const buildInfo: NonNullable<GoBinary["build_info"]> = {
|
||||
header_offset: 64,
|
||||
encoding: "inline",
|
||||
go_version: null,
|
||||
go_version_bytes_base64: "/w==",
|
||||
module_text: null,
|
||||
module_bytes_base64: moduleBytes.toString("base64"),
|
||||
version_location: { offset: 128, bytes: 1 },
|
||||
module_location: { offset: 256, bytes: moduleBytes.length },
|
||||
module: {
|
||||
path: null,
|
||||
main: null,
|
||||
dependencies: [],
|
||||
settings: [],
|
||||
unparsed_lines: [],
|
||||
unparsed_line_bytes_base64: ["/w=="],
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const partial: GoBinary = {
|
||||
...report,
|
||||
build_info: buildInfo,
|
||||
limitations: ["Some embedded strings contain non-UTF-8 bytes."],
|
||||
};
|
||||
const result = await new GoBinaryService({
|
||||
identity,
|
||||
inspect: () => Promise.resolve(ok(partial)),
|
||||
}).inspect({ path: report.artifact.path });
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.normalized_result).toEqual(partial);
|
||||
|
||||
const mismatched: GoBinary = {
|
||||
...partial,
|
||||
build_info: {
|
||||
...buildInfo,
|
||||
version_location: { offset: 128, bytes: 2 },
|
||||
},
|
||||
};
|
||||
const invalid = await new GoBinaryService({
|
||||
identity,
|
||||
inspect: () => Promise.resolve(ok(mismatched)),
|
||||
}).inspect({ path: report.artifact.path });
|
||||
expect(invalid.ok).toBe(false);
|
||||
if (!invalid.ok) expect(invalid.error).toBeInstanceOf(AnalysisOutputError);
|
||||
});
|
||||
|
||||
it("refuses reader identity changes and invalid original source ranges", async () => {
|
||||
const outside: GoBinary = {
|
||||
...report,
|
||||
build_info: {
|
||||
header_offset: 1000,
|
||||
encoding: "inline",
|
||||
go_version: "go1.26.0",
|
||||
go_version_bytes_base64: Buffer.from("go1.26.0").toString("base64"),
|
||||
module_text: "",
|
||||
module_bytes_base64: "",
|
||||
version_location: { offset: 2000, bytes: 8 },
|
||||
module_location: { offset: 0, bytes: 0 },
|
||||
module: {
|
||||
path: null,
|
||||
main: null,
|
||||
dependencies: [],
|
||||
settings: [],
|
||||
unparsed_lines: [],
|
||||
unparsed_line_bytes_base64: [],
|
||||
complete: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
for (const value of [
|
||||
{ ...report, artifact: { ...report.artifact, path: "/artifacts/other" } },
|
||||
outside,
|
||||
]) {
|
||||
const result = await new GoBinaryService({
|
||||
identity,
|
||||
inspect: () => Promise.resolve(ok(value)),
|
||||
}).inspect({ path: report.artifact.path });
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
|
||||
}
|
||||
});
|
||||
|
||||
it("honors cancellation before reading and after a completed observation", async () => {
|
||||
const controller = new AbortController();
|
||||
let calls = 0;
|
||||
const service = new GoBinaryService({
|
||||
identity,
|
||||
inspect: () => {
|
||||
calls += 1;
|
||||
controller.abort();
|
||||
return Promise.resolve(ok(report));
|
||||
},
|
||||
});
|
||||
const completed = await service.inspect(
|
||||
{ path: report.artifact.path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(completed.ok).toBe(false);
|
||||
if (!completed.ok)
|
||||
expect(completed.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
const before = await service.inspect(
|
||||
{ path: report.artifact.path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(before.ok).toBe(false);
|
||||
if (!before.ok) expect(before.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import type { ExecutionOptions } from "../AnalysisProvider.js";
|
||||
import type { GoBinaryPort } from "./GoBinaryPort.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import { BINARY_ARCHITECTURES } from "../../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
goBinarySchema,
|
||||
inspectGoBinaryInputSchema,
|
||||
} from "../../domain/go/goBinary.js";
|
||||
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
|
||||
const OPERATION = "inspect_go_binary";
|
||||
const architectureForSubject = (architecture: string) => {
|
||||
switch (architecture) {
|
||||
case "386":
|
||||
return "x86";
|
||||
case "amd64":
|
||||
return "x86_64";
|
||||
default:
|
||||
return BINARY_ARCHITECTURES.find(
|
||||
(supported) => supported === architecture,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Shared exact input validation and artifact-bound Evidence for CLI and MCP. */
|
||||
export class GoBinaryService {
|
||||
constructor(readonly provider: GoBinaryPort) {}
|
||||
|
||||
/** Inspect one explicitly selected file without acquiring a binary session. */
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const input = inspectGoBinaryInputSchema.safeParse(rawInput);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(OPERATION, input.error.issues, rawInput, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
if (!isAbsolute(input.data.path))
|
||||
return err(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: "Expected an absolute filesystem path on this host.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const inspected = await this.provider.inspect(input.data, options);
|
||||
if (!inspected.ok) return inspected;
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const report = goBinarySchema.safeParse(inspected.value);
|
||||
if (!report.success || report.data.artifact.path !== input.data.path)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Go build-information reader returned malformed metadata or changed the selected artifact identity.",
|
||||
),
|
||||
);
|
||||
const value = report.data;
|
||||
const architecture = architectureForSubject(value.architecture);
|
||||
return ok(
|
||||
createEvidence(
|
||||
{
|
||||
path: value.artifact.path,
|
||||
sha256: value.artifact.sha256,
|
||||
format: value.format === "macho" ? "mach-o" : value.format,
|
||||
...(architecture === undefined ? {} : { architecture }),
|
||||
},
|
||||
this.provider.identity,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters: input.data,
|
||||
result: value,
|
||||
confidence: "observed",
|
||||
limitations: value.limitations,
|
||||
locations: [
|
||||
{ kind: "artifact-path", path: value.artifact.path },
|
||||
...(value.build_info === null
|
||||
? []
|
||||
: [
|
||||
{
|
||||
kind: "file-offset-range" as const,
|
||||
start: value.build_info.header_offset,
|
||||
end: value.build_info.header_offset + 32,
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { registerWasmCommands } from "./cli/wasmCommands.js";
|
||||
import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
|
||||
import { createDirectAnalysis } from "./composition/directAnalysis.js";
|
||||
import { registerEvmCommands } from "./cli/evmCommands.js";
|
||||
import { registerGoCommands } from "./cli/goCommands.js";
|
||||
import { registerAnalysisViewCommands } from "./cli/analysisViewCommands.js";
|
||||
import { registerBinaryDiagnosticsCommands } from "./cli/binaryDiagnosticsCommands.js";
|
||||
import { Cli } from "incur";
|
||||
@@ -75,6 +76,7 @@ export const createCli = (
|
||||
registerUtilityCommands(cli, logger, environment, analysis);
|
||||
registerWasmCommands(cli, logger, environment);
|
||||
registerEvmCommands(cli, logger, environment);
|
||||
registerGoCommands(cli, logger);
|
||||
registerArtifactCommands(cli, logger, analysis.runProviderAnalysis);
|
||||
registerManagedCommands(cli, logger, analysis.runProviderAnalysis);
|
||||
registerAndroidCommands(cli, logger, environment);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { z } from "incur";
|
||||
import { resolve } from "node:path";
|
||||
import { createGoBinaryService } from "../composition/go.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** Resolve caller paths and inspect static build metadata through the shared workflow. */
|
||||
export const registerGoCommands = (cli: CliInstance, logger: Logger): void => {
|
||||
const service = createGoBinaryService();
|
||||
cli.command(CLI_COMMANDS.inspectGoBinary, {
|
||||
description:
|
||||
"Inspect embedded Go compiler, modules and build settings without target execution",
|
||||
args: z.object({
|
||||
path: z.string().describe("Local ELF, PE or thin Mach-O image"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectGoBinary, async () => {
|
||||
const result = await service.inspect(
|
||||
{ path: resolve(args.path) },
|
||||
{ signal },
|
||||
);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
};
|
||||
@@ -42,6 +42,7 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
inspectManagedArtifact: "inspect-managed-artifact",
|
||||
inspectRecordedCrash: "inspect-recorded-crash",
|
||||
inspectBinaryLayout: "inspect-binary-layout",
|
||||
inspectGoBinary: "inspect-go-binary",
|
||||
inspectPeResources: "inspect-pe-resources",
|
||||
inspectAnalysisView: "inspect-analysis-view",
|
||||
inspectEvidenceBundle: "inspect-evidence-bundle",
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { GoBinaryService } from "../application/go/GoBinaryService.js";
|
||||
import { GoBinaryProvider } from "../go/GoBinaryProvider.js";
|
||||
|
||||
/** Compose bundled offline inspection without acquiring a toolchain or starting any process. */
|
||||
export const createGoBinaryService = (): GoBinaryService =>
|
||||
new GoBinaryService(new GoBinaryProvider());
|
||||
@@ -0,0 +1,26 @@
|
||||
import {
|
||||
goBinarySchema,
|
||||
inspectGoBinaryInputSchema,
|
||||
} from "../../domain/go/goBinary.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
|
||||
/** Static Go metadata is independent of active native-analysis providers and host toolchains. */
|
||||
export const GO_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_go_binary",
|
||||
...toolContractMetadata("inspect_go_binary"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Inspect embedded Go compiler version, main module, dependency/replacement versions and build settings in an explicit local ELF, PE or thin Mach-O image. Returns original artifact SHA-256, exact build-info source ranges, raw framed module bytes and unparsed module-text lines inline as observed Evidence. Supports inline and historical pointer encodings without installing Go, opening a disassembler, executing the target, writing temporary files or accessing the network. Missing metadata is reported as unknown, not proof that an image is not Go. Does not recover functions, source mappings, types or runtime behavior. Resource guards bound files to 256 MiB, aggregate embedded strings to 1 MiB, structural table decoding to 16 MiB and complete inline metadata to 8 MiB; malformed, unsupported and oversized inputs receive typed failures rather than partial success.",
|
||||
inputSchema: inspectGoBinaryInputSchema,
|
||||
outputSchema: evidenceResultOf(goBinarySchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect embedded build provenance",
|
||||
input: { path: "/artifacts/application" },
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -1,5 +1,6 @@
|
||||
import { WASM_TOOL_CONTRACTS } from "./wasm/wasmToolContracts.js";
|
||||
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
|
||||
import { GO_TOOL_CONTRACTS } from "./go/goToolContracts.js";
|
||||
import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "./analysisViewToolContracts.js";
|
||||
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./native/nativeToolContracts.js";
|
||||
@@ -32,6 +33,7 @@ export const TOOL_CONTRACTS = [
|
||||
...ANALYSIS_VIEW_TOOL_CONTRACTS,
|
||||
...ARTIFACT_TOOL_CONTRACTS,
|
||||
...EVM_TOOL_CONTRACTS,
|
||||
...GO_TOOL_CONTRACTS,
|
||||
...WASM_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...ANDROID_TOOL_CONTRACTS,
|
||||
|
||||
@@ -16,6 +16,7 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
|
||||
inspect_native_load_image: "states that it does not execute the target",
|
||||
resolve_native_call_targets: "states that it does not execute code",
|
||||
inspect_pe_resources: "states that it does not execute the image",
|
||||
inspect_go_binary: "reads embedded metadata without executing the target",
|
||||
inspect_binary_layout:
|
||||
"parses the binary offline with operator-configured pwntools",
|
||||
inspect_recorded_crash: "inspects a core file without launching its target",
|
||||
|
||||
@@ -53,6 +53,7 @@ const sessionEvidence = effects({ mutatesSession: true });
|
||||
|
||||
/** Explicit effect audit for every public tool. */
|
||||
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
inspect_go_binary: evidence,
|
||||
inspect_wasm_artifact: effects({
|
||||
mutatesSession: true,
|
||||
writesFilesystem: true,
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { z } from "zod";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { localPathStringSchema } from "../localPath.js";
|
||||
import { CANONICAL_BASE64_PATTERN } from "../stringPatterns.js";
|
||||
|
||||
const sourceRangeSchema = z.strictObject({
|
||||
offset: z.number().int().nonnegative(),
|
||||
bytes: z.number().int().nonnegative(),
|
||||
});
|
||||
const moduleIdentitySchema = z.strictObject({
|
||||
path: z.string(),
|
||||
version: z.string(),
|
||||
sum: z.string().nullable(),
|
||||
});
|
||||
|
||||
/** Module identities retain development versions, local replacements and missing sums verbatim. */
|
||||
export const goModuleSchema = moduleIdentitySchema.extend({
|
||||
replacement: moduleIdentitySchema.nullable(),
|
||||
});
|
||||
|
||||
/** Parsed records alongside unrecognized text lines and exact non-UTF-8 line bytes. */
|
||||
export const goModuleMetadataSchema = z.strictObject({
|
||||
path: z.string().nullable(),
|
||||
main: goModuleSchema.nullable(),
|
||||
dependencies: z.array(goModuleSchema),
|
||||
settings: z.array(z.strictObject({ key: z.string(), value: z.string() })),
|
||||
unparsed_lines: z.array(z.string()),
|
||||
unparsed_line_bytes_base64: z.array(
|
||||
z.string().regex(CANONICAL_BASE64_PATTERN),
|
||||
),
|
||||
complete: z.boolean(),
|
||||
});
|
||||
|
||||
/** One exact local artifact, independent of any active disassembler target. */
|
||||
export const inspectGoBinaryInputSchema = z.strictObject({
|
||||
path: localPathStringSchema.describe(
|
||||
"Absolute filesystem path to the selected executable or library",
|
||||
),
|
||||
});
|
||||
|
||||
/** Compiler-written build information and its original file-backed source ranges. */
|
||||
export const goBuildInfoSchema = z.strictObject({
|
||||
header_offset: z.number().int().nonnegative(),
|
||||
encoding: z.enum(["inline", "pointer"]),
|
||||
go_version: z.string().nullable(),
|
||||
go_version_bytes_base64: z.string().regex(CANONICAL_BASE64_PATTERN),
|
||||
module_text: z.string().nullable(),
|
||||
module_bytes_base64: z.string().regex(CANONICAL_BASE64_PATTERN),
|
||||
version_location: sourceRangeSchema,
|
||||
module_location: sourceRangeSchema,
|
||||
module: goModuleMetadataSchema,
|
||||
});
|
||||
|
||||
/** Complete bounded build-metadata observation; absence does not identify a binary as non-Go. */
|
||||
export const goBinarySchema = z
|
||||
.strictObject({
|
||||
artifact: z.strictObject({
|
||||
path: localPathStringSchema,
|
||||
sha256: digestSchema,
|
||||
bytes: z.number().int().nonnegative(),
|
||||
}),
|
||||
format: z.enum(["elf", "pe", "macho"]),
|
||||
architecture: z.string(),
|
||||
bits: z.union([z.literal(32), z.literal(64)]),
|
||||
byte_order: z.enum(["little", "big"]),
|
||||
build_info: goBuildInfoSchema.nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
})
|
||||
.superRefine((report, context) => {
|
||||
const info = report.build_info;
|
||||
if (info === null) return;
|
||||
if (info.header_offset > report.artifact.bytes - 32)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["build_info", "header_offset"],
|
||||
message: "Build-info header is outside the selected artifact.",
|
||||
});
|
||||
for (const field of ["version_location", "module_location"] as const) {
|
||||
const range = info[field];
|
||||
if (
|
||||
range.offset > report.artifact.bytes ||
|
||||
range.bytes > report.artifact.bytes - range.offset
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["build_info", field],
|
||||
message: "Build-info source range is outside the selected artifact.",
|
||||
});
|
||||
}
|
||||
for (const [field, range, description] of [
|
||||
["go_version_bytes_base64", info.version_location, "compiler"],
|
||||
["module_bytes_base64", info.module_location, "module"],
|
||||
] as const) {
|
||||
const encoded = info[field];
|
||||
const padding = encoded.endsWith("==")
|
||||
? 2
|
||||
: encoded.endsWith("=")
|
||||
? 1
|
||||
: 0;
|
||||
if ((encoded.length / 4) * 3 - padding !== range.bytes)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["build_info", field],
|
||||
message: `Encoded ${description} bytes do not match their reported source length.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type GoModule = z.infer<typeof goModuleSchema>;
|
||||
export type GoModuleMetadata = z.infer<typeof goModuleMetadataSchema>;
|
||||
export type GoBinary = z.infer<typeof goBinarySchema>;
|
||||
export type InspectGoBinaryInput = z.infer<typeof inspectGoBinaryInputSchema>;
|
||||
@@ -0,0 +1,216 @@
|
||||
/** Distinguish corrupt recognized binaries from containers outside parser coverage. */
|
||||
export class GoBinaryFormatFailure extends Error {
|
||||
constructor(
|
||||
readonly kind: "malformed" | "unsupported",
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "GoBinaryFormatFailure";
|
||||
}
|
||||
}
|
||||
|
||||
/** Resource boundary exceeded while decoding metadata or native container structure. */
|
||||
export class GoBinaryResourceFailure extends Error {
|
||||
constructor(
|
||||
readonly boundary: "build-info" | "structure",
|
||||
readonly maximum_bytes: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "GoBinaryResourceFailure";
|
||||
}
|
||||
}
|
||||
|
||||
/** One file-backed virtual range; addresses stay exact until mapped to file offsets. */
|
||||
export interface GoFileMapping {
|
||||
readonly address: bigint;
|
||||
readonly offset: number;
|
||||
readonly size: number;
|
||||
}
|
||||
|
||||
/** Declared zero-initialized virtual memory with no corresponding file bytes. */
|
||||
export interface GoZeroFillMapping {
|
||||
readonly address: bigint;
|
||||
readonly size: bigint;
|
||||
}
|
||||
|
||||
/** Native container facts and its producer-defined build-info search area. */
|
||||
export interface GoBinaryContainer {
|
||||
readonly format: "elf" | "pe" | "macho";
|
||||
readonly architecture: string;
|
||||
readonly bits: 32 | 64;
|
||||
readonly byte_order: "little" | "big";
|
||||
readonly mappings: readonly GoFileMapping[];
|
||||
readonly zero_fills: readonly GoZeroFillMapping[];
|
||||
readonly search: GoFileMapping | null;
|
||||
}
|
||||
|
||||
/** Reader that checks every structural range before decoding numeric fields. */
|
||||
export class GoBinaryReader {
|
||||
constructor(
|
||||
readonly bytes: Buffer,
|
||||
readonly little: boolean,
|
||||
) {}
|
||||
|
||||
range(offset: number, size: number, label: string): Buffer {
|
||||
if (
|
||||
!Number.isSafeInteger(offset) ||
|
||||
!Number.isSafeInteger(size) ||
|
||||
offset < 0 ||
|
||||
size < 0 ||
|
||||
offset > this.bytes.length ||
|
||||
size > this.bytes.length - offset
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
`${label} range is truncated or outside the file`,
|
||||
);
|
||||
return this.bytes.subarray(offset, offset + size);
|
||||
}
|
||||
|
||||
u16(offset: number): number {
|
||||
const value = this.range(offset, 2, "16-bit field");
|
||||
return this.little ? value.readUInt16LE() : value.readUInt16BE();
|
||||
}
|
||||
|
||||
u32(offset: number): number {
|
||||
const value = this.range(offset, 4, "32-bit field");
|
||||
return this.little ? value.readUInt32LE() : value.readUInt32BE();
|
||||
}
|
||||
|
||||
word(offset: number, bits: 32 | 64): bigint {
|
||||
if (bits === 32) return BigInt(this.u32(offset));
|
||||
const value = this.range(offset, 8, "64-bit field");
|
||||
return this.little ? value.readBigUInt64LE() : value.readBigUInt64BE();
|
||||
}
|
||||
|
||||
fileRange(offset: bigint, size: bigint, label: string): GoFileMapping {
|
||||
if (
|
||||
offset > BigInt(this.bytes.length) ||
|
||||
size > BigInt(this.bytes.length) - offset
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
`${label} range is outside the file`,
|
||||
);
|
||||
const result = { address: 0n, offset: Number(offset), size: Number(size) };
|
||||
this.range(result.offset, result.size, label);
|
||||
return result;
|
||||
}
|
||||
|
||||
table(offset: bigint, count: number, width: number, label: string): number {
|
||||
const size = BigInt(count) * BigInt(width);
|
||||
if (size > 16n * 1024n * 1024n)
|
||||
throw new GoBinaryResourceFailure(
|
||||
"structure",
|
||||
16 * 1024 * 1024,
|
||||
`${label} exceeds the 16 MiB structural decoding budget`,
|
||||
);
|
||||
return this.fileRange(offset, size, label).offset;
|
||||
}
|
||||
}
|
||||
|
||||
/** Map a virtual span without losing precision or selecting an ambiguous alias. */
|
||||
export const mappedFileOffset = (
|
||||
mappings: readonly GoFileMapping[],
|
||||
address: bigint,
|
||||
size: number,
|
||||
zeroFills: readonly GoZeroFillMapping[] = [],
|
||||
): number => {
|
||||
let found: number | undefined;
|
||||
for (const mapping of mappings) {
|
||||
const delta = address - mapping.address;
|
||||
if (
|
||||
delta < 0n ||
|
||||
delta > BigInt(mapping.size) ||
|
||||
BigInt(size) > BigInt(mapping.size) - delta
|
||||
)
|
||||
continue;
|
||||
const offset = mapping.offset + Number(delta);
|
||||
if (found !== undefined && found !== offset)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Virtual address has ambiguous file mappings",
|
||||
);
|
||||
found = offset;
|
||||
}
|
||||
if (found === undefined)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Virtual address or string range is not file mapped",
|
||||
);
|
||||
for (const zeroFill of zeroFills) {
|
||||
if (spansOverlap(address, BigInt(size), zeroFill.address, zeroFill.size))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Virtual address has ambiguous file and zero-fill mappings",
|
||||
);
|
||||
}
|
||||
const end = address + BigInt(size);
|
||||
for (const mapping of mappings) {
|
||||
const start = address > mapping.address ? address : mapping.address;
|
||||
const mappingEnd = mapping.address + BigInt(mapping.size);
|
||||
const overlapEnd = end < mappingEnd ? end : mappingEnd;
|
||||
if (start >= overlapEnd) continue;
|
||||
if (
|
||||
BigInt(found) + start - address !==
|
||||
BigInt(mapping.offset) + start - mapping.address
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Virtual address has ambiguous file mappings",
|
||||
);
|
||||
}
|
||||
return found;
|
||||
};
|
||||
|
||||
/** Recognize a wholly zero-filled span while refusing even partial file aliases. */
|
||||
export const isZeroFilledSpan = (
|
||||
mappings: readonly GoFileMapping[],
|
||||
zeroFills: readonly GoZeroFillMapping[],
|
||||
address: bigint,
|
||||
size: number,
|
||||
): boolean => {
|
||||
const bytes = BigInt(size);
|
||||
if (
|
||||
!zeroFills.some(
|
||||
(mapping) =>
|
||||
address >= mapping.address &&
|
||||
address + bytes <= mapping.address + mapping.size,
|
||||
)
|
||||
)
|
||||
return false;
|
||||
for (const mapping of mappings) {
|
||||
if (spansOverlap(address, bytes, mapping.address, BigInt(mapping.size)))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Virtual address has ambiguous file and zero-fill mappings",
|
||||
);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const spansOverlap = (
|
||||
address: bigint,
|
||||
size: bigint,
|
||||
otherAddress: bigint,
|
||||
otherSize: bigint,
|
||||
): boolean =>
|
||||
size > 0n &&
|
||||
otherSize > 0n &&
|
||||
address < otherAddress + otherSize &&
|
||||
otherAddress < address + size;
|
||||
|
||||
/** Decode metadata text without replacing invalid bytes or stripping an initial BOM. */
|
||||
export const goUtf8 = (bytes: Buffer, label: string): string => {
|
||||
try {
|
||||
return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
|
||||
bytes,
|
||||
);
|
||||
} catch (cause) {
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
`${label} contains malformed UTF-8: ${String(cause)}`,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,316 @@
|
||||
import {
|
||||
GoBinaryFormatFailure,
|
||||
GoBinaryResourceFailure,
|
||||
GoBinaryReader,
|
||||
goUtf8,
|
||||
mappedFileOffset,
|
||||
isZeroFilledSpan,
|
||||
type GoBinaryContainer,
|
||||
type GoFileMapping,
|
||||
} from "./GoBinaryContainer.js";
|
||||
import { readGoElfImage } from "./GoElfImage.js";
|
||||
import { readGoMachoImage } from "./GoMachoImage.js";
|
||||
import { readGoPeImage } from "./GoPeImage.js";
|
||||
|
||||
export {
|
||||
GoBinaryFormatFailure,
|
||||
GoBinaryResourceFailure,
|
||||
} from "./GoBinaryContainer.js";
|
||||
|
||||
const MAGIC = Buffer.from("ff20476f206275696c64696e663a", "hex");
|
||||
const MODULE_START = Buffer.from("3077af0c9274080241e1c107e6d618e6", "hex");
|
||||
const MODULE_END = Buffer.from("f932433186182072008242104116d8f2", "hex");
|
||||
const MAX_BUILD_INFO_BYTES = 1024 * 1024;
|
||||
|
||||
/** Exact file span of one embedded string's contents, excluding its length/header. */
|
||||
export interface GoStringLocation {
|
||||
readonly offset: number;
|
||||
readonly bytes: number;
|
||||
}
|
||||
|
||||
/** Observed compiler string and validated module body with its original framing bytes. */
|
||||
export interface GoBuildInfo {
|
||||
readonly header_offset: number;
|
||||
readonly encoding: "inline" | "pointer";
|
||||
readonly go_version: string | null;
|
||||
readonly go_version_bytes_base64: string;
|
||||
readonly module_text: string | null;
|
||||
readonly module_bytes_base64: string;
|
||||
readonly version_location: GoStringLocation;
|
||||
readonly module_location: GoStringLocation;
|
||||
}
|
||||
|
||||
/** Native image identity and optional Go build information; absence is not a language verdict. */
|
||||
export interface GoBinaryImage {
|
||||
readonly format: "elf" | "pe" | "macho";
|
||||
readonly architecture: string;
|
||||
readonly bits: 32 | 64;
|
||||
readonly byte_order: "little" | "big";
|
||||
readonly build_info: GoBuildInfo | null;
|
||||
}
|
||||
|
||||
/** Inspect bounded executable bytes using native mappings, without loading or executing code. */
|
||||
export const readGoBinaryImage = (bytes: Buffer): GoBinaryImage => {
|
||||
const container = readContainer(bytes);
|
||||
const { format, architecture, bits, byte_order } = container;
|
||||
const search = container.search;
|
||||
const header = findHeader(bytes, search);
|
||||
if (header === null || search === null)
|
||||
return { format, architecture, bits, byte_order, build_info: null };
|
||||
const verifyMapping = (size: number): void => {
|
||||
const address = search.address + BigInt(header - search.offset);
|
||||
if (
|
||||
mappedFileOffset(
|
||||
container.mappings,
|
||||
address,
|
||||
size,
|
||||
container.zero_fills,
|
||||
) !== header
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info bytes disagree with their virtual mapping",
|
||||
);
|
||||
};
|
||||
verifyMapping(32);
|
||||
const reader = new GoBinaryReader(bytes, byte_order === "little");
|
||||
const ptrSize = bytes[header + 14];
|
||||
const flags = bytes[header + 15] ?? 0;
|
||||
if ((flags & ~3) !== 0)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"unsupported",
|
||||
"Go build-info flags contain an unsupported format bit",
|
||||
);
|
||||
if ((flags & 2) === 0 && (flags & 1) !== (byte_order === "big" ? 1 : 0))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info byte order disagrees with the image",
|
||||
);
|
||||
const encoding = (flags & 2) !== 0 ? "inline" : "pointer";
|
||||
const readInline = (offset: number, remaining: number) =>
|
||||
readInlineString(reader, offset, remaining);
|
||||
const sourceEnd = search.offset + search.size;
|
||||
let version: LocatedString;
|
||||
let module: LocatedString;
|
||||
if (encoding === "inline") {
|
||||
version = readInline(header + 32, sourceEnd - header - 32);
|
||||
const next = version.location.offset + version.location.bytes;
|
||||
module = readInline(next, sourceEnd - next);
|
||||
verifyMapping(module.location.offset + module.location.bytes - header);
|
||||
} else {
|
||||
if (ptrSize !== 4 && ptrSize !== 8)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info pointer width must be 4 or 8",
|
||||
);
|
||||
if (ptrSize * 8 !== bits)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info pointer width disagrees with the image",
|
||||
);
|
||||
const pointerBits = ptrSize === 8 ? 64 : 32;
|
||||
version = readPointerString(
|
||||
reader,
|
||||
container,
|
||||
reader.word(header + 16, pointerBits),
|
||||
);
|
||||
const moduleField = header + 16 + ptrSize;
|
||||
module = readOptionalModuleString(
|
||||
reader,
|
||||
container,
|
||||
reader.word(moduleField, pointerBits),
|
||||
moduleField,
|
||||
);
|
||||
}
|
||||
if (version.location.bytes + module.location.bytes > MAX_BUILD_INFO_BYTES)
|
||||
throw new GoBinaryResourceFailure(
|
||||
"build-info",
|
||||
MAX_BUILD_INFO_BYTES,
|
||||
"Go build-info strings exceed the aggregate 1 MiB limit",
|
||||
);
|
||||
if (version.bytes.length === 0)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info compiler version is empty",
|
||||
);
|
||||
const goVersion = observedText(version.bytes);
|
||||
let moduleText: string | null = "";
|
||||
if (module.bytes.length !== 0) {
|
||||
if (
|
||||
module.bytes.length < 33 ||
|
||||
!module.bytes.subarray(0, 16).equals(MODULE_START) ||
|
||||
!module.bytes.subarray(-16).equals(MODULE_END) ||
|
||||
module.bytes[module.bytes.length - 17] !== 10
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go module string framing is invalid",
|
||||
);
|
||||
moduleText = observedText(module.bytes.subarray(16, -16));
|
||||
}
|
||||
return {
|
||||
format,
|
||||
architecture,
|
||||
bits,
|
||||
byte_order,
|
||||
build_info: {
|
||||
header_offset: header,
|
||||
encoding,
|
||||
go_version: goVersion,
|
||||
go_version_bytes_base64: version.bytes.toString("base64"),
|
||||
module_text: moduleText,
|
||||
module_bytes_base64: module.bytes.toString("base64"),
|
||||
version_location: version.location,
|
||||
module_location: module.location,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const observedText = (bytes: Buffer): string | null => {
|
||||
try {
|
||||
return goUtf8(bytes, "Go build string");
|
||||
} catch (cause) {
|
||||
if (cause instanceof GoBinaryFormatFailure) return null;
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
interface LocatedString {
|
||||
readonly bytes: Buffer;
|
||||
readonly location: GoStringLocation;
|
||||
}
|
||||
|
||||
const readContainer = (bytes: Buffer): GoBinaryContainer => {
|
||||
if (bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
|
||||
return readGoElfImage(bytes);
|
||||
if (bytes.subarray(0, 2).equals(Buffer.from("MZ")))
|
||||
return readGoPeImage(bytes);
|
||||
if (bytes.length >= 4) {
|
||||
const magic = bytes.readUInt32BE();
|
||||
if ([0xcafebabe, 0xcafebabf, 0xbebafeca, 0xbfbafeca].includes(magic))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"unsupported",
|
||||
"Universal/fat Mach-O containers require selecting a thin slice",
|
||||
);
|
||||
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
|
||||
return readGoMachoImage(bytes);
|
||||
}
|
||||
throw new GoBinaryFormatFailure(
|
||||
"unsupported",
|
||||
"Only ELF, PE, and thin Mach-O native images are supported",
|
||||
);
|
||||
};
|
||||
|
||||
const findHeader = (
|
||||
bytes: Buffer,
|
||||
search: GoFileMapping | null,
|
||||
): number | null => {
|
||||
if (search === null || search.size === 0) return null;
|
||||
const end = search.offset + search.size;
|
||||
const selected = bytes.subarray(search.offset, end);
|
||||
let offset = Number((16n - (search.address % 16n)) % 16n);
|
||||
while (offset < selected.length) {
|
||||
const match = selected.indexOf(MAGIC, offset);
|
||||
if (match < 0) return null;
|
||||
const candidate = search.offset + match;
|
||||
const address = search.address + BigInt(candidate - search.offset);
|
||||
if (address % 16n === 0n) {
|
||||
if (end - candidate < 32)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info header is truncated",
|
||||
);
|
||||
return candidate;
|
||||
}
|
||||
offset = match + 1;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const readInlineString = (
|
||||
reader: GoBinaryReader,
|
||||
offset: number,
|
||||
remaining: number,
|
||||
): LocatedString => {
|
||||
let length = 0n;
|
||||
for (let index = 0; index < 10; index++) {
|
||||
if (index >= remaining)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info varint is truncated",
|
||||
);
|
||||
const byte = reader.bytes[offset + index] ?? 0;
|
||||
if (index === 9 && byte > 1)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info varint overflows 64 bits",
|
||||
);
|
||||
length |= BigInt(byte & 127) << BigInt(index * 7);
|
||||
if ((byte & 128) === 0) {
|
||||
if (length > BigInt(MAX_BUILD_INFO_BYTES))
|
||||
throw new GoBinaryResourceFailure(
|
||||
"build-info",
|
||||
MAX_BUILD_INFO_BYTES,
|
||||
"Go build-info string length exceeds the 1 MiB limit",
|
||||
);
|
||||
const size = Number(length);
|
||||
if (size > remaining - index - 1)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info string range is truncated",
|
||||
);
|
||||
const start = offset + index + 1;
|
||||
return {
|
||||
bytes: reader.range(start, size, "Go build-info string"),
|
||||
location: { offset: start, bytes: size },
|
||||
};
|
||||
}
|
||||
}
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Go build-info varint is unterminated",
|
||||
);
|
||||
};
|
||||
|
||||
const readPointerString = (
|
||||
reader: GoBinaryReader,
|
||||
container: GoBinaryContainer,
|
||||
address: bigint,
|
||||
): LocatedString => {
|
||||
const { mappings, zero_fills: zeroFills, bits } = container;
|
||||
const width = bits / 8;
|
||||
const header = mappedFileOffset(mappings, address, width * 2, zeroFills);
|
||||
const valueAddress = reader.word(header, bits);
|
||||
const length = reader.word(header + width, bits);
|
||||
if (length > BigInt(MAX_BUILD_INFO_BYTES))
|
||||
throw new GoBinaryResourceFailure(
|
||||
"build-info",
|
||||
MAX_BUILD_INFO_BYTES,
|
||||
"Go build-info pointer string length exceeds the 1 MiB limit",
|
||||
);
|
||||
const size = Number(length);
|
||||
// Zero-length Go strings may carry a zero data pointer.
|
||||
const offset =
|
||||
size === 0 && valueAddress === 0n
|
||||
? header
|
||||
: mappedFileOffset(mappings, valueAddress, size, zeroFills);
|
||||
return {
|
||||
bytes: reader.range(offset, size, "Go build-info pointer string"),
|
||||
location: { offset, bytes: size },
|
||||
};
|
||||
};
|
||||
|
||||
const readOptionalModuleString = (
|
||||
reader: GoBinaryReader,
|
||||
container: GoBinaryContainer,
|
||||
address: bigint,
|
||||
pointerField: number,
|
||||
): LocatedString =>
|
||||
isZeroFilledSpan(
|
||||
container.mappings,
|
||||
container.zero_fills,
|
||||
address,
|
||||
(container.bits / 8) * 2,
|
||||
)
|
||||
? { bytes: Buffer.alloc(0), location: { offset: pointerField, bytes: 0 } }
|
||||
: readPointerString(reader, container, address);
|
||||
@@ -0,0 +1,202 @@
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
|
||||
import type { ExecutionOptions } from "../application/AnalysisProvider.js";
|
||||
import type { GoBinaryPort } from "../application/go/GoBinaryPort.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisResourceConstraintError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
goBinarySchema,
|
||||
type GoBinary,
|
||||
type InspectGoBinaryInput,
|
||||
} from "../domain/go/goBinary.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
readGoBinaryImage,
|
||||
GoBinaryFormatFailure,
|
||||
GoBinaryResourceFailure,
|
||||
} from "./GoBinaryImage.js";
|
||||
import { parseGoModuleBytes, parseGoModuleText } from "./GoModuleText.js";
|
||||
|
||||
/** Bundled format reader identity; embedded compiler versions are separate observed facts. */
|
||||
export const GO_BINARY_PROVIDER_IDENTITY = {
|
||||
id: "go-build-info",
|
||||
name: "REA Go build-information reader",
|
||||
version: "1",
|
||||
} as const;
|
||||
const OPERATION = "inspect_go_binary";
|
||||
const INPUT_BYTES = 256 * 1024 * 1024;
|
||||
const OUTPUT_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
const failureFor = (
|
||||
cause: unknown,
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (signal?.aborted) return new AnalysisCancelledError(OPERATION);
|
||||
if (cause instanceof GoBinaryResourceFailure)
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"memory",
|
||||
`Selected artifact ${path}: ${cause.message}`,
|
||||
{ boundary: cause.boundary, maximum_bytes: cause.maximum_bytes },
|
||||
{ cause },
|
||||
);
|
||||
if (cause instanceof GoBinaryFormatFailure)
|
||||
return cause.kind === "unsupported"
|
||||
? new AnalysisUnsupportedTargetError(OPERATION, path, cause.message, {
|
||||
cause,
|
||||
})
|
||||
: new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: `Selected artifact ${path}: ${cause.message}`,
|
||||
},
|
||||
]);
|
||||
if (cause instanceof ArtifactReaderFailure) {
|
||||
if (cause.reason === "integrity")
|
||||
return new AnalysisArtifactChangedError(OPERATION, path, cause.message, {
|
||||
cause,
|
||||
});
|
||||
if (cause.reason === "cancelled")
|
||||
return new AnalysisCancelledError(OPERATION);
|
||||
if (cause.reason === "limit")
|
||||
return new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
cause.message,
|
||||
{ maximum_input_bytes: INPUT_BYTES },
|
||||
{ cause },
|
||||
);
|
||||
if (cause.reason === "path")
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{ path: ["path"], reason: "invalid_format", message: cause.message },
|
||||
]);
|
||||
}
|
||||
if (cause instanceof Error && "code" in cause) {
|
||||
if (cause.code === "EACCES" || cause.code === "EPERM")
|
||||
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
|
||||
cause,
|
||||
});
|
||||
if (
|
||||
["ENOENT", "ENOTDIR", "ELOOP", "ENAMETOOLONG"].includes(
|
||||
String(cause.code),
|
||||
)
|
||||
)
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: `Selected artifact could not be read (${String(cause.code)}): ${path}.`,
|
||||
},
|
||||
]);
|
||||
}
|
||||
return new ProviderAdapterError(GO_BINARY_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
cause,
|
||||
diagnostics: {
|
||||
path,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const outputLimit = (path: string) =>
|
||||
new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"transport",
|
||||
`Complete Go metadata for ${path} exceeds the inline output budget; no partial success is returned.`,
|
||||
{ maximum_output_bytes: OUTPUT_BYTES },
|
||||
);
|
||||
|
||||
/** Stable in-process metadata inspection without subprocesses, temporary files or Go installation. */
|
||||
export class GoBinaryProvider implements GoBinaryPort {
|
||||
readonly identity = GO_BINARY_PROVIDER_IDENTITY;
|
||||
|
||||
/** Read complete compiler/module metadata while preserving original byte identity and source ranges. */
|
||||
async inspect(
|
||||
input: InspectGoBinaryInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<GoBinary, AnalysisError>> {
|
||||
try {
|
||||
const snapshot = await readStableArtifact(
|
||||
input.path,
|
||||
INPUT_BYTES,
|
||||
options?.signal,
|
||||
);
|
||||
options?.signal?.throwIfAborted();
|
||||
const image = readGoBinaryImage(snapshot.bytes);
|
||||
const info = image.build_info;
|
||||
if (
|
||||
info !== null &&
|
||||
((info.module_text !== null &&
|
||||
Buffer.byteLength(info.module_text) > OUTPUT_BYTES) ||
|
||||
Buffer.byteLength(info.module_bytes_base64) > OUTPUT_BYTES)
|
||||
)
|
||||
throw outputLimit(input.path);
|
||||
const module =
|
||||
info === null
|
||||
? null
|
||||
: info.module_text === null
|
||||
? parseGoModuleBytes(
|
||||
Buffer.from(info.module_bytes_base64, "base64").subarray(
|
||||
16,
|
||||
-16,
|
||||
),
|
||||
)
|
||||
: parseGoModuleText(info.module_text);
|
||||
const report = {
|
||||
...image,
|
||||
artifact: {
|
||||
path: input.path,
|
||||
sha256: snapshot.sha256,
|
||||
bytes: snapshot.bytes.length,
|
||||
},
|
||||
build_info: info === null ? null : { ...info, module },
|
||||
limitations: [
|
||||
"Embedded build metadata is observed file content, not proof of compiler identity, dependency authenticity or runtime behavior.",
|
||||
"Only Go build information is inspected; function names, source mappings, type metadata and decompiled code are not recovered.",
|
||||
"Resource guards bound stable artifact reads to 256 MiB, aggregate embedded strings to 1 MiB, structural table decoding to 16 MiB and complete metadata payloads to 8 MiB; these are not operating-system memory or CPU limits.",
|
||||
...(info !== null &&
|
||||
(info.go_version === null || info.module_text === null)
|
||||
? [
|
||||
"Some embedded Go strings contain non-UTF8 bytes; undecodable text is null and exact source bytes are preserved as base64.",
|
||||
]
|
||||
: []),
|
||||
...(info === null
|
||||
? [
|
||||
"No recognized Go build-info record was found in the inspected image; absent metadata does not establish that the binary is not Go.",
|
||||
]
|
||||
: []),
|
||||
...(module?.complete === false
|
||||
? [
|
||||
"Some embedded module-text records could not be parsed completely; their original lines are preserved and additional metadata remains unknown.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
if (Buffer.byteLength(JSON.stringify(report), "utf8") > OUTPUT_BYTES)
|
||||
throw outputLimit(input.path);
|
||||
const parsed = goBinarySchema.safeParse(report);
|
||||
if (!parsed.success)
|
||||
throw new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"Go reader produced invalid source ranges or report values.",
|
||||
{ cause: parsed.error },
|
||||
);
|
||||
options?.signal?.throwIfAborted();
|
||||
return ok(parsed.data);
|
||||
} catch (cause: unknown) {
|
||||
return err(failureFor(cause, input.path, options?.signal));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import {
|
||||
GoBinaryFormatFailure,
|
||||
GoBinaryReader,
|
||||
mappedFileOffset,
|
||||
type GoBinaryContainer,
|
||||
type GoFileMapping,
|
||||
type GoZeroFillMapping,
|
||||
} from "./GoBinaryContainer.js";
|
||||
|
||||
/** Read ELF build-info sections and file-backed program mappings. */
|
||||
export const readGoElfImage = (bytes: Buffer): GoBinaryContainer => {
|
||||
if (bytes.length < 16)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF identification is truncated",
|
||||
);
|
||||
const bits = bytes[4] === 1 ? 32 : bytes[4] === 2 ? 64 : null;
|
||||
if (bits === null || ![1, 2].includes(bytes[5] ?? 0) || bytes[6] !== 1)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF class, byte order, or version is invalid",
|
||||
);
|
||||
const reader = new GoBinaryReader(bytes, bytes[5] === 1);
|
||||
const wide = bits === 64;
|
||||
const minimum = wide ? 64 : 52;
|
||||
reader.range(0, minimum, "ELF header");
|
||||
if (reader.u32(20) !== 1 || reader.u16(wide ? 52 : 40) < minimum)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF header version or size is invalid",
|
||||
);
|
||||
const headerSize = reader.u16(wide ? 52 : 40);
|
||||
reader.range(0, headerSize, "ELF declared header");
|
||||
const phOffset = reader.word(wide ? 32 : 28, bits);
|
||||
const shOffset = reader.word(wide ? 40 : 32, bits);
|
||||
const phWidth = reader.u16(wide ? 54 : 42);
|
||||
const shWidth = reader.u16(wide ? 58 : 46);
|
||||
let phCount = reader.u16(wide ? 56 : 44);
|
||||
let shCount = reader.u16(wide ? 60 : 48);
|
||||
let namesIndex = reader.u16(wide ? 62 : 50);
|
||||
if (
|
||||
(phCount !== 0 && phOffset < BigInt(headerSize)) ||
|
||||
(shOffset !== 0n && shOffset < BigInt(headerSize))
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF header table overlaps the native header",
|
||||
);
|
||||
if (
|
||||
shOffset !== 0n &&
|
||||
(shCount === 0 || phCount === 0xffff || namesIndex === 0xffff)
|
||||
) {
|
||||
if (shWidth < (wide ? 64 : 40))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF extended section header width is invalid",
|
||||
);
|
||||
const first = reader.fileRange(
|
||||
shOffset,
|
||||
BigInt(shWidth),
|
||||
"ELF section zero",
|
||||
).offset;
|
||||
if (reader.u32(first + 4) !== 0)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF initial section for extended numbering must have SHT_NULL type",
|
||||
);
|
||||
if (shCount === 0) {
|
||||
const count = reader.word(first + (wide ? 32 : 20), bits);
|
||||
if (count < 0xff00n || count > BigInt(Number.MAX_SAFE_INTEGER))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF extended section count is invalid",
|
||||
);
|
||||
shCount = Number(count);
|
||||
}
|
||||
if (phCount === 0xffff) {
|
||||
phCount = reader.u32(first + (wide ? 44 : 28));
|
||||
if (phCount < 0xffff)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF extended program count is below its reserved range",
|
||||
);
|
||||
}
|
||||
if (namesIndex === 0xffff) {
|
||||
namesIndex = reader.u32(first + (wide ? 40 : 24));
|
||||
if (namesIndex < 0xff00)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF extended section name index is below its reserved range",
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
shOffset === 0n &&
|
||||
(shCount !== 0 || namesIndex !== 0 || phCount === 0xffff)
|
||||
) {
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF section table is missing",
|
||||
);
|
||||
}
|
||||
if (phCount !== 0 && phWidth < (wide ? 56 : 32))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF program header width is invalid",
|
||||
);
|
||||
const phStart = reader.table(
|
||||
phOffset,
|
||||
phCount,
|
||||
phWidth,
|
||||
"ELF program headers",
|
||||
);
|
||||
const mappings: GoFileMapping[] = [];
|
||||
const zeroFills: GoZeroFillMapping[] = [];
|
||||
let fallback: GoFileMapping | null = null;
|
||||
for (let index = 0; index < phCount; index++) {
|
||||
const offset = phStart + index * phWidth;
|
||||
if (reader.u32(offset) !== 1) continue;
|
||||
const flags = reader.u32(offset + (wide ? 4 : 24));
|
||||
const fileOffset = reader.word(offset + (wide ? 8 : 4), bits);
|
||||
const address = reader.word(offset + (wide ? 16 : 8), bits);
|
||||
const size = reader.word(offset + (wide ? 32 : 16), bits);
|
||||
const memorySize = reader.word(offset + (wide ? 40 : 20), bits);
|
||||
if (size > memorySize || address + memorySize > 1n << BigInt(bits))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF load segment sizes or addresses are invalid",
|
||||
);
|
||||
const mapping = {
|
||||
...(size === 0n
|
||||
? { offset: 0, size: 0 }
|
||||
: reader.fileRange(fileOffset, size, "ELF load segment")),
|
||||
address,
|
||||
};
|
||||
if (mapping.size !== 0) mappings.push(mapping);
|
||||
if (memorySize > size)
|
||||
zeroFills.push({ address: address + size, size: memorySize - size });
|
||||
if (fallback === null && (flags & 3) === 2) fallback = mapping;
|
||||
}
|
||||
let search: GoFileMapping | null = null;
|
||||
if (shCount !== 0) {
|
||||
if (shWidth < (wide ? 64 : 40) || namesIndex >= shCount)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF section width or name-table index is invalid",
|
||||
);
|
||||
const shStart = reader.table(
|
||||
shOffset,
|
||||
shCount,
|
||||
shWidth,
|
||||
"ELF section headers",
|
||||
);
|
||||
if (namesIndex !== 0) {
|
||||
const namesHeader = shStart + namesIndex * shWidth;
|
||||
if (reader.u32(namesHeader + 4) !== 3)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF section name table is not a string table",
|
||||
);
|
||||
const names = reader.fileRange(
|
||||
reader.word(namesHeader + (wide ? 24 : 16), bits),
|
||||
reader.word(namesHeader + (wide ? 32 : 20), bits),
|
||||
"ELF section names",
|
||||
);
|
||||
for (let index = 0; index < shCount; index++) {
|
||||
const offset = shStart + index * shWidth;
|
||||
const nameOffset = reader.u32(offset);
|
||||
if (nameOffset >= names.size)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF section name offset is outside its string table",
|
||||
);
|
||||
// Comparing the complete fixed name avoids quadratic scans through malicious string tables.
|
||||
const expectedName = Buffer.from(".go.buildinfo\0");
|
||||
if (
|
||||
expectedName.length > names.size - nameOffset ||
|
||||
!bytes
|
||||
.subarray(
|
||||
names.offset + nameOffset,
|
||||
names.offset + nameOffset + expectedName.length,
|
||||
)
|
||||
.equals(expectedName)
|
||||
)
|
||||
continue;
|
||||
if (search !== null)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF contains ambiguous build-info sections",
|
||||
);
|
||||
if (reader.u32(offset + 4) !== 1)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF build-info section is not file-backed data",
|
||||
);
|
||||
if ((reader.word(offset + 8, bits) & 0x800n) !== 0n)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"unsupported",
|
||||
"Compressed ELF build-info sections are unsupported",
|
||||
);
|
||||
const address = reader.word(offset + (wide ? 16 : 12), bits);
|
||||
search = {
|
||||
...reader.fileRange(
|
||||
reader.word(offset + (wide ? 24 : 16), bits),
|
||||
reader.word(offset + (wide ? 32 : 20), bits),
|
||||
"ELF build-info section",
|
||||
),
|
||||
address,
|
||||
};
|
||||
if (
|
||||
mappedFileOffset(mappings, address, search.size, zeroFills) !==
|
||||
search.offset
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"ELF build-info section disagrees with its load mapping",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
const machine = reader.u16(18);
|
||||
return {
|
||||
format: "elf",
|
||||
architecture: elfArchitecture(machine),
|
||||
bits,
|
||||
byte_order: reader.little ? "little" : "big",
|
||||
mappings,
|
||||
zero_fills: zeroFills,
|
||||
search: search ?? fallback,
|
||||
};
|
||||
};
|
||||
|
||||
const elfArchitecture = (machine: number): string => {
|
||||
const names = new Map([
|
||||
[3, "386"],
|
||||
[8, "mips"],
|
||||
[20, "ppc"],
|
||||
[21, "ppc64"],
|
||||
[22, "s390"],
|
||||
[40, "arm"],
|
||||
[62, "amd64"],
|
||||
[183, "arm64"],
|
||||
[243, "riscv"],
|
||||
[258, "loongarch"],
|
||||
]);
|
||||
return names.get(machine) ?? `elf-machine-${machine}`;
|
||||
};
|
||||
@@ -0,0 +1,168 @@
|
||||
import {
|
||||
GoBinaryFormatFailure,
|
||||
GoBinaryReader,
|
||||
mappedFileOffset,
|
||||
type GoBinaryContainer,
|
||||
type GoFileMapping,
|
||||
type GoZeroFillMapping,
|
||||
} from "./GoBinaryContainer.js";
|
||||
|
||||
/** Read thin Mach-O images, retaining the slice's exact file-backed mappings. */
|
||||
export const readGoMachoImage = (bytes: Buffer): GoBinaryContainer => {
|
||||
const magic = bytes.readUInt32BE(0);
|
||||
const little = magic === 0xcefaedfe || magic === 0xcffaedfe;
|
||||
const bits = magic === 0xfeedfacf || magic === 0xcffaedfe ? 64 : 32;
|
||||
const reader = new GoBinaryReader(bytes, little);
|
||||
const headerSize = bits === 64 ? 32 : 28;
|
||||
reader.range(0, headerSize, "Mach-O header");
|
||||
const count = reader.u32(16);
|
||||
const commandBytes = reader.u32(20);
|
||||
const commandStart = reader.table(
|
||||
BigInt(headerSize),
|
||||
commandBytes,
|
||||
1,
|
||||
"Mach-O load commands",
|
||||
);
|
||||
if (count > Math.floor(commandBytes / 8))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O command count exceeds its load-command range",
|
||||
);
|
||||
const mappings: GoFileMapping[] = [];
|
||||
const zeroFills: GoZeroFillMapping[] = [];
|
||||
const named: GoFileMapping[] = [];
|
||||
let fallback: GoFileMapping | null = null;
|
||||
let offset = commandStart;
|
||||
const end = commandStart + commandBytes;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const command = reader.u32(offset);
|
||||
const size = reader.u32(offset + 4);
|
||||
if (size < 8 || size % 4 !== 0 || size > end - offset)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O load command size is invalid or truncated",
|
||||
);
|
||||
if (command === 1 || command === 0x19) {
|
||||
const wide = command === 0x19;
|
||||
if (wide !== (bits === 64))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O segment command does not match the header width",
|
||||
);
|
||||
const segmentHeader = wide ? 72 : 56;
|
||||
const sectionWidth = wide ? 80 : 68;
|
||||
if (size < segmentHeader)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O segment header is truncated",
|
||||
);
|
||||
const address = reader.word(offset + 24, bits);
|
||||
const memorySize = reader.word(offset + (wide ? 32 : 28), bits);
|
||||
const fileOffset = reader.word(offset + (wide ? 40 : 32), bits);
|
||||
const fileSize = reader.word(offset + (wide ? 48 : 36), bits);
|
||||
const maxProtection = reader.u32(offset + (wide ? 56 : 40));
|
||||
const protection = reader.u32(offset + (wide ? 60 : 44));
|
||||
const sectionCount = reader.u32(offset + (wide ? 64 : 48));
|
||||
if (fileSize > memorySize || address + memorySize > 1n << BigInt(bits))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O segment addresses or sizes are invalid",
|
||||
);
|
||||
if (sectionCount > Math.floor((size - segmentHeader) / sectionWidth))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O section table exceeds its segment command",
|
||||
);
|
||||
const mapping = {
|
||||
...(fileSize === 0n
|
||||
? { offset: 0, size: 0 }
|
||||
: reader.fileRange(fileOffset, fileSize, "Mach-O segment")),
|
||||
address,
|
||||
};
|
||||
const name = fixedName(
|
||||
reader.range(offset + 8, 16, "Mach-O segment name"),
|
||||
);
|
||||
if (mapping.size !== 0 && name !== "__PAGEZERO") mappings.push(mapping);
|
||||
if (memorySize > fileSize && name !== "__PAGEZERO")
|
||||
zeroFills.push({
|
||||
address: address + fileSize,
|
||||
size: memorySize - fileSize,
|
||||
});
|
||||
if (
|
||||
fallback === null &&
|
||||
address !== 0n &&
|
||||
mapping.size !== 0 &&
|
||||
protection === 3 &&
|
||||
maxProtection === 3
|
||||
)
|
||||
fallback = mapping;
|
||||
for (let sectionIndex = 0; sectionIndex < sectionCount; sectionIndex++) {
|
||||
const section = offset + segmentHeader + sectionIndex * sectionWidth;
|
||||
if (
|
||||
fixedName(reader.range(section, 16, "Mach-O section name")) !==
|
||||
"__go_buildinfo"
|
||||
)
|
||||
continue;
|
||||
const sectionFlags = reader.u32(section + (wide ? 64 : 56));
|
||||
if ([1, 0xc, 0x12].includes(sectionFlags & 0xff))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O build-info section is zero-fill data",
|
||||
);
|
||||
const sectionAddress = reader.word(section + 32, bits);
|
||||
const sectionSize = reader.word(section + (wide ? 40 : 36), bits);
|
||||
const sectionOffset = BigInt(reader.u32(section + (wide ? 48 : 40)));
|
||||
const info = {
|
||||
...reader.fileRange(
|
||||
sectionOffset,
|
||||
sectionSize,
|
||||
"Mach-O build-info section",
|
||||
),
|
||||
address: sectionAddress,
|
||||
};
|
||||
if (
|
||||
mappedFileOffset([mapping], sectionAddress, info.size) !== info.offset
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O build-info section disagrees with its segment",
|
||||
);
|
||||
named.push(info);
|
||||
}
|
||||
}
|
||||
offset += size;
|
||||
}
|
||||
if (offset !== end)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O load-command byte count does not match its commands",
|
||||
);
|
||||
if (named.length > 1)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"Mach-O has ambiguous build-info sections",
|
||||
);
|
||||
const cpu = reader.u32(4);
|
||||
const names = new Map([
|
||||
[7, "386"],
|
||||
[0x01000007, "amd64"],
|
||||
[12, "arm"],
|
||||
[0x0100000c, "arm64"],
|
||||
[18, "ppc"],
|
||||
[0x01000012, "ppc64"],
|
||||
]);
|
||||
return {
|
||||
format: "macho",
|
||||
architecture: names.get(cpu) ?? `macho-cpu-${cpu}`,
|
||||
bits,
|
||||
byte_order: little ? "little" : "big",
|
||||
mappings,
|
||||
zero_fills: zeroFills,
|
||||
search: named[0] ?? fallback,
|
||||
};
|
||||
};
|
||||
|
||||
const fixedName = (bytes: Buffer): string => {
|
||||
const nul = bytes.indexOf(0);
|
||||
return bytes.subarray(0, nul < 0 ? bytes.length : nul).toString("latin1");
|
||||
};
|
||||
@@ -0,0 +1,226 @@
|
||||
import type { GoModule, GoModuleMetadata } from "../domain/go/goBinary.js";
|
||||
|
||||
const utf8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
||||
const escapes = new Map([
|
||||
["a", 7],
|
||||
["b", 8],
|
||||
["f", 12],
|
||||
["n", 10],
|
||||
["r", 13],
|
||||
["t", 9],
|
||||
["v", 11],
|
||||
["\\", 92],
|
||||
['"', 34],
|
||||
]);
|
||||
|
||||
const quoted = (input: string): { value: string; end: number } | null => {
|
||||
if (input.startsWith("`")) {
|
||||
const end = input.indexOf("`", 1);
|
||||
return end < 0
|
||||
? null
|
||||
: { value: input.slice(1, end).replace(/\r/g, ""), end: end + 1 };
|
||||
}
|
||||
if (!input.startsWith('"')) return null;
|
||||
const output = Buffer.alloc(input.length * 3);
|
||||
let length = 0;
|
||||
for (let index = 1; index < input.length;) {
|
||||
const character = input[index];
|
||||
if (character === '"') {
|
||||
try {
|
||||
return {
|
||||
value: utf8.decode(output.subarray(0, length)),
|
||||
end: index + 1,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (character === "\n") return null;
|
||||
if (character !== "\\") {
|
||||
const point = input.codePointAt(index);
|
||||
if (point === undefined) return null;
|
||||
length += output.write(String.fromCodePoint(point), length, "utf8");
|
||||
index += point > 0xffff ? 2 : 1;
|
||||
continue;
|
||||
}
|
||||
const escaped = input[index + 1];
|
||||
if (escaped === undefined) return null;
|
||||
const simple = escapes.get(escaped);
|
||||
if (simple !== undefined) {
|
||||
output[length++] = simple;
|
||||
index += 2;
|
||||
continue;
|
||||
}
|
||||
const digits =
|
||||
escaped === "x" ? 2 : escaped === "u" ? 4 : escaped === "U" ? 8 : 0;
|
||||
if (digits > 0) {
|
||||
const encoded = input.slice(index + 2, index + 2 + digits);
|
||||
if (encoded.length !== digits || !/^[a-f\d]+$/i.test(encoded))
|
||||
return null;
|
||||
const point = Number.parseInt(encoded, 16);
|
||||
if (escaped === "x") output[length++] = point;
|
||||
else {
|
||||
if (point > 0x10ffff || (point >= 0xd800 && point <= 0xdfff))
|
||||
return null;
|
||||
length += output.write(String.fromCodePoint(point), length, "utf8");
|
||||
}
|
||||
index += 2 + digits;
|
||||
continue;
|
||||
}
|
||||
const octal = input.slice(index + 1, index + 4);
|
||||
if (!/^[0-7]{3}$/.test(octal)) return null;
|
||||
const byte = Number.parseInt(octal, 8);
|
||||
if (byte > 255) return null;
|
||||
output[length++] = byte;
|
||||
index += 4;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const setting = (input: string): { key: string; value: string } | null => {
|
||||
let key: string;
|
||||
let rawValue: string;
|
||||
if (input.startsWith('"') || input.startsWith("`")) {
|
||||
const decoded = quoted(input);
|
||||
if (decoded === null || input[decoded.end] !== "=") return null;
|
||||
key = decoded.value;
|
||||
rawValue = input.slice(decoded.end + 1);
|
||||
} else {
|
||||
const separator = input.indexOf("=");
|
||||
if (separator < 1) return null;
|
||||
key = input.slice(0, separator);
|
||||
if (/[= \t\r\n"`]/.test(key)) return null;
|
||||
rawValue = input.slice(separator + 1);
|
||||
}
|
||||
if (rawValue.startsWith('"') || rawValue.startsWith("`")) {
|
||||
const decoded = quoted(rawValue);
|
||||
return decoded !== null && decoded.end === rawValue.length
|
||||
? { key, value: decoded.value }
|
||||
: null;
|
||||
}
|
||||
return /[ \t\r\n"`]/.test(rawValue) ? null : { key, value: rawValue };
|
||||
};
|
||||
|
||||
const moduleLine = (fields: string[]): GoModule | null => {
|
||||
const [path, version] = fields;
|
||||
if (
|
||||
(fields.length !== 2 && fields.length !== 3) ||
|
||||
path === undefined ||
|
||||
version === undefined
|
||||
)
|
||||
return null;
|
||||
return { path, version, sum: fields[2] ?? null, replacement: null };
|
||||
};
|
||||
|
||||
interface ModuleSourceLine {
|
||||
readonly line: string | Buffer;
|
||||
readonly terminated: boolean;
|
||||
}
|
||||
|
||||
function* moduleSourceLines(
|
||||
source: string | Buffer,
|
||||
): Generator<ModuleSourceLine> {
|
||||
let start = 0;
|
||||
while (start < source.length) {
|
||||
const newline =
|
||||
typeof source === "string"
|
||||
? source.indexOf("\n", start)
|
||||
: source.indexOf(10, start);
|
||||
const end = newline < 0 ? source.length : newline;
|
||||
let line: string | Buffer;
|
||||
if (typeof source === "string") line = source.slice(start, end);
|
||||
else {
|
||||
const bytes = source.subarray(start, end);
|
||||
try {
|
||||
line = utf8.decode(bytes);
|
||||
} catch {
|
||||
line = bytes;
|
||||
}
|
||||
}
|
||||
yield { line, terminated: newline >= 0 };
|
||||
if (newline < 0) return;
|
||||
start = newline + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const modulePrefixes = ["mod\t", "dep\t", "=>\t"].map((prefix) =>
|
||||
Buffer.from(prefix),
|
||||
);
|
||||
|
||||
const parseModuleRecords = (source: string | Buffer): GoModuleMetadata => {
|
||||
let path: string | null = null;
|
||||
let main: GoModule | null = null;
|
||||
const dependencies: GoModule[] = [];
|
||||
const settings: { key: string; value: string }[] = [];
|
||||
const unparsed_lines: string[] = [];
|
||||
const unparsed_line_bytes_base64: string[] = [];
|
||||
let last: GoModule | null = null;
|
||||
for (const { line, terminated } of moduleSourceLines(source)) {
|
||||
if (typeof line !== "string") {
|
||||
unparsed_line_bytes_base64.push(line.toString("base64"));
|
||||
if (
|
||||
modulePrefixes.some((prefix) =>
|
||||
line.subarray(0, prefix.length).equals(prefix),
|
||||
)
|
||||
)
|
||||
last = null;
|
||||
continue;
|
||||
}
|
||||
if (line === "") continue;
|
||||
if (!terminated) {
|
||||
unparsed_lines.push(line);
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("path\t") && path === null) {
|
||||
path = line.slice(5);
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith("mod\t") || line.startsWith("dep\t")) {
|
||||
const value = moduleLine(line.slice(4).split("\t"));
|
||||
last = null;
|
||||
if (value !== null && (!line.startsWith("mod\t") || main === null)) {
|
||||
if (line.startsWith("mod\t")) main = value;
|
||||
else dependencies.push(value);
|
||||
last = value;
|
||||
continue;
|
||||
}
|
||||
} else if (line.startsWith("=>\t")) {
|
||||
const fields = line.slice(3).split("\t");
|
||||
const value = moduleLine(fields);
|
||||
if (fields.length === 3 && value !== null && last !== null) {
|
||||
last.replacement = {
|
||||
path: value.path,
|
||||
version: value.version,
|
||||
sum: value.sum,
|
||||
};
|
||||
last = null;
|
||||
continue;
|
||||
}
|
||||
last = null;
|
||||
} else if (line.startsWith("build\t")) {
|
||||
const value = setting(line.slice(6));
|
||||
if (value !== null) {
|
||||
settings.push(value);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
unparsed_lines.push(line);
|
||||
}
|
||||
return {
|
||||
path,
|
||||
main,
|
||||
dependencies,
|
||||
settings,
|
||||
unparsed_lines,
|
||||
unparsed_line_bytes_base64,
|
||||
complete: unparsed_lines.length + unparsed_line_bytes_base64.length === 0,
|
||||
};
|
||||
};
|
||||
|
||||
/** Decode Go's module records while preserving unsupported/malformed source lines. */
|
||||
export const parseGoModuleText = (text: string): GoModuleMetadata =>
|
||||
parseModuleRecords(text);
|
||||
|
||||
/** Decode an unframed Go module body while retaining non-UTF-8 line bytes exactly. */
|
||||
export const parseGoModuleBytes = (bytes: Buffer): GoModuleMetadata =>
|
||||
parseModuleRecords(bytes);
|
||||
@@ -0,0 +1,149 @@
|
||||
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../domain/dosMz.js";
|
||||
import {
|
||||
GoBinaryFormatFailure,
|
||||
GoBinaryReader,
|
||||
type GoBinaryContainer,
|
||||
type GoFileMapping,
|
||||
type GoZeroFillMapping,
|
||||
} from "./GoBinaryContainer.js";
|
||||
|
||||
const peHeaderOffset = (reader: GoBinaryReader): number => {
|
||||
const pe = mzWindowsHeaderOffset(reader.bytes);
|
||||
if (pe === null) {
|
||||
const dos = parseDosMzHeader(reader.bytes);
|
||||
if (!dos.ok) throw new GoBinaryFormatFailure("malformed", dos.error);
|
||||
throw new GoBinaryFormatFailure(
|
||||
"unsupported",
|
||||
"DOS MZ images are outside the supported ELF, PE and thin Mach-O formats",
|
||||
);
|
||||
}
|
||||
if (pe < 64)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"PE signature overlaps the DOS header",
|
||||
);
|
||||
const signature = reader
|
||||
.range(pe, 2, "Windows new-header signature")
|
||||
.toString("latin1");
|
||||
if (["NE", "LE", "LX"].includes(signature))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"unsupported",
|
||||
`${signature} images are outside the supported ELF, PE and thin Mach-O formats`,
|
||||
);
|
||||
return pe;
|
||||
};
|
||||
|
||||
const optionalHeaderMagic = (
|
||||
reader: GoBinaryReader,
|
||||
offset: number,
|
||||
size: number,
|
||||
): number => {
|
||||
reader.range(offset, size, "PE optional header");
|
||||
if (size < 2)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"PE optional header is missing its complete magic field",
|
||||
);
|
||||
return reader.u16(offset);
|
||||
};
|
||||
|
||||
/** Read PE32/PE32+ native image mappings and the linker data section. */
|
||||
export const readGoPeImage = (bytes: Buffer): GoBinaryContainer => {
|
||||
const reader = new GoBinaryReader(bytes, true);
|
||||
const pe = peHeaderOffset(reader);
|
||||
if (
|
||||
!reader
|
||||
.range(pe, 24, "PE signature and COFF header")
|
||||
.subarray(0, 4)
|
||||
.equals(Buffer.from("PE\0\0"))
|
||||
)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"PE signature is invalid or overlaps the DOS header",
|
||||
);
|
||||
const optional = pe + 24;
|
||||
const optionalSize = reader.u16(pe + 20);
|
||||
const magic = optionalHeaderMagic(reader, optional, optionalSize);
|
||||
const bits = magic === 0x10b ? 32 : magic === 0x20b ? 64 : null;
|
||||
if (bits === null)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"unsupported",
|
||||
"Only PE32 and PE32+ image optional headers are supported",
|
||||
);
|
||||
if (optionalSize < (bits === 64 ? 112 : 96))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"PE optional header is truncated",
|
||||
);
|
||||
const directoriesOffset = bits === 64 ? 112 : 96;
|
||||
const directories = reader.u32(optional + directoriesOffset - 4);
|
||||
if (directories * 8 > optionalSize - directoriesOffset)
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"PE data directories extend beyond the optional header",
|
||||
);
|
||||
const imageBase = reader.word(optional + (bits === 64 ? 24 : 28), bits);
|
||||
const count = reader.u16(pe + 6);
|
||||
const start = reader.table(
|
||||
BigInt(optional + optionalSize),
|
||||
count,
|
||||
40,
|
||||
"PE sections",
|
||||
);
|
||||
const mappings: GoFileMapping[] = [];
|
||||
const zeroFills: GoZeroFillMapping[] = [];
|
||||
let search: GoFileMapping | null = null;
|
||||
for (let index = 0; index < count; index++) {
|
||||
const entry = start + index * 40;
|
||||
const virtualSize = reader.u32(entry + 8);
|
||||
const virtualAddress = reader.u32(entry + 12);
|
||||
const size = reader.u32(entry + 16);
|
||||
const offset = reader.u32(entry + 20);
|
||||
const characteristics = reader.u32(entry + 36);
|
||||
const address = imageBase + BigInt(virtualAddress);
|
||||
if (address + BigInt(Math.max(size, virtualSize)) > 1n << BigInt(bits))
|
||||
throw new GoBinaryFormatFailure(
|
||||
"malformed",
|
||||
"PE section virtual address overflows its address width",
|
||||
);
|
||||
const mapping = {
|
||||
...(size === 0
|
||||
? { offset: 0, size: 0 }
|
||||
: reader.fileRange(BigInt(offset), BigInt(size), "PE section")),
|
||||
address,
|
||||
};
|
||||
if (size !== 0) mappings.push(mapping);
|
||||
if (virtualSize > size)
|
||||
zeroFills.push({
|
||||
address: address + BigInt(size),
|
||||
size: BigInt(virtualSize - size),
|
||||
});
|
||||
// Match debug/buildinfo's first initialized, readable, writable data section.
|
||||
if (
|
||||
search === null &&
|
||||
virtualAddress !== 0 &&
|
||||
size !== 0 &&
|
||||
(characteristics & ~0x00600000) >>> 0 === 0xc0000040
|
||||
) {
|
||||
search = { ...mapping, size: Math.min(size, virtualSize) };
|
||||
}
|
||||
}
|
||||
const machine = reader.u16(pe + 4);
|
||||
const names = new Map([
|
||||
[0x014c, "386"],
|
||||
[0x8664, "amd64"],
|
||||
[0x01c0, "arm"],
|
||||
[0x01c2, "arm"],
|
||||
[0x01c4, "arm"],
|
||||
[0xaa64, "arm64"],
|
||||
]);
|
||||
return {
|
||||
format: "pe",
|
||||
architecture: names.get(machine) ?? `pe-machine-${machine}`,
|
||||
bits,
|
||||
byte_order: "little",
|
||||
mappings,
|
||||
zero_fills: zeroFills,
|
||||
search,
|
||||
};
|
||||
};
|
||||
@@ -177,6 +177,9 @@ export class PwntoolsDecoder<
|
||||
requestPath,
|
||||
],
|
||||
cwd: root.path,
|
||||
// Caller-selected Python launchers can exec through prlimit or a
|
||||
// shell wrapper. Keep parent/group/run-token ownership across exec.
|
||||
expectedCommand: null,
|
||||
runId: `rea-artifact-decoder-${randomUUID()}`,
|
||||
hostEnvironment: {
|
||||
...this.environment,
|
||||
|
||||
@@ -9,6 +9,9 @@ import { createEvmInterfaceService } from "../composition/evm.js";
|
||||
import { registerEvmTools } from "./registerEvmTools.js";
|
||||
import { registerRecordedCrashTools } from "./registerRecordedCrashTools.js";
|
||||
import { createRecordedCrashService } from "../composition/binaryDiagnostics.js";
|
||||
import { createGoBinaryService } from "../composition/go.js";
|
||||
import type { GoBinaryService } from "../application/go/GoBinaryService.js";
|
||||
import { registerGoTools } from "./registerGoTools.js";
|
||||
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
|
||||
import { registerAnalysisViewTool } from "./registerAnalysisViewTool.js";
|
||||
import { registerBinaryDiagnosticsTools } from "./registerBinaryDiagnosticsTools.js";
|
||||
@@ -110,6 +113,7 @@ export interface CreateServerOptions {
|
||||
readonly evmInterface?: EvmInterfaceService;
|
||||
readonly logger?: Logger;
|
||||
readonly binaryLayout?: BinaryLayoutService;
|
||||
readonly goBinary?: GoBinaryService;
|
||||
readonly recordedCrash?: RecordedCrashService;
|
||||
readonly firmwareAnalysis?: FirmwareAnalysisPort;
|
||||
readonly javascriptRecovery?: JavaScriptRecoveryPort;
|
||||
@@ -435,6 +439,13 @@ const registerConfiguredAnalysisTools = (
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
registerGoTools(
|
||||
server,
|
||||
options.goBinary ?? createGoBinaryService(),
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
registerWasmTools(
|
||||
server,
|
||||
wasmArtifact,
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import type { GoBinaryService } from "../application/go/GoBinaryService.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { Logger } from "pino";
|
||||
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
|
||||
import { createEvidenceToolHandler } from "./contractToolHandler.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
|
||||
/** Bind the exact Go contract to its shared workflow and owning session Evidence ledger. */
|
||||
export const registerGoTools = (
|
||||
server: EvidenceMcpServer,
|
||||
service: GoBinaryService,
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
): void => {
|
||||
const contract = toolContract("inspect_go_binary");
|
||||
const handler = createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.inspect(input, options),
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
);
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
handler(contract),
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user