feat(dotnet): add managed artifact triage

This commit is contained in:
N0zoM1z0
2026-07-16 17:05:03 +09:00
committed by N0zoM1z0
parent 80faff3e5b
commit c251c38aa2
155 changed files with 4101 additions and 287 deletions
+2
View File
@@ -3,6 +3,7 @@ import type { OfficialToolName } from "../contracts/toolContracts.js";
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
import type { ManagedToolName } from "../contracts/managedToolContracts.js";
import type { AnalysisError } from "../domain/errors.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -24,6 +25,7 @@ export type AnalysisOperation =
| EnhancedToolName
| NativeToolName
| ArtifactToolName
| ManagedToolName
| "health";
/** Atomic successful provider observation with exact producing provenance. */
+32 -7
View File
@@ -9,6 +9,7 @@ import { createEvidence } from "../domain/evidence.js";
import type { Evidence } from "../domain/evidence.js";
import type { NativeToolName } from "../contracts/nativeToolContracts.js";
import type { ArtifactToolName } from "../contracts/artifactToolContracts.js";
import type { ManagedToolName } from "../contracts/managedToolContracts.js";
import {
EvidenceIntegrityError,
AnalysisProtocolError,
@@ -84,7 +85,7 @@ export const runDirectAnalysis = async (
/** Execute one provider-native semantic operation with atomic provenance. */
export const runProviderAnalysis = async (
path: string,
tool: NativeToolName | ArtifactToolName,
tool: NativeToolName | ArtifactToolName | ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
logger: Logger = silentLogger,
signal?: AbortSignal,
@@ -118,7 +119,11 @@ export const runSessionStatus = async (
const authorizeAnalysis = async (
authority: PermissionAuthority,
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool,
arguments_: Readonly<Record<string, JsonValue>>,
): Promise<Result<null, AnalysisError>> => {
const requests = [];
@@ -188,7 +193,11 @@ const permissionAuthorityFor = (
const authorizeSnapshotAccess = async (
authority: PermissionAuthority,
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool,
snapshotPath: string | undefined,
): Promise<
Result<DeferredFileWriteAuthorization | undefined, AnalysisError>
@@ -210,7 +219,11 @@ const authorizeDeferredWrite = (
const authorizeAnalysisRun = async (input: {
readonly config: AppConfig;
readonly suppliedAuthority: PermissionAuthority | undefined;
readonly tool: NativeToolName | ArtifactToolName | DirectAnalysisTool;
readonly tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool;
readonly arguments: Readonly<Record<string, JsonValue>>;
readonly snapshotPath: string | undefined;
}): Promise<
@@ -236,7 +249,11 @@ const authorizeAnalysisRun = async (input: {
const runAnalysis = async (
path: string,
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool,
arguments_: Readonly<Record<string, JsonValue>>,
options: {
readonly logger: Logger;
@@ -405,7 +422,11 @@ const prepareSnapshot = async (options: {
const replayProviderFor = (
session: ReturnType<typeof createBinarySession>,
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool,
) =>
tool === "binary_overview" || tool === "trace_feature"
? REA_WORKFLOW_PROVIDER
@@ -413,7 +434,11 @@ const replayProviderFor = (
const analysisProfileForEvidence = (
session: ReturnType<typeof createBinarySession>,
tool: NativeToolName | ArtifactToolName | DirectAnalysisTool,
tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
if (tool !== "binary_overview" && tool !== "trace_feature")
return session.analysisProfile(tool);
@@ -25,6 +25,13 @@ export const ARTIFACT_GRAPH_PROVIDER = {
version: "1",
} as const;
/** Provider identity for execution-free managed PE/CLI analysis. */
export const MANAGED_STATIC_PROVIDER = {
id: "rea-dotnet-static",
name: "REA managed static analysis provider",
version: "1",
} as const;
/** Provider identity for deterministic static JavaScript application analysis. */
export const JAVASCRIPT_APPLICATION_PROVIDER = {
id: "rea-javascript-application",
+2
View File
@@ -4,6 +4,7 @@ import { HopperProvider } from "../hopper/HopperProvider.js";
import { GhidraProvider } from "../ghidra/GhidraProvider.js";
import { NativeMacOSProvider } from "../native/NativeMacOSProvider.js";
import { ArtifactProvider } from "../artifacts/ArtifactProvider.js";
import { ManagedStaticProvider } from "../dotnet/ManagedStaticProvider.js";
import { silentLogger, type Logger } from "../logger.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { SessionProviderRouter } from "./SessionProviderRouter.js";
@@ -28,6 +29,7 @@ export const createBinarySession = (
config.artifactIntegrityContinueEnabled,
),
new NativeMacOSProvider(),
new ManagedStaticProvider(),
],
),
);
+72
View File
@@ -82,6 +82,7 @@ export const createCli = (): ReturnType<typeof Cli.create> => {
registerCapabilityCommands(cli, logger);
registerNativeCommands(cli, logger);
registerArtifactCommands(cli, logger);
registerManagedCommands(cli, logger);
registerInvestigationCommands(cli, logger);
registerEvidenceCommands(cli, logger);
registerReferenceSourceCommand(cli, logger);
@@ -549,6 +550,77 @@ const registerArtifactCommands = (
});
};
const registerManagedCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.inspectManagedArtifact, {
description: "Inspect PE/CLI identity without loading target code",
args: z.object({
path: z.string().describe("Managed PE executable or assembly path"),
}),
options: z.object({
referenceOffset: z.number().int().min(0).default(0),
referenceLimit: z.number().int().min(1).max(500).default(100),
resourceOffset: z.number().int().min(0).default(0),
resourceLimit: z.number().int().min(1).max(500).default(100),
attributeOffset: z.number().int().min(0).default(0),
attributeLimit: z.number().int().min(1).max(500).default(100),
maxFileBytes: z
.number()
.int()
.min(4_096)
.max(1_073_741_824)
.default(268_435_456),
maxMetadataBytes: z
.number()
.int()
.min(256)
.max(268_435_456)
.default(67_108_864),
maxTableRows: z.number().int().min(1).max(10_000_000).default(1_000_000),
maxHeapItemBytes: z
.number()
.int()
.min(1)
.max(16_777_216)
.default(1_048_576),
}),
alias: {
referenceOffset: "reference-offset",
referenceLimit: "reference-limit",
resourceOffset: "resource-offset",
resourceLimit: "resource-limit",
attributeOffset: "attribute-offset",
attributeLimit: "attribute-limit",
maxFileBytes: "max-file-bytes",
maxMetadataBytes: "max-metadata-bytes",
maxTableRows: "max-table-rows",
maxHeapItemBytes: "max-heap-item-bytes",
},
run: ({ args, options }) =>
logCliCommand(logger, "inspect-managed-artifact", () =>
runProviderAnalysis(
args.path,
"inspect_managed_artifact",
{
reference_offset: options.referenceOffset,
reference_limit: options.referenceLimit,
resource_offset: options.resourceOffset,
resource_limit: options.resourceLimit,
attribute_offset: options.attributeOffset,
attribute_limit: options.attributeLimit,
max_file_bytes: options.maxFileBytes,
max_metadata_bytes: options.maxMetadataBytes,
max_table_rows: options.maxTableRows,
max_heap_item_bytes: options.maxHeapItemBytes,
},
logger,
),
),
});
};
const registerNativeCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
+1
View File
@@ -16,6 +16,7 @@ export const CLI_COMMANDS = Object.freeze({
importReferenceSource: "import-reference-source",
inventoryArtifact: "inventory-artifact",
extractArtifact: "extract-artifact",
inspectManagedArtifact: "inspect-managed-artifact",
inspectMacho: "inspect-macho",
inspectSignature: "inspect-signature",
listArchitectures: "list-architectures",
+64
View File
@@ -0,0 +1,64 @@
import { z } from "zod";
import type { ToolContract } from "./toolContracts.js";
import { managedOutputSchemas } from "./toolOutputSchemas.js";
/** Exact caller boundary for execution-free PE/CLI triage and identity. */
export const managedArtifactInputSchema = z.object({
reference_offset: z.number().int().min(0).default(0),
reference_limit: z.number().int().min(1).max(500).default(100),
resource_offset: z.number().int().min(0).default(0),
resource_limit: z.number().int().min(1).max(500).default(100),
attribute_offset: z.number().int().min(0).default(0),
attribute_limit: z.number().int().min(1).max(500).default(100),
max_file_bytes: z
.number()
.int()
.min(4_096)
.max(1_073_741_824)
.default(268_435_456),
max_metadata_bytes: z
.number()
.int()
.min(256)
.max(268_435_456)
.default(67_108_864),
max_table_rows: z.number().int().min(1).max(1_000_000).default(100_000),
max_heap_item_bytes: z
.number()
.int()
.min(1)
.max(16_777_216)
.default(1_048_576),
});
const outputSchema = managedOutputSchemas.inspect_managed_artifact;
if (outputSchema === undefined)
throw new Error("Missing managed output schema for inspect_managed_artifact");
/** Read-only managed artifact contracts. */
export const MANAGED_TOOL_CONTRACTS = [
{
name: "inspect_managed_artifact",
description:
"Classify the active PE/CLI artifact and inventory exact assembly/module identity, target framework evidence, references, resources, and custom attributes without loading or executing target code. Returns bounded pages and explicit partial or malformed coverage.",
kind: "managed-provider",
inputSchema: managedArtifactInputSchema,
outputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Example inspect managed artifact request",
input: {},
},
],
},
] as const satisfies readonly ToolContract[];
/** Names of execution-free managed static operations. */
export type ManagedToolName = (typeof MANAGED_TOOL_CONTRACTS)[number]["name"];
+1
View File
@@ -22,6 +22,7 @@ export type ToolKind =
| "enhanced"
| "native-provider"
| "artifact-provider"
| "managed-provider"
| "browser-provider"
| "electron-provider"
| "application"
+2
View File
@@ -26,6 +26,7 @@ import {
import { TOOL_EXAMPLE_OVERRIDES } from "./toolContractExamples.js";
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
@@ -525,6 +526,7 @@ export const TOOL_CONTRACTS = [
...ENHANCED_TOOL_CONTRACTS,
...NATIVE_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...BROWSER_TOOL_CONTRACTS,
...ELECTRON_TOOL_CONTRACTS,
...APPLICATION_TOOL_CONTRACTS,
+6
View File
@@ -24,6 +24,7 @@ import {
artifactExtractionResultSchema,
artifactInventoryResultSchema,
} from "../domain/artifactGraph.js";
import { managedArtifactInspectionSchema } from "../domain/managedArtifact.js";
import { artifactComparisonResultSchema } from "../domain/artifactComparison.js";
import { functionComparisonResultSchema } from "../domain/functionComparison.js";
import { bundleComparisonResultSchema } from "../domain/bundleComparison.js";
@@ -529,6 +530,11 @@ export const artifactOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
extract_artifact: resultOf(artifactExtractionResultSchema),
};
/** Exact Evidence v2 schema for execution-free managed static analysis. */
export const managedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_managed_artifact: resultOf(managedArtifactInspectionSchema),
};
/** Exact structured-content schemas for target lifecycle operations. */
export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
open_binary: lifecycleResultOf(
+205
View File
@@ -0,0 +1,205 @@
import { z } from "zod";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const offsetSchema = z.number().int().min(0);
const managedPage = <Item extends z.ZodType>(item: Item) =>
z.object({
items: z.array(item),
offset: offsetSchema,
limit: z.number().int().min(1),
total: z.number().int().min(0),
returned: z.number().int().min(0),
dropped: z.number().int().min(0),
complete: z.boolean(),
});
const publicKeyIdentitySchema = z.object({
kind: z.enum(["none", "public-key", "public-key-token"]),
byte_length: z.number().int().min(0),
sha256: digestSchema.nullable(),
token: z
.string()
.regex(/^[a-f0-9]{16}$/u)
.nullable(),
});
const assemblyIdentitySchema = z.object({
name: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+\.\d+$/u),
culture: z.string().nullable(),
flags: z.number().int().min(0).max(0xffff_ffff),
hash_algorithm: z.number().int().min(0).max(0xffff_ffff),
public_key: publicKeyIdentitySchema,
token: tokenSchema,
row_offset: offsetSchema,
});
const moduleIdentitySchema = z.object({
name: z.string(),
generation: z.number().int().min(0).max(0xffff),
mvid: z.string().uuid().nullable(),
enc_id: z.string().uuid().nullable(),
enc_base_id: z.string().uuid().nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const assemblyReferenceSchema = z.object({
name: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+\.\d+$/u),
culture: z.string().nullable(),
flags: z.number().int().min(0).max(0xffff_ffff),
public_key_or_token: publicKeyIdentitySchema,
hash_value_sha256: digestSchema.nullable(),
hash_value_length: z.number().int().min(0),
token: tokenSchema,
row_offset: offsetSchema,
});
const managedResourceSchema = z.object({
name: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
visibility: z.enum(["public", "private", "unknown"]),
implementation_token: tokenSchema.nullable(),
embedded: z.boolean(),
declared_offset: z.number().int().min(0).max(0xffff_ffff),
data_length: z.number().int().min(0).nullable(),
data_sha256: digestSchema.nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const customAttributeSchema = z.object({
parent_token: tokenSchema,
constructor_token: tokenSchema.nullable(),
type_name: z.string().nullable(),
value_length: z.number().int().min(0),
value_sha256: digestSchema,
decoded_fixed_string: z.string().nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const managedParseIssueSchema = z.object({
code: z.enum([
"invalid-cli-header",
"invalid-directory",
"invalid-metadata-root",
"invalid-stream",
"missing-stream",
"invalid-tables",
"invalid-row",
"invalid-heap-index",
"invalid-string",
"invalid-blob",
"invalid-guid",
"invalid-resource",
"limit-exceeded",
]),
scope: z.string().min(1),
offset: offsetSchema.nullable(),
detail: z.string().min(1),
});
/** Provider-neutral, execution-free PE/CLI triage and identity result. */
export const managedArtifactInspectionSchema = z.object({
schema_version: z.literal(1),
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0),
format: z.literal("pe"),
}),
pe: z.object({
machine: z.number().int().min(0).max(0xffff),
machine_hex: z.string().regex(/^0x[0-9a-f]{4}$/u),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
optional_header: z.enum(["pe32", "pe32-plus"]),
section_count: z.number().int().min(1).max(96),
characteristics: z.number().int().min(0).max(0xffff),
cli: z
.object({
header_offset: offsetSchema,
header_size: z.number().int().min(72),
runtime_version: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
flag_names: z.array(z.string()),
entry_point: z.object({
kind: z.enum(["metadata-token", "native-rva", "none"]),
value: z.string().nullable(),
}),
metadata_rva: z.number().int().min(1).max(0xffff_ffff),
metadata_size: z.number().int().min(1).max(0xffff_ffff),
resources_rva: z.number().int().min(0).max(0xffff_ffff),
resources_size: z.number().int().min(0).max(0xffff_ffff),
strong_name_rva: z.number().int().min(0).max(0xffff_ffff),
strong_name_size: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_rva: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_size: z.number().int().min(0).max(0xffff_ffff),
ready_to_run_signature: z.boolean(),
})
.nullable(),
}),
classification: z.object({
status: z.enum(["managed", "not-managed", "malformed"]),
container: z.literal("pe"),
runtime_family: z.enum([
"dotnet-framework",
"modern-dotnet",
"unity-mono",
"mixed-clr-native",
"unknown",
]),
implementation: z.enum([
"cil",
"cil-and-ready-to-run",
"cpp-cli-mixed",
"metadata-only",
"not-managed",
"unknown",
]),
managed_architecture: z.enum([
"anycpu",
"anycpu-prefer-32",
"x86",
"x86_64",
"arm",
"arm64",
"unknown",
]),
evidence: z.array(
z.object({
code: z.string().min(1),
detail: z.string().min(1),
file_offset: offsetSchema.nullable(),
}),
),
}),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
stream_names: z.array(z.string()),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
module: moduleIdentitySchema.nullable(),
assembly: assemblyIdentitySchema.nullable(),
target_frameworks: z.array(z.string()),
references: managedPage(assemblyReferenceSchema),
resources: managedPage(managedResourceSchema),
attributes: managedPage(customAttributeSchema),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
}),
limitations: z.array(z.string()),
});
export type ManagedArtifactInspection = z.infer<
typeof managedArtifactInspectionSchema
>;
export type ManagedParseIssue = z.infer<typeof managedParseIssueSchema>;
+418
View File
@@ -0,0 +1,418 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
managedArtifactInspectionSchema,
type ManagedArtifactInspection,
type ManagedParseIssue,
} from "../domain/managedArtifact.js";
import {
readManagedPeLayout,
type ManagedCliHeader,
type ManagedPeLayout,
} from "./ManagedPeReader.js";
import {
managedTableRowCounts,
readManagedMetadataInventory,
type ManagedInventoryInput,
type ManagedMetadataInventory,
type ManagedResourceDirectory,
} from "./ManagedMetadataInventory.js";
import {
readManagedMetadataLayout,
type ManagedMetadataLayout,
} from "./ManagedMetadataLayout.js";
import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
export interface ManagedInspectionLimits extends ManagedInventoryInput {
readonly maxMetadataBytes: number;
readonly maxTableRows: number;
}
const emptyPage = (offset: number, limit: number) => ({
items: [],
offset,
limit,
total: 0,
returned: 0,
dropped: 0,
complete: offset === 0,
});
const flagNames = (flags: number): string[] => {
const names: string[] = [];
for (const [mask, name] of [
[0x0000_0001, "il-only"],
[0x0000_0002, "32-bit-required"],
[0x0000_0004, "il-library"],
[0x0000_0008, "strong-name-signed"],
[0x0000_0010, "native-entry-point"],
[0x0001_0000, "track-debug-data"],
[0x0002_0000, "32-bit-preferred"],
] as const)
if ((flags & mask) !== 0) names.push(name);
return names;
};
const cliProjection = (
cli: ManagedCliHeader,
): NonNullable<ManagedArtifactInspection["pe"]["cli"]> => ({
header_offset: cli.headerOffset,
header_size: cli.headerSize,
runtime_version: `${String(cli.runtimeMajor)}.${String(cli.runtimeMinor)}`,
flags: cli.flags,
flag_names: flagNames(cli.flags),
entry_point:
cli.entryPoint === 0
? { kind: "none", value: null }
: (cli.flags & 0x10) !== 0
? {
kind: "native-rva",
value: `0x${cli.entryPoint.toString(16)}`,
}
: {
kind: "metadata-token",
value: `0x${cli.entryPoint.toString(16).padStart(8, "0")}`,
},
metadata_rva: cli.metadata.rva,
metadata_size: cli.metadata.size,
resources_rva: cli.resources.rva,
resources_size: cli.resources.size,
strong_name_rva: cli.strongName.rva,
strong_name_size: cli.strongName.size,
managed_native_header_rva: cli.managedNativeHeader.rva,
managed_native_header_size: cli.managedNativeHeader.size,
ready_to_run_signature: cli.readyToRunSignature,
});
const peProjection = (
layout: ManagedPeLayout,
): ManagedArtifactInspection["pe"] => ({
machine: layout.machine,
machine_hex: `0x${layout.machine.toString(16).padStart(4, "0")}`,
architecture: layout.architecture,
optional_header: layout.optionalHeader,
section_count: layout.sectionCount,
characteristics: layout.characteristics,
cli: layout.cli === null ? null : cliProjection(layout.cli),
});
const base = (
target: BinaryTarget,
bytes: Buffer,
layout: ManagedPeLayout,
) => ({
schema_version: 1 as const,
artifact: {
path: target.path,
sha256: target.sha256,
byte_length: bytes.length,
format: "pe" as const,
},
pe: peProjection(layout),
});
const unavailableResult = (
target: BinaryTarget,
bytes: Buffer,
layout: ManagedPeLayout,
limits: ManagedInspectionLimits,
): ManagedArtifactInspection => {
const malformed = layout.cliDirectoryPresent;
const issues = layout.cliIssue === null ? [] : [layout.cliIssue];
const limitations = malformed
? [
"The PE declares a CLI directory, but its CLI header could not be admitted.",
]
: [
"The PE has no CLI data directory; managed metadata and CIL are unavailable.",
];
return managedArtifactInspectionSchema.parse({
...base(target, bytes, layout),
classification: {
status: malformed ? "malformed" : "not-managed",
container: "pe",
runtime_family: "unknown",
implementation: malformed ? "unknown" : "not-managed",
managed_architecture: "unknown",
evidence: [
{
code: malformed ? "cli-directory-malformed" : "cli-directory-absent",
detail: limitations[0],
file_offset: layout.cliIssue?.offset ?? null,
},
],
},
metadata: {
status: malformed ? "malformed" : "absent",
version: null,
stream_names: [],
table_row_counts: {},
},
module: null,
assembly: null,
target_frameworks: [],
references: emptyPage(limits.referenceOffset, limits.referenceLimit),
resources: emptyPage(limits.resourceOffset, limits.resourceLimit),
attributes: emptyPage(limits.attributeOffset, limits.attributeLimit),
coverage: {
state: malformed ? "partial" : "unavailable",
issues,
},
limitations,
});
};
const runtimeClassification = (
layout: ManagedPeLayout,
metadata: ManagedMetadataLayout,
inventory: ManagedMetadataInventory,
): Pick<
ManagedArtifactInspection["classification"],
"runtime_family" | "implementation" | "managed_architecture" | "evidence"
> => {
const cli = layout.cli;
if (cli === null) throw new TypeError("Managed classification requires CLI");
const evidence: ManagedArtifactInspection["classification"]["evidence"] = [
{
code: "cli-header-observed",
detail: "A file-backed PE CLI header and metadata root were admitted.",
file_offset: cli.headerOffset,
},
];
const frameworks = inventory.targetFrameworks;
const hasUnity = inventory.referenceNames.some(
(name) => name === "UnityEngine" || name.startsWith("UnityEngine."),
);
let runtimeFamily: ManagedArtifactInspection["classification"]["runtime_family"] =
"unknown";
if ((cli.flags & 1) === 0) {
runtimeFamily = "mixed-clr-native";
evidence.push({
code: "cli-il-only-clear",
detail:
"COMIMAGE_FLAGS_ILONLY is clear, so managed and native analysis must remain composed.",
file_offset: cli.headerOffset + 16,
});
} else if (hasUnity) {
runtimeFamily = "unity-mono";
evidence.push({
code: "unity-reference-observed",
detail:
"The admitted AssemblyRef table contains a UnityEngine reference.",
file_offset: metadata.table(35)?.offset ?? null,
});
} else if (frameworks.some((value) => value.startsWith(".NETFramework,"))) {
runtimeFamily = "dotnet-framework";
evidence.push({
code: "target-framework-observed",
detail:
"An assembly-level TargetFrameworkAttribute names .NET Framework.",
file_offset: metadata.table(12)?.offset ?? null,
});
} else if (
frameworks.some(
(value) =>
value.startsWith(".NETCoreApp,") || value.startsWith(".NETStandard,"),
) ||
cli.readyToRunSignature
) {
runtimeFamily = "modern-dotnet";
evidence.push({
code: cli.readyToRunSignature
? "ready-to-run-signature-observed"
: "target-framework-observed",
detail: cli.readyToRunSignature
? "The managed native header has the ReadyToRun signature."
: "An assembly-level TargetFrameworkAttribute names modern .NET.",
file_offset: cli.readyToRunSignature
? layout.rvaToOffset(
cli.managedNativeHeader.rva,
4,
"cli.managed-native-header",
)
: (metadata.table(12)?.offset ?? null),
});
}
const implementation =
(cli.flags & 1) === 0
? ("cpp-cli-mixed" as const)
: cli.readyToRunSignature
? ("cil-and-ready-to-run" as const)
: (metadata.rowCounts[6] ?? 0) === 0
? ("metadata-only" as const)
: ("cil" as const);
const managedArchitecture =
layout.architecture === "x86" && (cli.flags & 1) !== 0
? (cli.flags & 0x0000_0002) !== 0
? "x86"
: (cli.flags & 0x0002_0000) !== 0
? "anycpu-prefer-32"
: "anycpu"
: layout.architecture;
evidence.push({
code: "managed-architecture-derived",
detail: `Managed architecture ${managedArchitecture} is derived from PE machine and CLI flags.`,
file_offset: cli.headerOffset + 16,
});
return {
runtime_family: runtimeFamily,
implementation,
managed_architecture: managedArchitecture,
evidence,
};
};
const partialMetadataResult = (
target: BinaryTarget,
bytes: Buffer,
layout: ManagedPeLayout,
limits: ManagedInspectionLimits,
issue: ManagedParseIssue,
): ManagedArtifactInspection => ({
...base(target, bytes, layout),
classification: {
status: "malformed",
container: "pe",
runtime_family:
(layout.cli?.flags ?? 1) & 1 ? "unknown" : "mixed-clr-native",
implementation: "unknown",
managed_architecture: "unknown",
evidence: [
{
code: "metadata-not-admitted",
detail: issue.detail,
file_offset: issue.offset,
},
],
},
metadata: {
status: issue.code === "limit-exceeded" ? "partial" : "malformed",
version: null,
stream_names: [],
table_row_counts: {},
},
module: null,
assembly: null,
target_frameworks: [],
references: emptyPage(limits.referenceOffset, limits.referenceLimit),
resources: emptyPage(limits.resourceOffset, limits.resourceLimit),
attributes: emptyPage(limits.attributeOffset, limits.attributeLimit),
coverage: { state: "partial", issues: [issue] },
limitations: [
"CLI metadata triage stopped at the reported bounded format or resource limit.",
],
});
const mapResources = (
bytes: Buffer,
layout: ManagedPeLayout,
issues: ManagedParseIssue[],
): ManagedResourceDirectory | null => {
const resources = layout.cli?.resources;
if (resources === undefined || (resources.rva === 0 && resources.size === 0))
return null;
try {
return {
offset: layout.rvaToOffset(
resources.rva,
resources.size,
"cli.resources",
),
size: resources.size,
};
} catch (cause: unknown) {
if (!(cause instanceof ManagedReaderFailure)) throw cause;
issues.push(cause.issue);
return null;
}
};
/** Inspect PE/CLI identity directly from bounded bytes without CLR loading. */
export const inspectManagedArtifactBytes = (
bytes: Buffer,
target: BinaryTarget,
limits: ManagedInspectionLimits,
): ManagedArtifactInspection => {
const layout = readManagedPeLayout(bytes);
if (layout.cli === null)
return unavailableResult(target, bytes, layout, limits);
const cli = layout.cli;
if (cli.metadata.size > limits.maxMetadataBytes)
return managedArtifactInspectionSchema.parse(
partialMetadataResult(target, bytes, layout, limits, {
code: "limit-exceeded",
scope: "cli.metadata",
offset: cli.headerOffset + 8,
detail: `CLI metadata size exceeds max_metadata_bytes ${String(limits.maxMetadataBytes)}`,
}),
);
let metadata: ManagedMetadataLayout;
try {
const metadataOffset = layout.rvaToOffset(
cli.metadata.rva,
cli.metadata.size,
"cli.metadata",
);
metadata = readManagedMetadataLayout(
bytes,
metadataOffset,
cli.metadata.size,
limits.maxTableRows,
);
} catch (cause: unknown) {
if (!(cause instanceof ManagedReaderFailure)) throw cause;
return managedArtifactInspectionSchema.parse(
partialMetadataResult(target, bytes, layout, limits, cause.issue),
);
}
const resourceIssues: ManagedParseIssue[] = [];
const resourceDirectory = mapResources(bytes, layout, resourceIssues);
const inventory = readManagedMetadataInventory(
bytes,
metadata,
limits,
resourceDirectory,
);
const issues = [...resourceIssues, ...inventory.issues];
const pagesComplete =
inventory.references.complete &&
inventory.resources.complete &&
inventory.attributes.complete;
const limitations = [
...(pagesComplete
? []
: [
"At least one caller-selected metadata page omits rows; use its offset and total to continue.",
]),
...(issues.length === 0
? []
: [
"At least one bounded metadata or resource item was unavailable; coverage is partial.",
]),
"Static inspection did not load the assembly, resolve dependencies through a CLR, decompile C#, or execute target code.",
];
return managedArtifactInspectionSchema.parse({
...base(target, bytes, layout),
classification: {
status: "managed",
container: "pe",
...runtimeClassification(layout, metadata, inventory),
},
metadata: {
status: issues.length === 0 ? "complete" : "partial",
version: metadata.version,
stream_names: metadata.streamNames,
table_row_counts: managedTableRowCounts(metadata),
},
module: inventory.module,
assembly: inventory.assembly,
target_frameworks: inventory.targetFrameworks,
references: inventory.references,
resources: inventory.resources,
attributes: inventory.attributes,
coverage: {
state: pagesComplete && issues.length === 0 ? "complete" : "partial",
issues,
},
limitations,
});
};
+221
View File
@@ -0,0 +1,221 @@
import { createHash } from "node:crypto";
import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";
import { managedFailure } from "./ManagedReaderFailure.js";
const requireRange = (
bytes: Buffer,
offset: number,
length: number,
scope: string,
): void => {
if (offset < 0 || length < 0 || offset > bytes.length - length)
throw managedFailure(
"invalid-row",
scope,
`${scope} leaves the artifact byte range`,
offset >= 0 ? offset : null,
);
};
/** Cursor for checked fixed-width metadata row decoding. */
export class MetadataRowCursor {
#offset: number;
constructor(
private readonly bytes: Buffer,
readonly start: number,
private readonly end: number,
private readonly scope: string,
) {
this.#offset = start;
}
get offset(): number {
return this.#offset;
}
readUInt16(): number {
this.require(2);
const value = this.bytes.readUInt16LE(this.#offset);
this.#offset += 2;
return value;
}
readUInt32(): number {
this.require(4);
const value = this.bytes.readUInt32LE(this.#offset);
this.#offset += 4;
return value;
}
readIndex(size: 2 | 4): number {
return size === 2 ? this.readUInt16() : this.readUInt32();
}
private require(length: number): void {
if (this.#offset < this.start || this.#offset > this.end - length)
throw managedFailure(
"invalid-row",
this.scope,
`${this.scope} row ended before all declared columns`,
this.#offset,
);
}
}
const compressedLength = (
bytes: Buffer,
offset: number,
scope: string,
): { readonly length: number; readonly prefix: number } => {
requireRange(bytes, offset, 1, scope);
const first = bytes[offset] ?? 0;
if ((first & 0x80) === 0) return { length: first, prefix: 1 };
if ((first & 0xc0) === 0x80) {
requireRange(bytes, offset, 2, scope);
return {
length: ((first & 0x3f) << 8) | (bytes[offset + 1] ?? 0),
prefix: 2,
};
}
if ((first & 0xe0) === 0xc0) {
requireRange(bytes, offset, 4, scope);
return {
length:
(first & 0x1f) * 0x01_00_00_00 +
(bytes[offset + 1] ?? 0) * 0x01_00_00 +
(bytes[offset + 2] ?? 0) * 0x0100 +
(bytes[offset + 3] ?? 0),
prefix: 4,
};
}
throw managedFailure(
"invalid-blob",
scope,
"Metadata blob uses a reserved compressed-length prefix",
offset,
);
};
/** Read one bounded UTF-8 value from #Strings. */
export const readMetadataString = (
bytes: Buffer,
layout: ManagedMetadataLayout,
index: number,
maxBytes: number,
): string => {
if (index === 0) return "";
if (index < 0 || index >= layout.strings.size)
throw managedFailure(
"invalid-heap-index",
"metadata.#Strings",
"String heap index is outside #Strings",
layout.strings.offset + Math.max(index, 0),
);
const start = layout.strings.offset + index;
const maximum = Math.min(
layout.strings.offset + layout.strings.size,
start + maxBytes + 1,
);
let end = start;
while (end < maximum && bytes[end] !== 0) end += 1;
if (end === maximum)
throw managedFailure(
"limit-exceeded",
"metadata.#Strings",
`String heap item exceeds max_heap_item_bytes ${String(maxBytes)}`,
start,
);
try {
return new TextDecoder("utf-8", { fatal: true }).decode(
bytes.subarray(start, end),
);
} catch {
throw managedFailure(
"invalid-string",
"metadata.#Strings",
"String heap item is not valid UTF-8",
start,
);
}
};
/** Read one bounded item from #Blob without interpreting its contents. */
export const readMetadataBlob = (
bytes: Buffer,
layout: ManagedMetadataLayout,
index: number,
maxBytes: number,
): Buffer => {
if (index === 0) return Buffer.alloc(0);
if (index < 0 || index >= layout.blob.size)
throw managedFailure(
"invalid-heap-index",
"metadata.#Blob",
"Blob heap index is outside #Blob",
layout.blob.offset + Math.max(index, 0),
);
const start = layout.blob.offset + index;
const decoded = compressedLength(bytes, start, "metadata.#Blob");
if (decoded.length > maxBytes)
throw managedFailure(
"limit-exceeded",
"metadata.#Blob",
`Blob heap item exceeds max_heap_item_bytes ${String(maxBytes)}`,
start,
);
const content = start + decoded.prefix;
if (content > layout.blob.offset + layout.blob.size - decoded.length)
throw managedFailure(
"invalid-blob",
"metadata.#Blob",
"Blob heap item leaves #Blob",
start,
);
return bytes.subarray(content, content + decoded.length);
};
/** Read one conventional GUID value from the one-based #GUID heap. */
export const readMetadataGuid = (
bytes: Buffer,
layout: ManagedMetadataLayout,
index: number,
): string | null => {
if (index === 0) return null;
const relative = (index - 1) * 16;
if (relative < 0 || relative > layout.guid.size - 16)
throw managedFailure(
"invalid-guid",
"metadata.#GUID",
"GUID heap index is outside #GUID",
layout.guid.offset + Math.max(relative, 0),
);
const offset = layout.guid.offset + relative;
const part1 = bytes.readUInt32LE(offset).toString(16).padStart(8, "0");
const part2 = bytes
.readUInt16LE(offset + 4)
.toString(16)
.padStart(4, "0");
const part3 = bytes
.readUInt16LE(offset + 6)
.toString(16)
.padStart(4, "0");
const part4 = bytes.subarray(offset + 8, offset + 10).toString("hex");
const part5 = bytes.subarray(offset + 10, offset + 16).toString("hex");
return `${part1}-${part2}-${part3}-${part4}-${part5}`;
};
/** Format one metadata table/row pair as an exact build-local token. */
export const metadataToken = (table: number, row: number): string =>
`0x${(table * 0x01_00_00_00 + row).toString(16).padStart(8, "0")}`;
/** Hash bytes without exposing their contents. */
export const sha256Bytes = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
/** Derive the conventional strong-name token from a full public key. */
export const strongNameToken = (publicKey: Buffer): string =>
Buffer.from(createHash("sha1").update(publicKey).digest().subarray(-8))
.reverse()
.toString("hex");
+673
View File
@@ -0,0 +1,673 @@
import type {
ManagedArtifactInspection,
ManagedParseIssue,
} from "../domain/managedArtifact.js";
import {
METADATA_TABLE_NAMES,
metadataRowOffset,
type ManagedMetadataLayout,
type MetadataTableLayout,
} from "./ManagedMetadataLayout.js";
import {
MetadataRowCursor,
metadataToken,
readMetadataBlob,
readMetadataGuid,
readMetadataString,
sha256Bytes,
strongNameToken,
} from "./ManagedMetadataHeaps.js";
import {
ManagedReaderFailure,
managedFailure,
} from "./ManagedReaderFailure.js";
type ModuleIdentity = NonNullable<ManagedArtifactInspection["module"]>;
type AssemblyIdentity = NonNullable<ManagedArtifactInspection["assembly"]>;
type AssemblyReference =
ManagedArtifactInspection["references"]["items"][number];
type ManagedResource = ManagedArtifactInspection["resources"]["items"][number];
type CustomAttribute = ManagedArtifactInspection["attributes"]["items"][number];
type ManagedPage<Item> = {
readonly items: readonly Item[];
readonly offset: number;
readonly limit: number;
readonly total: number;
readonly returned: number;
readonly dropped: number;
readonly complete: boolean;
};
export interface ManagedInventoryInput {
readonly referenceOffset: number;
readonly referenceLimit: number;
readonly resourceOffset: number;
readonly resourceLimit: number;
readonly attributeOffset: number;
readonly attributeLimit: number;
readonly maxHeapItemBytes: number;
}
export interface ManagedResourceDirectory {
readonly offset: number;
readonly size: number;
}
export interface ManagedMetadataInventory {
readonly module: ModuleIdentity | null;
readonly assembly: AssemblyIdentity | null;
readonly targetFrameworks: readonly string[];
readonly referenceNames: readonly string[];
readonly references: ManagedPage<AssemblyReference>;
readonly resources: ManagedPage<ManagedResource>;
readonly attributes: ManagedPage<CustomAttribute>;
readonly issues: readonly ManagedParseIssue[];
}
const rowCursor = (
bytes: Buffer,
layout: ManagedMetadataLayout,
table: number,
row: number,
): MetadataRowCursor => {
const descriptor = layout.table(table);
const start = metadataRowOffset(layout, table, row);
if (descriptor === undefined)
throw managedFailure(
"invalid-row",
`metadata.${String(table)}`,
"Metadata table is absent",
start,
);
return new MetadataRowCursor(
bytes,
start,
start + descriptor.rowSize,
`metadata.${descriptor.name}`,
);
};
const publicKeyIdentity = (
bytes: Buffer,
kind: "public-key" | "public-key-token",
): AssemblyIdentity["public_key"] => ({
kind: bytes.length === 0 ? "none" : kind,
byte_length: bytes.length,
sha256: bytes.length === 0 ? null : sha256Bytes(bytes),
token:
bytes.length === 0
? null
: kind === "public-key"
? strongNameToken(bytes)
: bytes.length === 8
? bytes.toString("hex")
: null,
});
const readModule = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): ModuleIdentity | null => {
const table = layout.table(0);
if (table === undefined || table.rowCount === 0) return null;
const cursor = rowCursor(bytes, layout, 0, 1);
const generation = cursor.readUInt16();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const mvid = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
const encId = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
const encBaseId = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
return {
name,
generation,
mvid,
enc_id: encId,
enc_base_id: encBaseId,
token: metadataToken(0, 1),
row_offset: table.offset,
};
};
const readAssembly = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): AssemblyIdentity | null => {
const table = layout.table(32);
if (table === undefined || table.rowCount === 0) return null;
const cursor = rowCursor(bytes, layout, 32, 1);
const hashAlgorithm = cursor.readUInt32();
const version = [
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
].join(".");
const flags = cursor.readUInt32();
const key = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const culture = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
return {
name,
version,
culture: culture.length === 0 ? null : culture,
flags,
hash_algorithm: hashAlgorithm,
public_key: publicKeyIdentity(
key,
(flags & 1) === 0 ? "public-key-token" : "public-key",
),
token: metadataToken(32, 1),
row_offset: table.offset,
};
};
const readAssemblyReference = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
): AssemblyReference => {
const cursor = rowCursor(bytes, layout, 35, row);
const version = [
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
].join(".");
const flags = cursor.readUInt32();
const keyOrToken = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const culture = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const hashValue = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
return {
name,
version,
culture: culture.length === 0 ? null : culture,
flags,
public_key_or_token: publicKeyIdentity(
keyOrToken,
(flags & 1) === 0 ? "public-key-token" : "public-key",
),
hash_value_sha256: hashValue.length === 0 ? null : sha256Bytes(hashValue),
hash_value_length: hashValue.length,
token: metadataToken(35, row),
row_offset: metadataRowOffset(layout, 35, row),
};
};
const codedToken = (
raw: number,
bits: number,
tables: readonly (number | undefined)[],
): string | null => {
if (raw === 0) return null;
const tag = raw & (2 ** bits - 1);
const row = Math.floor(raw / 2 ** bits);
const table = tables[tag];
return table === undefined || row === 0 ? null : metadataToken(table, row);
};
const readTypeName = (
bytes: Buffer,
layout: ManagedMetadataLayout,
table: 1 | 2,
row: number,
maxBytes: number,
): string | null => {
const descriptor = layout.table(table);
if (descriptor === undefined || row < 1 || row > descriptor.rowCount)
return null;
const cursor = rowCursor(bytes, layout, table, row);
if (table === 1) cursor.readIndex(layout.codedIndexSize("ResolutionScope"));
else cursor.readUInt32();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const namespace = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
return namespace.length === 0 ? name : `${namespace}.${name}`;
};
const declaringTypeForMethod = (
bytes: Buffer,
layout: ManagedMetadataLayout,
methodRow: number,
maxBytes: number,
): string | null => {
const types = layout.table(2);
const methods = layout.table(6);
if (types === undefined || methods === undefined) return null;
for (let row = 1; row <= types.rowCount; row += 1) {
const cursor = rowCursor(bytes, layout, 2, row);
cursor.readUInt32();
const nameIndex = cursor.readIndex(layout.stringIndexSize);
const namespaceIndex = cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
const methodStart = cursor.readIndex(layout.tableIndexSize(6));
const methodEnd =
row === types.rowCount
? methods.rowCount + 1
: methodListForType(bytes, layout, row + 1);
if (methodRow < methodStart || methodRow >= methodEnd) continue;
const name = readMetadataString(bytes, layout, nameIndex, maxBytes);
const namespace = readMetadataString(
bytes,
layout,
namespaceIndex,
maxBytes,
);
return namespace.length === 0 ? name : `${namespace}.${name}`;
}
return null;
};
const methodListForType = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
): number => {
const cursor = rowCursor(bytes, layout, 2, row);
cursor.readUInt32();
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
return cursor.readIndex(layout.tableIndexSize(6));
};
const attributeTypeName = (
bytes: Buffer,
layout: ManagedMetadataLayout,
rawType: number,
maxBytes: number,
): string | null => {
const tag = rawType & 7;
const row = Math.floor(rawType / 8);
if (row === 0) return null;
if (tag === 2) return declaringTypeForMethod(bytes, layout, row, maxBytes);
if (tag !== 3) return null;
const memberRefs = layout.table(10);
if (memberRefs === undefined || row > memberRefs.rowCount) return null;
const cursor = rowCursor(bytes, layout, 10, row);
const parent = cursor.readIndex(layout.codedIndexSize("MemberRefParent"));
const parentTag = parent & 7;
const parentRow = Math.floor(parent / 8);
if (parentTag === 0)
return readTypeName(bytes, layout, 2, parentRow, maxBytes);
if (parentTag === 1)
return readTypeName(bytes, layout, 1, parentRow, maxBytes);
if (parentTag === 3)
return declaringTypeForMethod(bytes, layout, parentRow, maxBytes);
return null;
};
const decodeCompressedLength = (
blob: Buffer,
offset: number,
): { readonly length: number; readonly prefix: number } | undefined => {
const first = blob[offset];
if (first === undefined) return undefined;
if ((first & 0x80) === 0) return { length: first, prefix: 1 };
if ((first & 0xc0) === 0x80 && blob[offset + 1] !== undefined)
return {
length: ((first & 0x3f) << 8) | (blob[offset + 1] ?? 0),
prefix: 2,
};
if (
(first & 0xe0) === 0xc0 &&
blob[offset + 1] !== undefined &&
blob[offset + 2] !== undefined &&
blob[offset + 3] !== undefined
)
return {
length:
(first & 0x1f) * 0x01_00_00_00 +
(blob[offset + 1] ?? 0) * 0x01_00_00 +
(blob[offset + 2] ?? 0) * 0x0100 +
(blob[offset + 3] ?? 0),
prefix: 4,
};
return undefined;
};
const decodeFixedString = (blob: Buffer): string | null => {
if (blob.length < 3 || blob.readUInt16LE(0) !== 1 || blob[2] === 0xff)
return null;
const length = decodeCompressedLength(blob, 2);
if (length === undefined) return null;
const start = 2 + length.prefix;
if (start > blob.length - length.length) return null;
try {
return new TextDecoder("utf-8", { fatal: true }).decode(
blob.subarray(start, start + length.length),
);
} catch {
return null;
}
};
const readCustomAttribute = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
): CustomAttribute => {
const cursor = rowCursor(bytes, layout, 12, row);
const parentRaw = cursor.readIndex(
layout.codedIndexSize("HasCustomAttribute"),
);
const typeRaw = cursor.readIndex(
layout.codedIndexSize("CustomAttributeType"),
);
const value = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const parent = codedToken(
parentRaw,
5,
[
6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42,
44, 43,
],
);
if (parent === null)
throw managedFailure(
"invalid-row",
"metadata.CustomAttribute",
"CustomAttribute parent coded index is invalid",
cursor.start,
);
const typeName = attributeTypeName(bytes, layout, typeRaw, maxBytes);
return {
parent_token: parent,
constructor_token: codedToken(typeRaw, 3, [undefined, undefined, 6, 10]),
type_name: typeName,
value_length: value.length,
value_sha256: sha256Bytes(value),
decoded_fixed_string:
typeName === "System.Runtime.Versioning.TargetFrameworkAttribute"
? decodeFixedString(value)
: null,
token: metadataToken(12, row),
row_offset: cursor.start,
};
};
const readResource = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
directory: ManagedResourceDirectory | null,
issues: ManagedParseIssue[],
): ManagedResource => {
const cursor = rowCursor(bytes, layout, 40, row);
const declaredOffset = cursor.readUInt32();
const flags = cursor.readUInt32();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const implementationRaw = cursor.readIndex(
layout.codedIndexSize("Implementation"),
);
const implementationToken = codedToken(implementationRaw, 2, [38, 35, 39]);
let dataLength: number | null = null;
let dataSha256: string | null = null;
if (implementationRaw === 0) {
if (directory === null || declaredOffset > directory.size - 4) {
issues.push({
code: "invalid-resource",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: directory?.offset ?? null,
detail: "Embedded resource offset leaves the CLI resources directory",
});
} else {
const start = directory.offset + declaredOffset;
dataLength = bytes.readUInt32LE(start);
if (dataLength > directory.size - declaredOffset - 4) {
issues.push({
code: "invalid-resource",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: start,
detail: "Embedded resource length leaves the CLI resources directory",
});
} else if (dataLength > maxBytes) {
issues.push({
code: "limit-exceeded",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: start + 4,
detail: `Embedded resource exceeds max_heap_item_bytes ${String(maxBytes)}; digest omitted`,
});
} else {
dataSha256 = sha256Bytes(
bytes.subarray(start + 4, start + 4 + dataLength),
);
}
}
}
return {
name,
flags,
visibility:
(flags & 7) === 1 ? "public" : (flags & 7) === 2 ? "private" : "unknown",
implementation_token: implementationToken,
embedded: implementationRaw === 0,
declared_offset: declaredOffset,
data_length: dataLength,
data_sha256: dataSha256,
token: metadataToken(40, row),
row_offset: cursor.start,
};
};
const safeRead = <Value>(
operation: () => Value,
issues: ManagedParseIssue[],
): Value | undefined => {
try {
return operation();
} catch (cause: unknown) {
if (!(cause instanceof ManagedReaderFailure)) throw cause;
issues.push(cause.issue);
return undefined;
}
};
const pageRows = <Item>(
descriptor: MetadataTableLayout | undefined,
offset: number,
limit: number,
read: (row: number) => Item | undefined,
): ManagedPage<Item> => {
const total = descriptor?.rowCount ?? 0;
const items: Item[] = [];
const end = Math.min(total, offset + limit);
for (let index = offset; index < end; index += 1) {
const item = read(index + 1);
if (item !== undefined) items.push(item);
}
return {
items,
offset,
limit,
total,
returned: items.length,
dropped: total - items.length,
complete: offset === 0 && end === total && items.length === total,
};
};
const uniqueIssues = (
issues: readonly ManagedParseIssue[],
): readonly ManagedParseIssue[] => [
...new Map(issues.map((issue) => [JSON.stringify(issue), issue])).values(),
];
/** Inventory bounded identity tables without CLR reflection or execution. */
export const readManagedMetadataInventory = (
bytes: Buffer,
layout: ManagedMetadataLayout,
input: ManagedInventoryInput,
resourceDirectory: ManagedResourceDirectory | null,
): ManagedMetadataInventory => {
const issues: ManagedParseIssue[] = [];
const module =
safeRead(() => readModule(bytes, layout, input.maxHeapItemBytes), issues) ??
null;
const assembly =
safeRead(
() => readAssembly(bytes, layout, input.maxHeapItemBytes),
issues,
) ?? null;
const references = pageRows(
layout.table(35),
input.referenceOffset,
input.referenceLimit,
(row) =>
safeRead(
() => readAssemblyReference(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
);
const resources = pageRows(
layout.table(40),
input.resourceOffset,
input.resourceLimit,
(row) =>
safeRead(
() =>
readResource(
bytes,
layout,
row,
input.maxHeapItemBytes,
resourceDirectory,
issues,
),
issues,
),
);
const attributes = pageRows(
layout.table(12),
input.attributeOffset,
input.attributeLimit,
(row) =>
safeRead(
() => readCustomAttribute(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
);
const referenceNames: string[] = [];
const referenceTable = layout.table(35);
for (let row = 1; row <= (referenceTable?.rowCount ?? 0); row += 1) {
const reference = safeRead(
() => readAssemblyReference(bytes, layout, row, input.maxHeapItemBytes),
issues,
);
if (reference !== undefined) referenceNames.push(reference.name);
}
const targetFrameworks: string[] = [];
const attributeTable = layout.table(12);
for (let row = 1; row <= (attributeTable?.rowCount ?? 0); row += 1) {
const attribute = safeRead(
() => readCustomAttribute(bytes, layout, row, input.maxHeapItemBytes),
issues,
);
if (
attribute?.parent_token === metadataToken(32, 1) &&
attribute.type_name ===
"System.Runtime.Versioning.TargetFrameworkAttribute" &&
attribute.decoded_fixed_string !== null &&
!targetFrameworks.includes(attribute.decoded_fixed_string)
)
targetFrameworks.push(attribute.decoded_fixed_string);
}
return {
module,
assembly,
targetFrameworks: targetFrameworks.sort(),
referenceNames: [...new Set(referenceNames)].sort(),
references,
resources,
attributes,
issues: uniqueIssues(issues),
};
};
/** Stable table-name/count projection for caller-visible coverage. */
export const managedTableRowCounts = (
layout: ManagedMetadataLayout,
): Readonly<Record<string, number>> =>
Object.fromEntries(
[...layout.tables.values()].map(({ index, rowCount }) => [
METADATA_TABLE_NAMES[index] ?? `Table${String(index)}`,
rowCount,
]),
);
+467
View File
@@ -0,0 +1,467 @@
import { managedFailure } from "./ManagedReaderFailure.js";
export const METADATA_TABLE_NAMES = [
"Module",
"TypeRef",
"TypeDef",
"FieldPtr",
"Field",
"MethodPtr",
"MethodDef",
"ParamPtr",
"Param",
"InterfaceImpl",
"MemberRef",
"Constant",
"CustomAttribute",
"FieldMarshal",
"DeclSecurity",
"ClassLayout",
"FieldLayout",
"StandAloneSig",
"EventMap",
"EventPtr",
"Event",
"PropertyMap",
"PropertyPtr",
"Property",
"MethodSemantics",
"MethodImpl",
"ModuleRef",
"TypeSpec",
"ImplMap",
"FieldRVA",
"ENCLog",
"ENCMap",
"Assembly",
"AssemblyProcessor",
"AssemblyOS",
"AssemblyRef",
"AssemblyRefProcessor",
"AssemblyRefOS",
"File",
"ExportedType",
"ManifestResource",
"NestedClass",
"GenericParam",
"MethodSpec",
"GenericParamConstraint",
] as const;
interface MetadataStream {
readonly name: string;
readonly offset: number;
readonly size: number;
}
export interface MetadataTableLayout {
readonly index: number;
readonly name: string;
readonly rowCount: number;
readonly rowSize: number;
readonly offset: number;
}
export interface ManagedMetadataLayout {
readonly rootOffset: number;
readonly size: number;
readonly version: string;
readonly streamNames: readonly string[];
readonly strings: MetadataStream;
readonly guid: MetadataStream;
readonly blob: MetadataStream;
readonly tables: ReadonlyMap<number, MetadataTableLayout>;
readonly rowCounts: readonly number[];
readonly stringIndexSize: 2 | 4;
readonly guidIndexSize: 2 | 4;
readonly blobIndexSize: 2 | 4;
table(index: number): MetadataTableLayout | undefined;
tableIndexSize(index: number): 2 | 4;
codedIndexSize(name: CodedIndexName): 2 | 4;
}
type CodedIndexName = keyof typeof CODED_INDEXES;
const CODED_INDEXES = {
TypeDefOrRef: { bits: 2, tables: [2, 1, 27] },
HasConstant: { bits: 2, tables: [4, 8, 23] },
HasCustomAttribute: {
bits: 5,
tables: [
6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42,
44, 43,
],
},
HasFieldMarshal: { bits: 1, tables: [4, 8] },
HasDeclSecurity: { bits: 2, tables: [2, 6, 32] },
MemberRefParent: { bits: 3, tables: [2, 1, 26, 6, 27] },
HasSemantics: { bits: 1, tables: [20, 23] },
MethodDefOrRef: { bits: 1, tables: [6, 10] },
MemberForwarded: { bits: 1, tables: [4, 6] },
Implementation: { bits: 2, tables: [38, 35, 39] },
CustomAttributeType: { bits: 3, tables: [6, 10] },
ResolutionScope: { bits: 2, tables: [0, 26, 35, 1] },
TypeOrMethodDef: { bits: 1, tables: [2, 6] },
} as const;
const SUPPORTED_TABLE_MASK = (1n << BigInt(METADATA_TABLE_NAMES.length)) - 1n;
const requireRange = (
bytes: Buffer,
offset: number,
length: number,
scope: string,
): void => {
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(length) ||
offset < 0 ||
length < 0 ||
offset > bytes.length - length
)
throw managedFailure(
"invalid-metadata-root",
scope,
`${scope} leaves the metadata byte range`,
Number.isSafeInteger(offset) && offset >= 0 ? offset : null,
);
};
const align4 = (value: number): number => (value + 3) & ~3;
const readStreamName = (
bytes: Buffer,
offset: number,
): { readonly name: string; readonly next: number } => {
const endLimit = Math.min(bytes.length, offset + 32);
let end = offset;
while (end < endLimit && bytes[end] !== 0) end += 1;
if (end === endLimit)
throw managedFailure(
"invalid-stream",
"metadata.stream-name",
"Metadata stream name is missing a bounded terminator",
offset,
);
const nameBytes = bytes.subarray(offset, end);
if (nameBytes.some((byte) => byte < 0x20 || byte > 0x7e))
throw managedFailure(
"invalid-stream",
"metadata.stream-name",
"Metadata stream name is not printable ASCII",
offset,
);
return {
name: nameBytes.toString("ascii"),
next: align4(end + 1),
};
};
const streamByName = (
streams: ReadonlyMap<string, MetadataStream>,
names: readonly string[],
): MetadataStream | undefined => {
for (const name of names) {
const stream = streams.get(name);
if (stream !== undefined) return stream;
}
return undefined;
};
const requireStream = (
streams: ReadonlyMap<string, MetadataStream>,
name: string,
): MetadataStream => {
const stream = streams.get(name);
if (stream === undefined)
throw managedFailure(
"missing-stream",
`metadata.${name}`,
`Required metadata stream ${name} is absent`,
);
return stream;
};
const codedSize = (
name: CodedIndexName,
rowCounts: readonly number[],
): 2 | 4 => {
const descriptor = CODED_INDEXES[name];
let maximum = 0;
for (const table of descriptor.tables)
maximum = Math.max(maximum, rowCounts[table] ?? 0);
return maximum < 2 ** (16 - descriptor.bits) ? 2 : 4;
};
const tableSize = (index: number, rows: readonly number[]): 2 | 4 =>
(rows[index] ?? 0) < 0x1_0000 ? 2 : 4;
const rowSize = (
table: number,
rowCounts: readonly number[],
heaps: { readonly string: 2 | 4; readonly guid: 2 | 4; readonly blob: 2 | 4 },
): number => {
const t = (index: number): number => tableSize(index, rowCounts);
const c = (name: CodedIndexName): number => codedSize(name, rowCounts);
const { string: s, guid: g, blob: b } = heaps;
switch (table) {
case 0:
return 2 + s + g * 3;
case 1:
return c("ResolutionScope") + s * 2;
case 2:
return 4 + s * 2 + c("TypeDefOrRef") + t(4) + t(6);
case 3:
return t(4);
case 4:
return 2 + s + b;
case 5:
return t(6);
case 6:
return 8 + s + b + t(8);
case 7:
return t(8);
case 8:
return 4 + s;
case 9:
return t(2) + c("TypeDefOrRef");
case 10:
return c("MemberRefParent") + s + b;
case 11:
return 2 + c("HasConstant") + b;
case 12:
return c("HasCustomAttribute") + c("CustomAttributeType") + b;
case 13:
return c("HasFieldMarshal") + b;
case 14:
return 2 + c("HasDeclSecurity") + b;
case 15:
return 6 + t(2);
case 16:
return 4 + t(4);
case 17:
return b;
case 18:
return t(2) + t(20);
case 19:
return t(20);
case 20:
return 2 + s + c("TypeDefOrRef");
case 21:
return t(2) + t(23);
case 22:
return t(23);
case 23:
return 2 + s + b;
case 24:
return 2 + t(6) + c("HasSemantics");
case 25:
return t(2) + c("MethodDefOrRef") * 2;
case 26:
return s;
case 27:
return b;
case 28:
return 2 + c("MemberForwarded") + s + t(26);
case 29:
return 4 + t(4);
case 30:
return 8;
case 31:
return 4;
case 32:
return 16 + b + s * 2;
case 33:
return 4;
case 34:
return 12;
case 35:
return 12 + b * 2 + s * 2;
case 36:
return 4 + t(35);
case 37:
return 12 + t(35);
case 38:
return 4 + s + b;
case 39:
return 8 + s * 2 + c("Implementation");
case 40:
return 8 + s + c("Implementation");
case 41:
return t(2) * 2;
case 42:
return 4 + c("TypeOrMethodDef") + s;
case 43:
return c("MethodDefOrRef") + b;
case 44:
return t(42) + c("TypeDefOrRef");
default:
throw managedFailure(
"invalid-tables",
"metadata.tables",
`Metadata table ${String(table)} is unsupported`,
);
}
};
/** Parse ECMA-335 stream and table layout with checked byte extents. */
export const readManagedMetadataLayout = (
artifact: Buffer,
rootOffset: number,
size: number,
maxTableRows: number,
): ManagedMetadataLayout => {
if (size < 20 || rootOffset < 0 || rootOffset > artifact.length - size)
throw managedFailure(
"invalid-metadata-root",
"metadata.root",
"CLI metadata directory leaves the artifact byte range",
rootOffset,
);
const bytes = artifact.subarray(rootOffset, rootOffset + size);
if (bytes.readUInt32LE(0) !== 0x424a_5342)
throw managedFailure(
"invalid-metadata-root",
"metadata.signature",
"CLI metadata signature is not BSJB",
rootOffset,
);
const versionLength = bytes.readUInt32LE(12);
requireRange(bytes, 16, versionLength, "metadata.version");
const versionBytes = bytes.subarray(16, 16 + versionLength);
const zero = versionBytes.indexOf(0);
const version = versionBytes
.subarray(0, zero < 0 ? versionBytes.length : zero)
.toString("utf8");
let cursor = align4(16 + versionLength);
requireRange(bytes, cursor, 4, "metadata.stream-count");
const streamCount = bytes.readUInt16LE(cursor + 2);
if (streamCount === 0 || streamCount > 64)
throw managedFailure(
"invalid-stream",
"metadata.stream-count",
"Metadata stream count is outside the admitted range",
rootOffset + cursor + 2,
);
cursor += 4;
const streams = new Map<string, MetadataStream>();
for (let index = 0; index < streamCount; index += 1) {
requireRange(bytes, cursor, 8, "metadata.stream-header");
const relativeOffset = bytes.readUInt32LE(cursor);
const streamSize = bytes.readUInt32LE(cursor + 4);
const named = readStreamName(bytes, cursor + 8);
if (streams.has(named.name))
throw managedFailure(
"invalid-stream",
"metadata.stream-header",
`Duplicate metadata stream ${named.name}`,
rootOffset + cursor,
);
requireRange(bytes, relativeOffset, streamSize, `metadata.${named.name}`);
streams.set(named.name, {
name: named.name,
offset: rootOffset + relativeOffset,
size: streamSize,
});
cursor = named.next;
}
const tablesStream = streamByName(streams, ["#~", "#-"]);
if (tablesStream === undefined)
throw managedFailure(
"missing-stream",
"metadata.tables",
"Required metadata table stream #~ or #- is absent",
);
const tableBytes = artifact.subarray(
tablesStream.offset,
tablesStream.offset + tablesStream.size,
);
requireRange(tableBytes, 0, 24, "metadata.tables-header");
const heapSizes = tableBytes[6] ?? 0;
const heaps = {
string: (heapSizes & 0x01) === 0 ? (2 as const) : (4 as const),
guid: (heapSizes & 0x02) === 0 ? (2 as const) : (4 as const),
blob: (heapSizes & 0x04) === 0 ? (2 as const) : (4 as const),
};
const valid = tableBytes.readBigUInt64LE(8);
if ((valid & ~SUPPORTED_TABLE_MASK) !== 0n)
throw managedFailure(
"invalid-tables",
"metadata.valid-mask",
"Metadata valid mask names unsupported tables outside the admitted ECMA-335 range",
tablesStream.offset + 8,
);
const rowCounts = Array<number>(METADATA_TABLE_NAMES.length).fill(0);
let tableCursor = 24;
for (let index = 0; index < METADATA_TABLE_NAMES.length; index += 1) {
if ((valid & (1n << BigInt(index))) === 0n) continue;
requireRange(tableBytes, tableCursor, 4, "metadata.table-row-count");
const count = tableBytes.readUInt32LE(tableCursor);
if (count > maxTableRows)
throw managedFailure(
"limit-exceeded",
`metadata.${METADATA_TABLE_NAMES[index] ?? String(index)}`,
`Metadata table row count ${String(count)} exceeds max_table_rows ${String(maxTableRows)}`,
tablesStream.offset + tableCursor,
);
rowCounts[index] = count;
tableCursor += 4;
}
const tables = new Map<number, MetadataTableLayout>();
for (let index = 0; index < METADATA_TABLE_NAMES.length; index += 1) {
const count = rowCounts[index] ?? 0;
if ((valid & (1n << BigInt(index))) === 0n) continue;
const sizeOfRow = rowSize(index, rowCounts, heaps);
const byteLength = count * sizeOfRow;
if (!Number.isSafeInteger(byteLength))
throw managedFailure(
"invalid-tables",
"metadata.tables",
"Metadata table byte size overflowed",
tablesStream.offset + tableCursor,
);
requireRange(tableBytes, tableCursor, byteLength, "metadata.table-data");
tables.set(index, {
index,
name: METADATA_TABLE_NAMES[index] ?? `Table${String(index)}`,
rowCount: count,
rowSize: sizeOfRow,
offset: tablesStream.offset + tableCursor,
});
tableCursor += byteLength;
}
const layout: ManagedMetadataLayout = {
rootOffset,
size,
version,
streamNames: [...streams.keys()].sort(),
strings: requireStream(streams, "#Strings"),
guid: requireStream(streams, "#GUID"),
blob: requireStream(streams, "#Blob"),
tables,
rowCounts,
stringIndexSize: heaps.string,
guidIndexSize: heaps.guid,
blobIndexSize: heaps.blob,
table: (index) => tables.get(index),
tableIndexSize: (index) => tableSize(index, rowCounts),
codedIndexSize: (name) => codedSize(name, rowCounts),
};
return layout;
};
/** Resolve a one-based metadata row to its exact file offset. */
export const metadataRowOffset = (
layout: ManagedMetadataLayout,
table: number,
row: number,
): number => {
const descriptor = layout.table(table);
if (descriptor === undefined || row < 1 || row > descriptor.rowCount)
throw managedFailure(
"invalid-row",
`metadata.${METADATA_TABLE_NAMES[table] ?? String(table)}`,
`Metadata row ${String(row)} is outside its table`,
);
return descriptor.offset + (row - 1) * descriptor.rowSize;
};
+296
View File
@@ -0,0 +1,296 @@
import type { ManagedParseIssue } from "../domain/managedArtifact.js";
import {
managedFailure,
ManagedReaderFailure,
} from "./ManagedReaderFailure.js";
interface PeSection {
readonly virtualAddress: number;
readonly virtualSize: number;
readonly rawOffset: number;
readonly rawSize: number;
}
interface PeDataDirectory {
readonly rva: number;
readonly size: number;
}
export interface ManagedCliHeader {
readonly headerOffset: number;
readonly headerSize: number;
readonly runtimeMajor: number;
readonly runtimeMinor: number;
readonly metadata: PeDataDirectory;
readonly flags: number;
readonly entryPoint: number;
readonly resources: PeDataDirectory;
readonly strongName: PeDataDirectory;
readonly managedNativeHeader: PeDataDirectory;
readonly readyToRunSignature: boolean;
}
export interface ManagedPeLayout {
readonly machine: number;
readonly architecture: "x86" | "x86_64" | "arm" | "arm64";
readonly optionalHeader: "pe32" | "pe32-plus";
readonly sectionCount: number;
readonly characteristics: number;
readonly sections: readonly PeSection[];
readonly cli: ManagedCliHeader | null;
readonly cliDirectoryPresent: boolean;
readonly cliIssue: ManagedParseIssue | null;
rvaToOffset(rva: number, size: number, scope: string): number;
}
const requireRange = (
bytes: Buffer,
offset: number,
length: number,
scope: string,
): void => {
if (
!Number.isSafeInteger(offset) ||
!Number.isSafeInteger(length) ||
offset < 0 ||
length < 0 ||
offset > bytes.length - length
)
throw managedFailure(
"invalid-directory",
scope,
`${scope} leaves the artifact byte range`,
Number.isSafeInteger(offset) && offset >= 0 ? offset : null,
);
};
const add = (left: number, right: number, scope: string): number => {
const result = left + right;
if (!Number.isSafeInteger(result) || result < left)
throw managedFailure(
"invalid-directory",
scope,
`${scope} offset arithmetic overflowed`,
left,
);
return result;
};
const architectureFor = (machine: number): ManagedPeLayout["architecture"] => {
switch (machine) {
case 0x014c:
return "x86";
case 0x8664:
return "x86_64";
case 0x01c0:
return "arm";
case 0xaa64:
return "arm64";
default:
throw managedFailure(
"invalid-directory",
"pe.machine",
`Unsupported PE machine 0x${machine.toString(16).padStart(4, "0")}`,
);
}
};
const mapRva = (
bytes: Buffer,
sections: readonly PeSection[],
rva: number,
size: number,
scope: string,
): number => {
if (rva === 0 && size === 0) return 0;
for (const section of sections) {
const mappedSize = Math.max(section.virtualSize, section.rawSize);
if (rva < section.virtualAddress) continue;
const within = rva - section.virtualAddress;
if (within > mappedSize || size > mappedSize - within) continue;
if (within > section.rawSize || size > section.rawSize - within)
throw managedFailure(
"invalid-directory",
scope,
`${scope} occupies virtual bytes without file-backed data`,
);
const offset = add(section.rawOffset, within, scope);
requireRange(bytes, offset, size, scope);
return offset;
}
throw managedFailure(
"invalid-directory",
scope,
`${scope} RVA is not covered by a PE section`,
);
};
const readDirectory = (bytes: Buffer, offset: number): PeDataDirectory => {
requireRange(bytes, offset, 8, "pe.data-directory");
return {
rva: bytes.readUInt32LE(offset),
size: bytes.readUInt32LE(offset + 4),
};
};
const readCliHeader = (
bytes: Buffer,
sections: readonly PeSection[],
directory: PeDataDirectory,
): ManagedCliHeader => {
if (directory.size < 72)
throw managedFailure(
"invalid-cli-header",
"cli.header",
"CLI header is shorter than the required 72 bytes",
);
const offset = mapRva(bytes, sections, directory.rva, 72, "cli.header");
const headerSize = bytes.readUInt32LE(offset);
if (headerSize < 72 || headerSize > directory.size)
throw managedFailure(
"invalid-cli-header",
"cli.header",
"CLI header size is outside its PE data directory",
offset,
);
const metadata = readDirectory(bytes, offset + 8);
if (metadata.rva === 0 || metadata.size === 0)
throw managedFailure(
"invalid-cli-header",
"cli.metadata",
"CLI metadata directory is absent",
offset + 8,
);
const flags = bytes.readUInt32LE(offset + 16);
const managedNativeHeader = readDirectory(bytes, offset + 64);
let readyToRunSignature = false;
if (managedNativeHeader.rva !== 0 && managedNativeHeader.size >= 4) {
const nativeOffset = mapRva(
bytes,
sections,
managedNativeHeader.rva,
4,
"cli.managed-native-header",
);
readyToRunSignature = bytes.readUInt32LE(nativeOffset) === 0x0052_5452;
}
return {
headerOffset: offset,
headerSize,
runtimeMajor: bytes.readUInt16LE(offset + 4),
runtimeMinor: bytes.readUInt16LE(offset + 6),
metadata,
flags,
entryPoint: bytes.readUInt32LE(offset + 20),
resources: readDirectory(bytes, offset + 24),
strongName: readDirectory(bytes, offset + 32),
managedNativeHeader,
readyToRunSignature,
};
};
/** Parse the file-backed PE and CLI layout without loading target code. */
export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => {
requireRange(bytes, 0, 64, "pe.dos-header");
if (bytes[0] !== 0x4d || bytes[1] !== 0x5a)
throw managedFailure(
"invalid-directory",
"pe.dos-header",
"Artifact does not start with an MZ header",
0,
);
const peOffset = bytes.readUInt32LE(0x3c);
requireRange(bytes, peOffset, 24, "pe.coff-header");
if (bytes.readUInt32LE(peOffset) !== 0x0000_4550)
throw managedFailure(
"invalid-directory",
"pe.signature",
"PE signature is invalid",
peOffset,
);
const coff = peOffset + 4;
const machine = bytes.readUInt16LE(coff);
const sectionCount = bytes.readUInt16LE(coff + 2);
if (sectionCount === 0 || sectionCount > 96)
throw managedFailure(
"invalid-directory",
"pe.sections",
"PE section count is outside the admitted range",
coff + 2,
);
const optionalSize = bytes.readUInt16LE(coff + 16);
const characteristics = bytes.readUInt16LE(coff + 18);
const optionalOffset = coff + 20;
requireRange(bytes, optionalOffset, optionalSize, "pe.optional-header");
if (optionalSize < 96)
throw managedFailure(
"invalid-directory",
"pe.optional-header",
"PE optional header is too short",
optionalOffset,
);
const magic = bytes.readUInt16LE(optionalOffset);
const optionalHeader =
magic === 0x010b ? "pe32" : magic === 0x020b ? "pe32-plus" : undefined;
if (optionalHeader === undefined)
throw managedFailure(
"invalid-directory",
"pe.optional-header",
"PE optional header magic is unsupported",
optionalOffset,
);
const directoryCountOffset =
optionalOffset + (optionalHeader === "pe32" ? 92 : 108);
const directoryOffset =
optionalOffset + (optionalHeader === "pe32" ? 96 : 112);
requireRange(bytes, directoryCountOffset, 4, "pe.data-directories");
const directoryCount = bytes.readUInt32LE(directoryCountOffset);
const sectionOffset = add(optionalOffset, optionalSize, "pe.sections");
requireRange(bytes, sectionOffset, sectionCount * 40, "pe.sections");
const sections: PeSection[] = [];
for (let index = 0; index < sectionCount; index += 1) {
const offset = sectionOffset + index * 40;
const section = {
virtualSize: bytes.readUInt32LE(offset + 8),
virtualAddress: bytes.readUInt32LE(offset + 12),
rawSize: bytes.readUInt32LE(offset + 16),
rawOffset: bytes.readUInt32LE(offset + 20),
};
if (section.rawSize > 0)
requireRange(
bytes,
section.rawOffset,
section.rawSize,
"pe.section-data",
);
sections.push(section);
}
const cliDirectory =
directoryCount <= 14 ||
optionalSize < directoryOffset - optionalOffset + 120
? { rva: 0, size: 0 }
: readDirectory(bytes, directoryOffset + 14 * 8);
const cliDirectoryPresent = cliDirectory.rva !== 0 || cliDirectory.size !== 0;
let cli: ManagedCliHeader | null = null;
let cliIssue: ManagedParseIssue | null = null;
if (cliDirectoryPresent)
try {
cli = readCliHeader(bytes, sections, cliDirectory);
} catch (cause: unknown) {
if (!(cause instanceof ManagedReaderFailure)) throw cause;
cliIssue = cause.issue;
}
return {
machine,
architecture: architectureFor(machine),
optionalHeader,
sectionCount,
characteristics,
sections,
cli,
cliDirectoryPresent,
cliIssue,
rvaToOffset: (rva, size, scope) =>
mapRva(bytes, sections, rva, size, scope),
};
};
+20
View File
@@ -0,0 +1,20 @@
import type { ManagedParseIssue } from "../domain/managedArtifact.js";
/** Bounded format failure retained as caller-visible managed coverage. */
export class ManagedReaderFailure extends Error {
constructor(
readonly issue: ManagedParseIssue,
options?: ErrorOptions,
) {
super(issue.detail, options);
}
}
/** Construct a typed managed parse failure at an exact byte location. */
export const managedFailure = (
code: ManagedParseIssue["code"],
scope: string,
detail: string,
offset: number | null = null,
): ManagedReaderFailure =>
new ManagedReaderFailure({ code, scope, offset, detail });
+188
View File
@@ -0,0 +1,188 @@
import { createHash } from "node:crypto";
import { readFile, stat } from "node:fs/promises";
import {
createAnalysisExecution,
type AnalysisClient,
type AnalysisOperation,
type AnalysisProvider,
type CapabilityDescriptor,
type ExecutionOptions,
type ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js";
import {
MANAGED_TOOL_CONTRACTS,
managedArtifactInputSchema,
type ManagedToolName,
} from "../contracts/managedToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
EvidenceIntegrityError,
ProviderAdapterError,
} from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
const IDENTITY: ProviderIdentity = Object.freeze(MANAGED_STATIC_PROVIDER);
/** Execution-free managed PE/CLI auxiliary provider. */
export class ManagedStaticProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[] = Object.freeze(
MANAGED_TOOL_CONTRACTS.map((contract) =>
Object.freeze({
provider: IDENTITY,
operation: contract.name,
inputContractVersion: 1,
outputContractVersion: 1,
available: true as const,
reason: null,
pagination: "offset" as const,
exhaustive: false,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: false,
mayShowUi: false,
mayAccessNetwork: false,
mayWriteFilesystem: false,
changesPermissions: false,
requiresRoot: false,
}),
limits: Object.freeze({
maxResults: 500,
maxPayloadBytes: 4 * 1024 * 1024,
timeoutMs: null,
}),
limitations: Object.freeze([
"This capability inventories PE/CLI identity only; method signatures and CIL are admitted by a later contract.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
]),
}),
),
);
identity(): ProviderIdentity {
return IDENTITY;
}
capabilities(): readonly CapabilityDescriptor[] {
return this.#capabilities;
}
createClient(target: BinaryTarget): AnalysisClient {
return new ManagedStaticClient(target);
}
}
class ManagedStaticClient implements AnalysisClient {
constructor(private readonly target: BinaryTarget) {}
async execute(
operation: AnalysisOperation,
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
if (operation === "health")
return ok(createAnalysisExecution(null, IDENTITY));
if (!isManagedOperation(operation))
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
"Operation is not implemented by the managed static provider.",
),
);
if (this.target.format !== "pe")
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
`Managed static triage requires a PE target; observed ${this.target.format}.`,
),
);
try {
const input = managedArtifactInputSchema.parse(parameters);
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const metadata = await stat(this.target.path);
if (metadata.size > input.max_file_bytes)
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
`Artifact size ${String(metadata.size)} exceeds max_file_bytes ${String(input.max_file_bytes)}.`,
),
);
const bytes = await readFile(
this.target.path,
options?.signal === undefined ? undefined : { signal: options.signal },
);
if (bytes.length > input.max_file_bytes)
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
`Artifact grew beyond max_file_bytes ${String(input.max_file_bytes)} while it was read.`,
),
);
const observedDigest = createHash("sha256").update(bytes).digest("hex");
if (observedDigest !== this.target.sha256)
return err(
new EvidenceIntegrityError(
`Managed artifact digest changed after open: expected ${this.target.sha256}, observed ${observedDigest} at ${this.target.path}`,
),
);
const result = inspectManagedArtifactBytes(bytes, this.target, {
referenceOffset: input.reference_offset,
referenceLimit: input.reference_limit,
resourceOffset: input.resource_offset,
resourceLimit: input.resource_limit,
attributeOffset: input.attribute_offset,
attributeLimit: input.attribute_limit,
maxMetadataBytes: input.max_metadata_bytes,
maxTableRows: input.max_table_rows,
maxHeapItemBytes: input.max_heap_item_bytes,
});
return ok(
createAnalysisExecution(result, IDENTITY, {
rawResult: null,
limitations: result.limitations,
subject: this.target,
locations:
result.pe.cli === null
? [{ kind: "file-offset" as const, offset: 0 }]
: [
{
kind: "file-offset-range" as const,
start: result.pe.cli.header_offset,
end:
result.pe.cli.header_offset + result.pe.cli.header_size,
},
...[result.module, result.assembly]
.filter((value) => value !== null)
.map((value) => ({
kind: "file-offset" as const,
offset: value.row_offset,
})),
],
}),
);
} catch (cause: unknown) {
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
return err(new ProviderAdapterError(IDENTITY.id, operation, { cause }));
}
}
close(): Promise<void> {
return Promise.resolve();
}
}
const isManagedOperation = (
operation: AnalysisOperation,
): operation is ManagedToolName =>
MANAGED_TOOL_CONTRACTS.some(({ name }) => name === operation);
+6
View File
@@ -8,6 +8,7 @@ import { registerOfficialTools } from "./registerOfficialTools.js";
import { registerSessionTools } from "./registerSessionTools.js";
import { registerNativeTools } from "./registerNativeTools.js";
import { registerArtifactTools } from "./registerArtifactTools.js";
import { registerManagedTools } from "./registerManagedTools.js";
import { silentLogger, type Logger } from "../logger.js";
import type { ProcessExecutionPolicy } from "../domain/processCapture.js";
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
@@ -169,6 +170,11 @@ export const createServer = (
? {}
: { permissionAuthority: options.permissionAuthority }),
});
registerManagedTools(server, analysis, {
logger: toolLogger,
activeTarget,
recordEvidence,
});
registerBrowserTools(server, {
logger: toolLogger,
browser: options.browserObservation,
+21
View File
@@ -0,0 +1,21 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { MANAGED_TOOL_CONTRACTS } from "../contracts/managedToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { Logger } from "../logger.js";
import { registerEvidenceTools } from "./registerEvidenceTools.js";
/** Register execution-free managed PE/CLI inspection. */
export const registerManagedTools = (
server: McpServer,
analysis: AnalysisOperationPort,
options: {
readonly logger: Logger;
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
},
): void => {
registerEvidenceTools(server, analysis, MANAGED_TOOL_CONTRACTS, options);
};