feat(dotnet): import managed reconstructions

This commit is contained in:
N0zoM1z0
2026-07-16 20:37:42 +09:00
committed by N0zoM1z0
parent 798631ade6
commit c506664744
88 changed files with 1251 additions and 212 deletions
@@ -0,0 +1,85 @@
import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
type AnalysisError,
} from "../domain/errors.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import {
importManagedReconstruction,
managedReconstructionImportInputSchema,
type ManagedReconstructionImportInput,
type ManagedReconstructionImportResult,
} from "../domain/managedReconstruction.js";
import { err, ok, type Result } from "../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
const OPERATION = "import_managed_reconstruction" as const;
/** Authenticate and import managed decompiler reconstruction as Evidence. */
export const importManagedReconstructionEvidence = (
rawInput: unknown,
): Result<Evidence, AnalysisError> => {
const parsed = managedReconstructionImportInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
try {
const result = importManagedReconstruction(parsed.data);
return ok(createManagedReconstructionEvidence(parsed.data, result));
} catch (cause: unknown) {
return err(
cause instanceof TypeError || cause instanceof z.ZodError
? new AnalysisInputError(OPERATION, { cause })
: new AnalysisProtocolError(
"Managed reconstruction import produced an invalid result",
{ cause },
),
);
}
};
const createManagedReconstructionEvidence = (
input: ManagedReconstructionImportInput,
result: ManagedReconstructionImportResult,
): Evidence =>
createEvidence(
{
path: result.static_observation.artifact_path,
sha256: result.static_observation.artifact_sha256,
format: "pe",
},
MANAGED_WORKFLOW_PROVIDER,
{
predicateType: "rea.managed-reconstruction-import/v1",
operation: OPERATION,
parameters: {
static_members_evidence_id: input.static_members.evidence_id,
decompiler: jsonValueSchema.parse(result.decompiler),
method_locks: jsonValueSchema.parse(
input.methods.map(
({ token, signature_sha256, normalized_il_sha256 }) => ({
token,
signature_sha256,
normalized_il_sha256,
}),
),
),
notes: jsonValueSchema.parse(input.notes),
},
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: result.limitations,
locations: [
{
kind: "artifact-path",
path: result.static_observation.artifact_path,
},
],
evidenceLinks: result.evidence_links,
},
);
+20
View File
@@ -9,6 +9,7 @@ import {
runSessionStatus,
} from "./application/DirectAnalysis.js";
import { compareManagedMemberPaths } from "./application/ManagedMemberComparisonService.js";
import { importManagedReconstructionEvidence } from "./application/ManagedReconstructionService.js";
import { planManagedRuntimeCorrelationEvidence } from "./application/ManagedRuntimeCorrelationService.js";
import {
runSetup,
@@ -893,6 +894,25 @@ const registerManagedCommands = (
};
}),
});
cli.command(CLI_COMMANDS.importManagedReconstruction, {
description:
"Import decompiler-produced managed reconstruction against exact static member evidence",
args: z.object({
inputJson: z
.string()
.describe("Inline managed reconstruction JSON or JSON file path"),
}),
run: ({ args }) =>
logCliCommand(logger, "import-managed-reconstruction", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"import-managed-reconstruction",
);
if (!input.ok) return input.error;
const result = importManagedReconstructionEvidence(input.value);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
});
cli.command(CLI_COMMANDS.planManagedRuntimeCorrelation, {
description:
"Plan a separately authorized managed runtime-correlation experiment without executing target code",
+1
View File
@@ -20,6 +20,7 @@ export const CLI_COMMANDS = Object.freeze({
inspectManagedMembers: "inspect-managed-members",
inspectManagedNativeBoundaries: "inspect-managed-native-boundaries",
compareManagedMembers: "compare-managed-members",
importManagedReconstruction: "import-managed-reconstruction",
planManagedRuntimeCorrelation: "plan-managed-runtime-correlation",
inspectMacho: "inspect-macho",
inspectSignature: "inspect-signature",
+32 -2
View File
@@ -69,7 +69,7 @@ const evidence = (result: ManagedMemberInspection) =>
const runtimeMembers = (): ManagedMemberInspection => {
const result = emptyManagedMembers(
"2".repeat(64),
"11112222-3333-4444-5555-666677778888",
"11112222-3333-4444-9555-666677778888",
);
return {
...result,
@@ -131,7 +131,7 @@ export const MANAGED_MEMBER_COMPARISON_EXAMPLE = {
emptyManagedMembers("0".repeat(64), "00112233-4455-6677-8899-aabbccddeeff"),
),
right: evidence(
emptyManagedMembers("1".repeat(64), "ffeeddcc-bbaa-9988-7766-554433221100"),
emptyManagedMembers("1".repeat(64), "ffeeddcc-bbaa-4988-9766-554433221100"),
),
limits: {
max_method_matches: 100,
@@ -142,6 +142,36 @@ export const MANAGED_MEMBER_COMPARISON_EXAMPLE = {
const runtimeExampleEvidence = evidence(runtimeMembers());
/** Minimal valid managed decompiler reconstruction import request. */
export const MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE = {
static_members: runtimeExampleEvidence,
decompiler: {
name: "ilspycmd",
version: "9.1.0.7988",
family: "ilspy",
executable_sha256: null,
options: ["--disable-updatecheck", "--type", "Example.Program"],
},
methods: [
{
token: "0x06000001",
signature_sha256: "3".repeat(64),
normalized_il_sha256: "5".repeat(64),
reconstruction: {
kind: "decompiled-csharp",
language: "csharp",
text: "internal static void Main() { }",
source_path: "/examples/Example.Program.cs",
start_line: 1,
end_line: 1,
},
},
],
notes: [
"Synthetic example only; decompiler output is imported as inference.",
],
};
/** Minimal valid managed runtime-correlation planning request. */
export const MANAGED_RUNTIME_CORRELATION_EXAMPLE = {
static_members: runtimeExampleEvidence,
@@ -1,9 +1,11 @@
import { compareManagedMembersInputSchema } from "../domain/managedMemberComparison.js";
import { managedReconstructionImportInputSchema } from "../domain/managedReconstruction.js";
import { managedRuntimeCorrelationInputSchema } from "../domain/managedRuntimeCorrelation.js";
import type { ToolContract } from "./toolContracts.js";
import { managedWorkflowOutputSchemas } from "./toolOutputSchemas.js";
import {
MANAGED_MEMBER_COMPARISON_EXAMPLE,
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
MANAGED_RUNTIME_CORRELATION_EXAMPLE,
} from "./managedWorkflowExamples.js";
@@ -19,6 +21,12 @@ if (runtimeOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for plan_managed_runtime_correlation",
);
const reconstructionOutputSchema =
managedWorkflowOutputSchemas.import_managed_reconstruction;
if (reconstructionOutputSchema === undefined)
throw new Error(
"Missing managed workflow output schema for import_managed_reconstruction",
);
/** Provider-neutral managed-code workflow contracts. */
export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
@@ -42,6 +50,26 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
},
],
},
{
name: "import_managed_reconstruction",
description:
"Import decompiler-produced managed reconstruction against authenticated inspect_managed_members Evidence. The workflow locks each method to artifact SHA-256, MVID, metadata token, signature hash, and normalized IL hash, records the decompiler identity and options, and marks C# or pseudocode as analyst inference rather than canonical byte observation.",
kind: "application",
inputSchema: managedReconstructionImportInputSchema,
outputSchema: reconstructionOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Import a decompiler reconstruction for one managed method",
input: MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
},
],
},
{
name: "plan_managed_runtime_correlation",
description:
+4
View File
@@ -30,6 +30,7 @@ import {
managedNativeBoundaryInspectionSchema,
} from "../domain/managedArtifact.js";
import { managedMemberComparisonResultSchema } from "../domain/managedMemberComparison.js";
import { managedReconstructionImportResultSchema } from "../domain/managedReconstruction.js";
import { managedRuntimeCorrelationResultSchema } from "../domain/managedRuntimeCorrelation.js";
import { artifactComparisonResultSchema } from "../domain/artifactComparison.js";
import { functionComparisonResultSchema } from "../domain/functionComparison.js";
@@ -550,6 +551,9 @@ export const managedWorkflowOutputSchemas: Readonly<
Record<string, z.ZodObject>
> = {
compare_managed_members: resultOf(managedMemberComparisonResultSchema),
import_managed_reconstruction: resultOf(
managedReconstructionImportResultSchema,
),
plan_managed_runtime_correlation: resultOf(
managedRuntimeCorrelationResultSchema,
),
+227
View File
@@ -0,0 +1,227 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import { z } from "zod";
import { evidenceSchema, parseEvidence } from "./evidence.js";
import { managedMemberInspectionSchema } from "./managedArtifact.js";
import type { JsonValue } from "./jsonValue.js";
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const boundedTextSchema = z.string().min(1).max(65_536);
const boundedLabelSchema = z.string().min(1).max(512);
const decompilerSchema = z.strictObject({
name: boundedLabelSchema,
version: z.string().min(1).max(128).nullable(),
family: z.enum(["ilspy", "dnspy", "dnlib", "mono-cecil", "other"]),
executable_sha256: digestSchema.nullable(),
options: z.array(z.string().max(512)).max(50).default([]),
});
const managedReconstructionMethodInputSchema = z.strictObject({
token: tokenSchema,
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
reconstruction: z.strictObject({
kind: z.enum(["decompiled-csharp", "decompiled-il", "semantic-pseudocode"]),
language: z.enum(["csharp", "il", "pseudocode"]),
text: boundedTextSchema,
text_sha256: digestSchema.optional(),
source_path: z.string().min(1).max(4_096).nullable().optional(),
start_line: z.number().int().min(1).nullable().optional(),
end_line: z.number().int().min(1).nullable().optional(),
}),
});
export const managedReconstructionImportInputSchema = z.strictObject({
static_members: evidenceSchema,
decompiler: decompilerSchema,
methods: z.array(managedReconstructionMethodInputSchema).min(1).max(50),
notes: z.array(z.string().min(1).max(4_096)).max(100).default([]),
unknown_registry_approved: z.literal(true).optional(),
});
const importedMethodSchema = z.strictObject({
token: tokenSchema,
declaring_type: z.string().nullable(),
name: z.string(),
signature_sha256: digestSchema,
normalized_il_sha256: digestSchema.nullable(),
body_sha256: digestSchema.nullable(),
il_size: z.number().int().min(0),
reconstruction: z.strictObject({
kind: z.enum(["decompiled-csharp", "decompiled-il", "semantic-pseudocode"]),
language: z.enum(["csharp", "il", "pseudocode"]),
text: boundedTextSchema,
text_sha256: digestSchema,
text_length: z.number().int().min(1).max(65_536),
line_count: z.number().int().min(1),
source_path: z.string().min(1).max(4_096).nullable(),
start_line: z.number().int().min(1).nullable(),
end_line: z.number().int().min(1).nullable(),
}),
validation: z.strictObject({
matched_static_member: z.literal(true),
exact_build_required: z.literal(true),
canonical_observation: z.literal(false),
confidence_floor: z.literal("inference"),
}),
});
export const managedReconstructionImportResultSchema = z.strictObject({
schema_version: z.literal(1),
reconstruction_id: z.string().regex(/^mre_[a-f0-9]{64}$/u),
phase: z.literal("reconstruction-import"),
executed: z.literal(false),
static_observation: z.strictObject({
evidence_id: evidenceIdSchema,
artifact_sha256: digestSchema,
artifact_path: z.string().min(1),
byte_length: z.number().int().min(0),
module_name: z.string().nullable(),
mvid: z.string().uuid().nullable(),
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
}),
decompiler: decompilerSchema.extend({
options_sha256: digestSchema,
}),
summary: z.strictObject({
imported_methods: z.number().int().min(1).max(50),
decompiled_csharp_methods: z.number().int().min(0).max(50),
decompiled_il_methods: z.number().int().min(0).max(50),
pseudocode_methods: z.number().int().min(0).max(50),
total_text_bytes: z.number().int().min(1),
}),
methods: z.array(importedMethodSchema).min(1).max(50),
notes: z.array(z.string().min(1).max(4_096)).max(100),
evidence_links: z.array(evidenceIdSchema).length(1),
limitations: z.array(z.string().min(1).max(4_096)).max(1_000),
});
export type ManagedReconstructionImportInput = z.infer<
typeof managedReconstructionImportInputSchema
>;
export type ManagedReconstructionImportResult = z.infer<
typeof managedReconstructionImportResultSchema
>;
const sha256Text = (value: string): string =>
createHash("sha256").update(value).digest("hex");
const sha256Json = (value: JsonValue): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
throw new TypeError("Managed reconstruction canonicalization failed");
return createHash("sha256").update(serialized).digest("hex");
};
/** Authenticate decompiler reconstruction against static IL Evidence. */
export const importManagedReconstruction = (
input: ManagedReconstructionImportInput,
): ManagedReconstructionImportResult => {
const staticEvidence = parseEvidence(input.static_members);
if (staticEvidence.operation !== "inspect_managed_members")
throw new TypeError("Evidence operation is not inspect_managed_members");
const members = managedMemberInspectionSchema.parse(
staticEvidence.normalized_result,
);
const methods = input.methods.map((candidate) => {
const observed = members.methods.items.find(
(item) =>
item.token === candidate.token &&
item.signature.raw_sha256 === candidate.signature_sha256 &&
item.body.normalized_il_sha256 === candidate.normalized_il_sha256,
);
if (observed === undefined)
throw new TypeError(
`Reconstruction method lock ${candidate.token} does not match a static managed member observation`,
);
const textSha256 = sha256Text(candidate.reconstruction.text);
if (
candidate.reconstruction.text_sha256 !== undefined &&
candidate.reconstruction.text_sha256 !== textSha256
)
throw new TypeError(
`Reconstruction text hash mismatch for ${candidate.token}`,
);
return {
token: observed.token,
declaring_type: observed.declaring_type,
name: observed.name,
signature_sha256: observed.signature.raw_sha256,
normalized_il_sha256: observed.body.normalized_il_sha256,
body_sha256: observed.body.il_sha256,
il_size: observed.body.il_size,
reconstruction: {
kind: candidate.reconstruction.kind,
language: candidate.reconstruction.language,
text: candidate.reconstruction.text,
text_sha256: textSha256,
text_length: candidate.reconstruction.text.length,
line_count: countLines(candidate.reconstruction.text),
source_path: candidate.reconstruction.source_path ?? null,
start_line: candidate.reconstruction.start_line ?? null,
end_line: candidate.reconstruction.end_line ?? null,
},
validation: {
matched_static_member: true as const,
exact_build_required: true as const,
canonical_observation: false as const,
confidence_floor: "inference" as const,
},
};
});
const withoutId = {
schema_version: 1 as const,
phase: "reconstruction-import" as const,
executed: false as const,
static_observation: {
evidence_id: staticEvidence.evidence_id,
artifact_sha256: members.artifact.sha256,
artifact_path: members.artifact.path,
byte_length: members.artifact.byte_length,
module_name: members.module?.name ?? null,
mvid: members.module?.mvid ?? null,
metadata_status: members.metadata.status,
},
decompiler: {
...input.decompiler,
options_sha256: sha256Json(input.decompiler.options),
},
summary: {
imported_methods: methods.length,
decompiled_csharp_methods: methods.filter(
({ reconstruction }) => reconstruction.kind === "decompiled-csharp",
).length,
decompiled_il_methods: methods.filter(
({ reconstruction }) => reconstruction.kind === "decompiled-il",
).length,
pseudocode_methods: methods.filter(
({ reconstruction }) => reconstruction.kind === "semantic-pseudocode",
).length,
total_text_bytes: methods.reduce(
(total, { reconstruction }) => total + reconstruction.text_length,
0,
),
},
methods,
notes: input.notes,
evidence_links: [staticEvidence.evidence_id],
limitations: [
"Decompiler output is imported as reconstruction evidence and analyst inference; metadata and IL observations remain canonical.",
"This operation did not execute, load, reflect over, debug, instrument, patch, or decompile the target artifact.",
"The imported reconstruction is valid only for the exact artifact SHA-256, MVID, method signature, and normalized IL shape recorded here.",
"Obfuscated names, decompiler variables, and control-flow restructuring are not treated as proof without separate validation.",
],
};
return managedReconstructionImportResultSchema.parse({
...withoutId,
reconstruction_id: `mre_${sha256Json(withoutId)}`,
});
};
const countLines = (text: string): number =>
text.length === 0 ? 0 : text.split(/\r\n|\r|\n/u).length;
+37 -3
View File
@@ -2,6 +2,7 @@ import type { McpServer } from "@modelcontextprotocol/server";
import type { BinarySessionPort } from "../application/BinarySession.js";
import { compareManagedMembersEvidence } from "../application/ManagedMemberComparisonService.js";
import { importManagedReconstructionEvidence } from "../application/ManagedReconstructionService.js";
import {
planManagedRuntimeCorrelationEvidence,
type ManagedRuntimeCorrelationDependencies,
@@ -11,6 +12,7 @@ import {
compareManagedMembersInputSchema,
managedMemberComparisonResultSchema,
} from "../domain/managedMemberComparison.js";
import { managedReconstructionImportInputSchema } from "../domain/managedReconstruction.js";
import { managedRuntimeCorrelationInputSchema } from "../domain/managedRuntimeCorrelation.js";
import type { Evidence } from "../domain/evidence.js";
import type { Logger } from "../logger.js";
@@ -32,9 +34,9 @@ export const registerManagedWorkflowTools = (
server: McpServer,
options: ManagedWorkflowToolRegistration,
): void => {
const [compareContract, runtimeContract] = MANAGED_WORKFLOW_TOOL_CONTRACTS;
if (compareContract === undefined || runtimeContract === undefined)
throw new Error("Missing managed workflow contract");
const compareContract = contract("compare_managed_members");
const reconstructionContract = contract("import_managed_reconstruction");
const runtimeContract = contract("plan_managed_runtime_correlation");
server.registerTool(
compareContract.name,
toolRegistrationOptions(compareContract),
@@ -89,6 +91,28 @@ export const registerManagedWorkflowTools = (
);
},
);
server.registerTool(
reconstructionContract.name,
toolRegistrationOptions(reconstructionContract),
async (input) => {
const parsed = managedReconstructionImportInputSchema.parse(input);
const result = await logToolExecution(
options.logger,
reconstructionContract.name,
() => Promise.resolve(importManagedReconstructionEvidence(parsed)),
);
if (!result.ok) return toCallToolResult(result, reconstructionContract);
const recordedSource = options.recordEvidence?.(parsed.static_members);
if (recordedSource !== undefined && !recordedSource.ok)
return toCallToolResult(recordedSource, reconstructionContract);
const recorded = options.recordEvidence?.(result.value);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, reconstructionContract);
return toCallToolResult(result, reconstructionContract, {
evidenceResourcesAvailable: recorded !== undefined,
});
},
);
server.registerTool(
runtimeContract.name,
toolRegistrationOptions(runtimeContract),
@@ -113,6 +137,16 @@ export const registerManagedWorkflowTools = (
);
};
const contract = (
name: (typeof MANAGED_WORKFLOW_TOOL_CONTRACTS)[number]["name"],
) => {
const found = MANAGED_WORKFLOW_TOOL_CONTRACTS.find(
(candidate) => candidate.name === name,
);
if (found === undefined) throw new Error(`Missing ${name} contract`);
return found;
};
const recordSources = (
recordEvidence: ManagedWorkflowToolRegistration["recordEvidence"],
sources: readonly Evidence[],