feat(dotnet): add managed member inspection

This commit is contained in:
N0zoM1z0
2026-07-16 17:44:36 +09:00
committed by N0zoM1z0
parent c251c38aa2
commit 98cad3788d
83 changed files with 2230 additions and 197 deletions
+98 -1
View File
@@ -578,7 +578,7 @@ const registerManagedCommands = (
.min(256)
.max(268_435_456)
.default(67_108_864),
maxTableRows: z.number().int().min(1).max(10_000_000).default(1_000_000),
maxTableRows: z.number().int().min(1).max(1_000_000).default(100_000),
maxHeapItemBytes: z
.number()
.int()
@@ -619,6 +619,103 @@ const registerManagedCommands = (
),
),
});
cli.command(CLI_COMMANDS.inspectManagedMembers, {
description:
"Inspect PE/CLI metadata members, signatures, and CIL anchors without loading target code",
args: z.object({
path: z.string().describe("Managed PE executable or assembly path"),
}),
options: z.object({
typeOffset: z.number().int().min(0).default(0),
typeLimit: z.number().int().min(1).max(500).default(100),
methodOffset: z.number().int().min(0).default(0),
methodLimit: z.number().int().min(1).max(500).default(100),
fieldOffset: z.number().int().min(0).default(0),
fieldLimit: z.number().int().min(1).max(500).default(100),
memberRefOffset: z.number().int().min(0).default(0),
memberRefLimit: z.number().int().min(1).max(500).default(100),
edgeOffset: z.number().int().min(0).default(0),
edgeLimit: z.number().int().min(1).max(1_000).default(250),
instructionAnchorLimit: z.number().int().min(0).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(1_000_000).default(100_000),
maxHeapItemBytes: z
.number()
.int()
.min(1)
.max(16_777_216)
.default(1_048_576),
maxMethodBodyBytes: z
.number()
.int()
.min(1)
.max(16_777_216)
.default(1_048_576),
maxMethodInstructions: z
.number()
.int()
.min(1)
.max(100_000)
.default(10_000),
}),
alias: {
typeOffset: "type-offset",
typeLimit: "type-limit",
methodOffset: "method-offset",
methodLimit: "method-limit",
fieldOffset: "field-offset",
fieldLimit: "field-limit",
memberRefOffset: "member-ref-offset",
memberRefLimit: "member-ref-limit",
edgeOffset: "edge-offset",
edgeLimit: "edge-limit",
instructionAnchorLimit: "instruction-anchor-limit",
maxFileBytes: "max-file-bytes",
maxMetadataBytes: "max-metadata-bytes",
maxTableRows: "max-table-rows",
maxHeapItemBytes: "max-heap-item-bytes",
maxMethodBodyBytes: "max-method-body-bytes",
maxMethodInstructions: "max-method-instructions",
},
run: ({ args, options }) =>
logCliCommand(logger, "inspect-managed-members", () =>
runProviderAnalysis(
args.path,
"inspect_managed_members",
{
type_offset: options.typeOffset,
type_limit: options.typeLimit,
method_offset: options.methodOffset,
method_limit: options.methodLimit,
field_offset: options.fieldOffset,
field_limit: options.fieldLimit,
member_ref_offset: options.memberRefOffset,
member_ref_limit: options.memberRefLimit,
edge_offset: options.edgeOffset,
edge_limit: options.edgeLimit,
instruction_anchor_limit: options.instructionAnchorLimit,
max_file_bytes: options.maxFileBytes,
max_metadata_bytes: options.maxMetadataBytes,
max_table_rows: options.maxTableRows,
max_heap_item_bytes: options.maxHeapItemBytes,
max_method_body_bytes: options.maxMethodBodyBytes,
max_method_instructions: options.maxMethodInstructions,
},
logger,
),
),
});
};
const registerNativeCommands = (
+1
View File
@@ -17,6 +17,7 @@ export const CLI_COMMANDS = Object.freeze({
inventoryArtifact: "inventory-artifact",
extractArtifact: "extract-artifact",
inspectManagedArtifact: "inspect-managed-artifact",
inspectManagedMembers: "inspect-managed-members",
inspectMacho: "inspect-macho",
inspectSignature: "inspect-signature",
listArchitectures: "list-architectures",
+64
View File
@@ -32,9 +32,53 @@ export const managedArtifactInputSchema = z.object({
.default(1_048_576),
});
/** Exact caller boundary for execution-free metadata/signature/IL inspection. */
export const managedMemberInputSchema = z.object({
type_offset: z.number().int().min(0).default(0),
type_limit: z.number().int().min(1).max(500).default(100),
method_offset: z.number().int().min(0).default(0),
method_limit: z.number().int().min(1).max(500).default(100),
field_offset: z.number().int().min(0).default(0),
field_limit: z.number().int().min(1).max(500).default(100),
member_ref_offset: z.number().int().min(0).default(0),
member_ref_limit: z.number().int().min(1).max(500).default(100),
edge_offset: z.number().int().min(0).default(0),
edge_limit: z.number().int().min(1).max(1_000).default(250),
instruction_anchor_limit: z.number().int().min(0).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),
max_method_body_bytes: z
.number()
.int()
.min(1)
.max(16_777_216)
.default(1_048_576),
max_method_instructions: z.number().int().min(1).max(100_000).default(10_000),
});
const outputSchema = managedOutputSchemas.inspect_managed_artifact;
if (outputSchema === undefined)
throw new Error("Missing managed output schema for inspect_managed_artifact");
const memberOutputSchema = managedOutputSchemas.inspect_managed_members;
if (memberOutputSchema === undefined)
throw new Error("Missing managed output schema for inspect_managed_members");
/** Read-only managed artifact contracts. */
export const MANAGED_TOOL_CONTRACTS = [
@@ -58,6 +102,26 @@ export const MANAGED_TOOL_CONTRACTS = [
},
],
},
{
name: "inspect_managed_members",
description:
"Inspect bounded PE/CLI metadata members, signatures, method body IL hashes, exception regions, call edges, and field-access anchors without loading or executing target code. Metadata tokens are reported as build-local coordinates bound to the artifact SHA-256 and MVID.",
kind: "managed-provider",
inputSchema: managedMemberInputSchema,
outputSchema: memberOutputSchema,
annotations: {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
},
examples: [
{
title: "Example inspect managed members request",
input: { method_limit: 25, edge_limit: 100 },
},
],
},
] as const satisfies readonly ToolContract[];
/** Names of execution-free managed static operations. */
+5 -1
View File
@@ -24,7 +24,10 @@ import {
artifactExtractionResultSchema,
artifactInventoryResultSchema,
} from "../domain/artifactGraph.js";
import { managedArtifactInspectionSchema } from "../domain/managedArtifact.js";
import {
managedArtifactInspectionSchema,
managedMemberInspectionSchema,
} from "../domain/managedArtifact.js";
import { artifactComparisonResultSchema } from "../domain/artifactComparison.js";
import { functionComparisonResultSchema } from "../domain/functionComparison.js";
import { bundleComparisonResultSchema } from "../domain/bundleComparison.js";
@@ -533,6 +536,7 @@ export const artifactOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
/** Exact Evidence v2 schema for execution-free managed static analysis. */
export const managedOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
inspect_managed_artifact: resultOf(managedArtifactInspectionSchema),
inspect_managed_members: resultOf(managedMemberInspectionSchema),
};
/** Exact structured-content schemas for target lifecycle operations. */
+171
View File
@@ -82,6 +82,138 @@ const customAttributeSchema = z.object({
row_offset: offsetSchema,
});
const managedSignatureSchema = z.object({
raw_length: z.number().int().min(0),
raw_sha256: digestSchema,
kind: z.enum(["method", "field", "unknown"]),
parse_status: z.enum(["decoded", "partial", "unsupported", "malformed"]),
calling_convention: z.string().nullable(),
generic_parameter_count: z.number().int().min(0).nullable(),
parameter_count: z.number().int().min(0).nullable(),
return_type: z.string().nullable(),
parameter_types: z.array(z.string()),
field_type: z.string().nullable(),
issue: z.string().nullable(),
});
const managedTypeSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
namespace: z.string(),
name: z.string(),
full_name: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
extends_token: tokenSchema.nullable(),
field_list: z.object({
first_row: z.number().int().min(1).nullable(),
last_row: z.number().int().min(0).nullable(),
count: z.number().int().min(0),
}),
method_list: z.object({
first_row: z.number().int().min(1).nullable(),
last_row: z.number().int().min(0).nullable(),
count: z.number().int().min(0),
}),
});
const managedFieldSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
declaring_type_token: tokenSchema.nullable(),
declaring_type: z.string().nullable(),
name: z.string(),
flags: z.number().int().min(0).max(0xffff),
signature: managedSignatureSchema,
});
const managedExceptionRegionSchema = z.object({
flags: z.number().int().min(0).max(0xffff_ffff),
try_offset: z.number().int().min(0),
try_length: z.number().int().min(0),
handler_offset: z.number().int().min(0),
handler_length: z.number().int().min(0),
class_token: tokenSchema.nullable(),
filter_offset: z.number().int().min(0).nullable(),
});
const managedInstructionAnchorSchema = z.object({
il_offset: z.number().int().min(0),
opcode: z.string().min(1),
operand_kind: z.enum([
"none",
"branch",
"constant",
"field",
"method",
"signature",
"string",
"switch",
"token",
"type",
"variable",
"unknown",
]),
operand: z.string().nullable(),
});
const managedMethodBodySchema = z.object({
status: z.enum(["present", "absent", "malformed", "too-large"]),
header_format: z.enum(["tiny", "fat", "none", "unknown"]),
rva: z.number().int().min(0).max(0xffff_ffff),
file_offset: offsetSchema.nullable(),
max_stack: z.number().int().min(0).nullable(),
init_locals: z.boolean().nullable(),
local_var_sig_token: tokenSchema.nullable(),
il_size: z.number().int().min(0),
il_sha256: digestSchema.nullable(),
normalized_il_sha256: digestSchema.nullable(),
instruction_count: z.number().int().min(0),
decoded_instruction_count: z.number().int().min(0),
truncated_instructions: z.number().int().min(0),
opcode_counts: z.record(z.string(), z.number().int().min(1)),
anchors: z.array(managedInstructionAnchorSchema),
exception_regions: z.array(managedExceptionRegionSchema),
issue: z.string().nullable(),
});
const managedMethodSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
declaring_type_token: tokenSchema.nullable(),
declaring_type: z.string().nullable(),
name: z.string(),
rva: z.number().int().min(0).max(0xffff_ffff),
impl_flags: z.number().int().min(0).max(0xffff),
flags: z.number().int().min(0).max(0xffff),
signature: managedSignatureSchema,
body: managedMethodBodySchema,
});
const managedMemberReferenceSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
parent_token: tokenSchema.nullable(),
name: z.string(),
signature: managedSignatureSchema,
});
const managedCallEdgeSchema = z.object({
caller_token: tokenSchema,
caller: z.string().nullable(),
opcode: z.string(),
target_token: tokenSchema,
target_kind: z.enum(["method-def", "member-ref", "method-spec", "unknown"]),
target_name: z.string().nullable(),
});
const managedFieldAccessSchema = z.object({
method_token: tokenSchema,
method: z.string().nullable(),
opcode: z.string(),
field_token: tokenSchema,
field_name: z.string().nullable(),
});
const managedParseIssueSchema = z.object({
code: z.enum([
"invalid-cli-header",
@@ -199,7 +331,46 @@ export const managedArtifactInspectionSchema = z.object({
limitations: z.array(z.string()),
});
/** Provider-neutral, execution-free metadata/signature/IL member inspection. */
export const managedMemberInspectionSchema = 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"),
}),
module: moduleIdentitySchema.nullable(),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
identity_scope: z.object({
token_identity: z.literal("build-local"),
requires_artifact_sha256: digestSchema,
requires_mvid: z.string().uuid().nullable(),
}),
types: managedPage(managedTypeSchema),
fields: managedPage(managedFieldSchema),
methods: managedPage(managedMethodSchema),
member_refs: managedPage(managedMemberReferenceSchema),
call_edges: managedPage(managedCallEdgeSchema),
field_accesses: managedPage(managedFieldAccessSchema),
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 ManagedMemberInspection = z.infer<
typeof managedMemberInspectionSchema
>;
export type ManagedParseIssue = z.infer<typeof managedParseIssueSchema>;
File diff suppressed because it is too large Load Diff
+116 -37
View File
@@ -14,6 +14,7 @@ import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.j
import {
MANAGED_TOOL_CONTRACTS,
managedArtifactInputSchema,
managedMemberInputSchema,
type ManagedToolName,
} from "../contracts/managedToolContracts.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
@@ -23,9 +24,15 @@ import {
EvidenceIntegrityError,
ProviderAdapterError,
} from "../domain/errors.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type {
ManagedArtifactInspection,
ManagedMemberInspection,
} from "../domain/managedArtifact.js";
import { err, ok } from "../domain/result.js";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
const IDENTITY: ProviderIdentity = Object.freeze(MANAGED_STATIC_PROVIDER);
@@ -56,10 +63,7 @@ export class ManagedStaticProvider implements AnalysisProvider {
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.",
]),
limitations: limitationsFor(contract.name),
}),
),
);
@@ -104,28 +108,28 @@ class ManagedStaticClient implements AnalysisClient {
),
);
try {
const input = managedArtifactInputSchema.parse(parameters);
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const maxFileBytes = maxRequestedFileBytes(operation, parameters);
const metadata = await stat(this.target.path);
if (metadata.size > input.max_file_bytes)
if (metadata.size > maxFileBytes)
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
`Artifact size ${String(metadata.size)} exceeds max_file_bytes ${String(input.max_file_bytes)}.`,
`Artifact size ${String(metadata.size)} exceeds max_file_bytes ${String(maxFileBytes)}.`,
),
);
const bytes = await readFile(
this.target.path,
options?.signal === undefined ? undefined : { signal: options.signal },
);
if (bytes.length > input.max_file_bytes)
if (bytes.length > maxFileBytes)
return err(
new AnalysisCapabilityUnavailableError(
IDENTITY.id,
operation,
`Artifact grew beyond max_file_bytes ${String(input.max_file_bytes)} while it was read.`,
`Artifact grew beyond max_file_bytes ${String(maxFileBytes)} while it was read.`,
),
);
const observedDigest = createHash("sha256").update(bytes).digest("hex");
@@ -135,39 +139,18 @@ class ManagedStaticClient implements AnalysisClient {
`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,
});
const result = inspectManagedOperation(
operation,
parameters,
bytes,
this.target,
);
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,
})),
],
locations: managedLocations(result),
}),
);
} catch (cause: unknown) {
@@ -186,3 +169,99 @@ const isManagedOperation = (
operation: AnalysisOperation,
): operation is ManagedToolName =>
MANAGED_TOOL_CONTRACTS.some(({ name }) => name === operation);
const limitationsFor = (operation: ManagedToolName): readonly string[] =>
Object.freeze(
operation === "inspect_managed_artifact"
? [
"This capability inventories PE/CLI identity only; inspect_managed_members admits bounded metadata members, signatures, and CIL anchors.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
]
: [
"This capability decodes bounded PE/CLI metadata members, signatures, and file-backed method bodies; decompiled C# and cross-build matching are separate future contracts.",
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
],
);
const maxRequestedFileBytes = (
operation: ManagedToolName,
parameters: Readonly<Record<string, JsonValue>>,
): number => {
if (operation === "inspect_managed_artifact")
return managedArtifactInputSchema.parse(parameters).max_file_bytes;
return managedMemberInputSchema.parse(parameters).max_file_bytes;
};
const inspectManagedOperation = (
operation: ManagedToolName,
parameters: Readonly<Record<string, JsonValue>>,
bytes: Buffer,
target: BinaryTarget,
): ManagedArtifactInspection | ManagedMemberInspection => {
if (operation === "inspect_managed_artifact") {
const input = managedArtifactInputSchema.parse(parameters);
return inspectManagedArtifactBytes(bytes, 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,
});
}
const input = managedMemberInputSchema.parse(parameters);
return inspectManagedMembersBytes(bytes, target, {
typeOffset: input.type_offset,
typeLimit: input.type_limit,
methodOffset: input.method_offset,
methodLimit: input.method_limit,
fieldOffset: input.field_offset,
fieldLimit: input.field_limit,
memberRefOffset: input.member_ref_offset,
memberRefLimit: input.member_ref_limit,
edgeOffset: input.edge_offset,
edgeLimit: input.edge_limit,
instructionAnchorLimit: input.instruction_anchor_limit,
maxMetadataBytes: input.max_metadata_bytes,
maxTableRows: input.max_table_rows,
maxHeapItemBytes: input.max_heap_item_bytes,
maxMethodBodyBytes: input.max_method_body_bytes,
maxMethodInstructions: input.max_method_instructions,
});
};
const managedLocations = (
result: ManagedArtifactInspection | ManagedMemberInspection,
): readonly EvidenceLocation[] => {
if ("pe" in result) {
if (result.pe.cli === null) return [{ kind: "file-offset", offset: 0 }];
return [
{
kind: "file-offset-range",
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,
})),
];
}
return [
...(result.module === null
? [{ kind: "file-offset" as const, offset: 0 }]
: [{ kind: "file-offset" as const, offset: result.module.row_offset }]),
...result.methods.items
.filter((method) => method.body.file_offset !== null)
.slice(0, 8)
.map((method) => ({
kind: "file-offset" as const,
offset: method.body.file_offset ?? 0,
})),
];
};