Merge remote-tracking branch 'origin/main' into feat/dylib-resolution
# Conflicts: # docs/product-catalog.json # docs/verification/managed-conformance-manifest.json # skills/reverse-engineer-anything/SKILL.md # src/generatedMcpToolCatalog.ts
This commit is contained in:
@@ -42,12 +42,13 @@ const SOURCE_PATHS = {
|
||||
sessionContracts: "dist/contracts/sessionToolContracts.js",
|
||||
nativeContracts: "dist/contracts/nativeToolContracts.js",
|
||||
artifactContracts: "dist/contracts/artifactToolContracts.js",
|
||||
managedContracts: "dist/contracts/managedToolContracts.js",
|
||||
managedContracts: "dist/contracts/managed/managedToolContracts.js",
|
||||
firmwareContracts: "dist/contracts/firmware/firmwareToolContracts.js",
|
||||
firmwareProvider: "dist/firmware/FirmwareRelease.js",
|
||||
androidContracts: "dist/contracts/android/androidToolContracts.js",
|
||||
androidProvider: "dist/android/JadxRelease.js",
|
||||
managedWorkflowContracts: "dist/contracts/managedWorkflowToolContracts.js",
|
||||
managedWorkflowContracts:
|
||||
"dist/contracts/managed/managedWorkflowToolContracts.js",
|
||||
browserContracts: "dist/contracts/browserToolContracts.js",
|
||||
browserScenarioContracts: "dist/contracts/browserScenarioToolContracts.js",
|
||||
electronContracts: "dist/contracts/javascript/electronToolContracts.js",
|
||||
@@ -88,9 +89,9 @@ const SOURCE_PATHS = {
|
||||
"dist/domain/javascript/javascriptRuntimeObservation.js",
|
||||
webBundleAnalysis: "dist/domain/webBundleAnalysis.js",
|
||||
webCaptureDiff: "dist/domain/webCaptureDiff.js",
|
||||
managedArtifact: "dist/domain/managedArtifact.js",
|
||||
managedComparison: "dist/domain/managedMemberComparison.js",
|
||||
managedNativeVerification: "dist/domain/managedNativeVerification.js",
|
||||
managedArtifact: "dist/domain/managed/managedArtifact.js",
|
||||
managedComparison: "dist/domain/managed/managedMemberComparison.js",
|
||||
managedNativeVerification: "dist/domain/managed/managedNativeVerification.js",
|
||||
webMcpDiscovery: "dist/domain/webMcpDiscovery.js",
|
||||
webScreenshot: "dist/domain/webScreenshot.js",
|
||||
javascriptApplicationGraph:
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
import { createEvidence } from "../../dist/domain/evidence.js";
|
||||
|
||||
const COMPLETION_PROVIDER = {
|
||||
id: "rea-managed-conformance",
|
||||
name: "REA managed conformance verifier",
|
||||
version: "1",
|
||||
};
|
||||
|
||||
const completionClaim = ({
|
||||
claimId,
|
||||
scenarioId,
|
||||
targets = [],
|
||||
status = "pass",
|
||||
limitations = [],
|
||||
}) => {
|
||||
const artifactSha256s = [
|
||||
...new Set(targets.map(({ sha256: digest }) => digest)),
|
||||
].sort();
|
||||
const evidence = createEvidence(targets[0], COMPLETION_PROVIDER, {
|
||||
predicateType: "rea.verification",
|
||||
operation: "verify_managed_conformance",
|
||||
parameters: {
|
||||
scenario_id: scenarioId,
|
||||
scenario_version: 1,
|
||||
artifact_sha256s: artifactSha256s,
|
||||
},
|
||||
result: { status },
|
||||
rawResult: null,
|
||||
limitations,
|
||||
});
|
||||
return {
|
||||
claim_id: claimId,
|
||||
scenario: { id: scenarioId, version: 1 },
|
||||
artifact_sha256s: artifactSha256s,
|
||||
provider: {
|
||||
id: COMPLETION_PROVIDER.id,
|
||||
version: COMPLETION_PROVIDER.version,
|
||||
},
|
||||
status,
|
||||
evidence_ids: [evidence.evidence_id],
|
||||
};
|
||||
};
|
||||
|
||||
const optionalTarget = (target) =>
|
||||
target === undefined
|
||||
? []
|
||||
: [{ path: target.file_name, sha256: target.sha256, format: "pe" }];
|
||||
|
||||
const sourceOwnedClaims = ({
|
||||
modern,
|
||||
framework,
|
||||
nativeFunctionTarget,
|
||||
readyToRun,
|
||||
obfuscated,
|
||||
left,
|
||||
right,
|
||||
nativeOnly,
|
||||
malformed,
|
||||
manifestSelfTest,
|
||||
}) => [
|
||||
completionClaim({
|
||||
claimId: "managed.modern-dotnet-anycpu",
|
||||
scenarioId: "modern-dotnet-anycpu",
|
||||
targets: [modern.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.dotnet-framework-x86-pinvoke",
|
||||
scenarioId: "dotnet-framework-x86-pinvoke",
|
||||
targets: [framework.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.x64-ready-to-run-native-body",
|
||||
scenarioId: "x64-ready-to-run-native-body",
|
||||
targets: [readyToRun.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.managed-native-verification",
|
||||
scenarioId: "managed-native-verification",
|
||||
targets: [framework.target, nativeFunctionTarget],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.application-graph-projection",
|
||||
scenarioId: "managed-application-graph-projection",
|
||||
targets: [framework.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.unicode-obfuscated-identifiers",
|
||||
scenarioId: "unicode-obfuscated-identifiers",
|
||||
targets: [obfuscated.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.decompiler-reconstruction-import",
|
||||
scenarioId: "decompiler-reconstruction-import",
|
||||
targets: [obfuscated.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.mvid-and-token-drift",
|
||||
scenarioId: "mvid-and-token-drift",
|
||||
targets: [left.target, right.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.not-managed",
|
||||
scenarioId: "not-managed",
|
||||
targets: [nativeOnly.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.malformed-metadata",
|
||||
scenarioId: "malformed-metadata",
|
||||
targets: [malformed.target],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.operator-manifest-self-test",
|
||||
scenarioId: "operator-manifest-self-test",
|
||||
targets: [
|
||||
{
|
||||
path: manifestSelfTest.target.file_name,
|
||||
sha256: manifestSelfTest.target.sha256,
|
||||
format: "pe",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const optionalClaims = ({ operatorManifest, ilspyOracle }) => [
|
||||
completionClaim({
|
||||
claimId: "managed.operator-local-manifest",
|
||||
scenarioId: "operator-local-manifest",
|
||||
targets: optionalTarget(operatorManifest?.target),
|
||||
status: operatorManifest === null ? "unsupported" : "pass",
|
||||
limitations:
|
||||
operatorManifest === null
|
||||
? ["REA_MANAGED_APP_MANIFEST_PATH is not configured."]
|
||||
: [],
|
||||
}),
|
||||
completionClaim({
|
||||
claimId: "managed.ilspy-reconstruction-oracle",
|
||||
scenarioId: "ilspy-reconstruction-oracle",
|
||||
targets: optionalTarget(ilspyOracle?.fixture),
|
||||
status: ilspyOracle === null ? "unsupported" : "pass",
|
||||
limitations:
|
||||
ilspyOracle === null ? ["REA_ILSPY_CMD_PATH is not configured."] : [],
|
||||
}),
|
||||
];
|
||||
|
||||
/** Project completed managed assertions into the standard verifier report. */
|
||||
export const createManagedCompletionReport = (input, verifierRun) => ({
|
||||
verifier: {
|
||||
id: COMPLETION_PROVIDER.id,
|
||||
version: COMPLETION_PROVIDER.version,
|
||||
},
|
||||
verifier_run: verifierRun,
|
||||
environment: {
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
runtime: "node",
|
||||
runtime_version: process.versions.node.split(".")[0],
|
||||
},
|
||||
claims: [...sourceOwnedClaims(input), ...optionalClaims(input)],
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
export const inspectionLimits = {
|
||||
referenceOffset: 0,
|
||||
referenceLimit: 100,
|
||||
resourceOffset: 0,
|
||||
resourceLimit: 100,
|
||||
attributeOffset: 0,
|
||||
attributeLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
export const memberLimits = {
|
||||
typeOffset: 0,
|
||||
typeLimit: 100,
|
||||
methodOffset: 0,
|
||||
methodLimit: 100,
|
||||
fieldOffset: 0,
|
||||
fieldLimit: 100,
|
||||
memberRefOffset: 0,
|
||||
memberRefLimit: 100,
|
||||
edgeOffset: 0,
|
||||
edgeLimit: 100,
|
||||
instructionAnchorLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
maxMethodBodyBytes: 1024 * 1024,
|
||||
maxMethodInstructions: 1_000,
|
||||
};
|
||||
|
||||
export const nativeBoundaryLimits = {
|
||||
moduleRefOffset: 0,
|
||||
moduleRefLimit: 100,
|
||||
importOffset: 0,
|
||||
importLimit: 100,
|
||||
implementationOffset: 0,
|
||||
implementationLimit: 100,
|
||||
maxMetadataBytes: 1024 * 1024,
|
||||
maxTableRows: 1_000,
|
||||
maxHeapItemBytes: 1024 * 1024,
|
||||
};
|
||||
|
||||
export const comparisonLimits = {
|
||||
max_method_matches: 100,
|
||||
max_field_matches: 100,
|
||||
max_candidates: 20,
|
||||
};
|
||||
|
||||
export const defaultIlBody = Buffer.from([
|
||||
0x32, 0x02, 0x7b, 0x01, 0x00, 0x00, 0x04, 0x28, 0x01, 0x00, 0x00, 0x0a, 0x2a,
|
||||
]);
|
||||
|
||||
export function functionDossier(name) {
|
||||
return {
|
||||
procedure: {
|
||||
address: "0x401000",
|
||||
name,
|
||||
classification: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
provenance: "synthetic-provider",
|
||||
},
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: "",
|
||||
assembly: [],
|
||||
comments: [],
|
||||
callers: [],
|
||||
callees: [],
|
||||
incoming_references: [],
|
||||
outgoing_references: [],
|
||||
referenced_strings: [],
|
||||
referenced_names: [],
|
||||
basic_blocks: [],
|
||||
limitations: [],
|
||||
};
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
export function parseManagedAppManifest(rawManifest) {
|
||||
const manifest = object(rawManifest, "manifest");
|
||||
const target = object(manifest.target, "manifest.target");
|
||||
const methods = array(manifest.methods, "manifest.methods");
|
||||
ensure(manifest.methods.length > 0, "manifest.methods must not be empty");
|
||||
return {
|
||||
label: optionalString(manifest.label, "manifest.label"),
|
||||
target: {
|
||||
path: string(target.path, "manifest.target.path"),
|
||||
sha256: digest(target.sha256, "manifest.target.sha256"),
|
||||
mvid: optionalCliMetadataGuid(target.mvid, "manifest.target.mvid"),
|
||||
assembly_name: optionalString(
|
||||
target.assembly_name,
|
||||
"manifest.target.assembly_name",
|
||||
),
|
||||
runtime_family: optionalString(
|
||||
target.runtime_family,
|
||||
"manifest.target.runtime_family",
|
||||
),
|
||||
managed_architecture: optionalString(
|
||||
target.managed_architecture,
|
||||
"manifest.target.managed_architecture",
|
||||
),
|
||||
},
|
||||
methods: methods.map((method, index) =>
|
||||
parseManagedAppManifestMethod(method, index),
|
||||
),
|
||||
application_graph: parseManagedAppManifestGraph(manifest.application_graph),
|
||||
};
|
||||
}
|
||||
|
||||
function parseManagedAppManifestGraph(rawGraph) {
|
||||
if (rawGraph === undefined) return undefined;
|
||||
const graph = object(rawGraph, "manifest.application_graph");
|
||||
const expectedKinds =
|
||||
graph.expected_node_kinds === undefined
|
||||
? []
|
||||
: array(
|
||||
graph.expected_node_kinds,
|
||||
"manifest.application_graph.expected_node_kinds",
|
||||
).map((kind, index) =>
|
||||
string(
|
||||
kind,
|
||||
`manifest.application_graph.expected_node_kinds[${String(index)}]`,
|
||||
),
|
||||
);
|
||||
const traces =
|
||||
graph.feature_traces === undefined
|
||||
? []
|
||||
: array(
|
||||
graph.feature_traces,
|
||||
"manifest.application_graph.feature_traces",
|
||||
).map((trace, index) => parseManagedAppManifestTrace(trace, index));
|
||||
ensure(
|
||||
expectedKinds.length > 0 || traces.length > 0,
|
||||
"manifest.application_graph must declare expected_node_kinds or feature_traces",
|
||||
);
|
||||
return {
|
||||
expected_node_kinds: expectedKinds,
|
||||
feature_traces: traces,
|
||||
};
|
||||
}
|
||||
|
||||
function parseManagedAppManifestTrace(rawTrace, index) {
|
||||
const prefix = `manifest.application_graph.feature_traces[${String(index)}]`;
|
||||
const trace = object(rawTrace, prefix);
|
||||
const match = trace.match ?? "exact";
|
||||
ensure(
|
||||
match === "exact" || match === "contains",
|
||||
`${prefix}.match must be exact or contains`,
|
||||
);
|
||||
const caseSensitive = trace.case_sensitive ?? true;
|
||||
ensure(
|
||||
typeof caseSensitive === "boolean",
|
||||
`${prefix}.case_sensitive must be a boolean`,
|
||||
);
|
||||
const minMatchedSeeds = trace.min_matched_seeds ?? 1;
|
||||
ensure(
|
||||
Number.isInteger(minMatchedSeeds) && minMatchedSeeds > 0,
|
||||
`${prefix}.min_matched_seeds must be a positive integer`,
|
||||
);
|
||||
return {
|
||||
label: optionalString(trace.label, `${prefix}.label`),
|
||||
method_token: methodToken(trace.method_token, `${prefix}.method_token`),
|
||||
seed: string(trace.seed, `${prefix}.seed`),
|
||||
match,
|
||||
case_sensitive: caseSensitive,
|
||||
min_matched_seeds: minMatchedSeeds,
|
||||
};
|
||||
}
|
||||
|
||||
function parseManagedAppManifestMethod(rawMethod, index) {
|
||||
const prefix = `manifest.methods[${String(index)}]`;
|
||||
const method = object(rawMethod, prefix);
|
||||
const token = methodToken(method.token, `${prefix}.token`);
|
||||
return {
|
||||
label: optionalString(method.label, `${prefix}.label`),
|
||||
token,
|
||||
signature_sha256: digest(
|
||||
method.signature_sha256,
|
||||
`${prefix}.signature_sha256`,
|
||||
),
|
||||
il_size: nonNegativeInteger(method.il_size, `${prefix}.il_size`),
|
||||
il_sha256:
|
||||
method.il_sha256 === undefined
|
||||
? undefined
|
||||
: digest(method.il_sha256, `${prefix}.il_sha256`),
|
||||
normalized_il_sha256: digest(
|
||||
method.normalized_il_sha256,
|
||||
`${prefix}.normalized_il_sha256`,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function object(value, name) {
|
||||
ensure(
|
||||
value !== null && typeof value === "object" && !Array.isArray(value),
|
||||
`${name} must be an object`,
|
||||
);
|
||||
return value;
|
||||
}
|
||||
|
||||
function array(value, name) {
|
||||
ensure(Array.isArray(value), `${name} must be an array`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function string(value, name) {
|
||||
ensure(
|
||||
typeof value === "string" && value.length > 0,
|
||||
`${name} must be a non-empty string`,
|
||||
);
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalString(value, name) {
|
||||
if (value === undefined) return undefined;
|
||||
return string(value, name);
|
||||
}
|
||||
|
||||
function nonNegativeInteger(value, name) {
|
||||
ensure(
|
||||
Number.isInteger(value) && value >= 0,
|
||||
`${name} must be a non-negative integer`,
|
||||
);
|
||||
return value;
|
||||
}
|
||||
|
||||
function digest(value, name) {
|
||||
const text = string(value, name);
|
||||
ensure(/^[a-f0-9]{64}$/u.test(text), `${name} must be a lowercase sha256`);
|
||||
return text;
|
||||
}
|
||||
|
||||
function optionalCliMetadataGuid(value, name) {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return null;
|
||||
const text = string(value, name);
|
||||
ensure(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/u.test(
|
||||
text,
|
||||
),
|
||||
`${name} must be a lowercase GUID`,
|
||||
);
|
||||
return text;
|
||||
}
|
||||
|
||||
function metadataToken(value, name) {
|
||||
const text = string(value, name);
|
||||
ensure(/^0x[0-9a-f]{8}$/u.test(text), `${name} must be a metadata token`);
|
||||
return text;
|
||||
}
|
||||
|
||||
function methodToken(value, name) {
|
||||
const token = metadataToken(value, name);
|
||||
ensure(
|
||||
token.startsWith("0x06"),
|
||||
`${name} must be a MethodDef token beginning with 0x06`,
|
||||
);
|
||||
return token;
|
||||
}
|
||||
|
||||
export function methodTokenRow(token) {
|
||||
const row = Number.parseInt(token.slice(4), 16);
|
||||
ensure(row > 0, `method token ${token} has an invalid row id`);
|
||||
return row;
|
||||
}
|
||||
|
||||
export function ensure(condition, message) {
|
||||
if (!condition)
|
||||
throw new Error(`managed app manifest verification failed: ${message}`);
|
||||
}
|
||||
@@ -1,329 +0,0 @@
|
||||
import { basename, dirname, isAbsolute, resolve } from "node:path";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js";
|
||||
import { inspectManagedArtifactBytes } from "../../dist/dotnet/ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "../../dist/dotnet/ManagedMemberInspector.js";
|
||||
import { projectManagedApplicationGraphEvidence } from "../../dist/application/ManagedApplicationGraphService.js";
|
||||
import { traceApplicationFeatureEvidence } from "../../dist/application/javascript/JavaScriptApplicationWorkflowService.js";
|
||||
import { createEvidence } from "../../dist/domain/evidence.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../../dist/application/InvestigationProviders.js";
|
||||
import {
|
||||
ensure,
|
||||
methodTokenRow,
|
||||
parseManagedAppManifest,
|
||||
} from "./managed-conformance-manifest-parser.mjs";
|
||||
|
||||
export const createManagedManifestVerifier = (context) => ({
|
||||
verifyManagedAppManifest: (rawManifest, manifestPath) =>
|
||||
verifyManagedAppManifest(context, rawManifest, manifestPath),
|
||||
});
|
||||
|
||||
async function verifyManagedAppManifest(context, rawManifest, manifestPath) {
|
||||
const { appManifestInspectionLimits } = context;
|
||||
const manifest = parseManagedAppManifest(rawManifest);
|
||||
const targetPath = isAbsolute(manifest.target.path)
|
||||
? manifest.target.path
|
||||
: resolve(dirname(manifestPath), manifest.target.path);
|
||||
const parsedTarget = await parseBinaryTarget(targetPath);
|
||||
ensure(
|
||||
parsedTarget.ok,
|
||||
`target ${targetPath} could not be parsed as a binary target`,
|
||||
);
|
||||
const target = parsedTarget.value;
|
||||
ensure(
|
||||
target.sha256 === manifest.target.sha256,
|
||||
`target sha256 mismatch: expected ${manifest.target.sha256}, observed ${target.sha256}`,
|
||||
);
|
||||
const bytes = await readFile(targetPath);
|
||||
const artifact = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
target,
|
||||
appManifestInspectionLimits,
|
||||
);
|
||||
verifyManifestTarget(manifest, artifact);
|
||||
const methodVerification = verifyManifestMethods(
|
||||
context,
|
||||
manifest,
|
||||
bytes,
|
||||
target,
|
||||
);
|
||||
const { methods, inspectedMethods } = methodVerification;
|
||||
let assertions = 1 + methodVerification.assertions;
|
||||
const applicationGraph =
|
||||
manifest.application_graph === undefined
|
||||
? undefined
|
||||
: verifyManagedAppManifestApplicationGraph({
|
||||
context,
|
||||
graphManifest: manifest.application_graph,
|
||||
bytes,
|
||||
target,
|
||||
artifact,
|
||||
manifestMethods: manifest.methods,
|
||||
inspectedMethods,
|
||||
});
|
||||
if (applicationGraph !== undefined) assertions += applicationGraph.assertions;
|
||||
return {
|
||||
label: manifest.label ?? null,
|
||||
assertions,
|
||||
target: {
|
||||
file_name: basename(targetPath),
|
||||
sha256: target.sha256,
|
||||
mvid: artifact.module?.mvid ?? null,
|
||||
assembly_name: artifact.assembly?.name ?? null,
|
||||
runtime_family: artifact.classification.runtime_family,
|
||||
managed_architecture: artifact.classification.managed_architecture,
|
||||
},
|
||||
methods,
|
||||
...(applicationGraph === undefined
|
||||
? {}
|
||||
: { application_graph: applicationGraph.summary }),
|
||||
};
|
||||
}
|
||||
|
||||
function verifyManifestTarget(manifest, artifact) {
|
||||
ensure(
|
||||
artifact.classification.status === "managed",
|
||||
`target is ${artifact.classification.status}, expected managed`,
|
||||
);
|
||||
if (manifest.target.mvid !== undefined)
|
||||
ensure(
|
||||
artifact.module?.mvid === manifest.target.mvid,
|
||||
`target MVID mismatch: expected ${manifest.target.mvid}, observed ${artifact.module?.mvid ?? "null"}`,
|
||||
);
|
||||
if (manifest.target.assembly_name !== undefined)
|
||||
ensure(
|
||||
artifact.assembly?.name === manifest.target.assembly_name,
|
||||
`assembly name mismatch: expected ${manifest.target.assembly_name}, observed ${artifact.assembly?.name ?? "null"}`,
|
||||
);
|
||||
if (manifest.target.runtime_family !== undefined)
|
||||
ensure(
|
||||
artifact.classification.runtime_family === manifest.target.runtime_family,
|
||||
`runtime family mismatch: expected ${manifest.target.runtime_family}, observed ${artifact.classification.runtime_family}`,
|
||||
);
|
||||
if (manifest.target.managed_architecture !== undefined)
|
||||
ensure(
|
||||
artifact.classification.managed_architecture ===
|
||||
manifest.target.managed_architecture,
|
||||
`managed architecture mismatch: expected ${manifest.target.managed_architecture}, observed ${artifact.classification.managed_architecture}`,
|
||||
);
|
||||
}
|
||||
|
||||
function verifyManifestMethods(context, manifest, bytes, target) {
|
||||
const methods = [];
|
||||
let assertions = 0;
|
||||
const inspectedMethods = new Map();
|
||||
for (const expectedMethod of manifest.methods) {
|
||||
const method = inspectManagedMethodByToken(
|
||||
context,
|
||||
bytes,
|
||||
target,
|
||||
expectedMethod,
|
||||
);
|
||||
ensure(
|
||||
method.signature.raw_sha256 === expectedMethod.signature_sha256,
|
||||
`method ${expectedMethod.token} signature sha256 mismatch: expected ${expectedMethod.signature_sha256}, observed ${method.signature.raw_sha256}`,
|
||||
);
|
||||
ensure(
|
||||
method.body.il_size === expectedMethod.il_size,
|
||||
`method ${expectedMethod.token} IL size mismatch: expected ${String(expectedMethod.il_size)}, observed ${String(method.body.il_size)}`,
|
||||
);
|
||||
if (expectedMethod.il_sha256 !== undefined)
|
||||
ensure(
|
||||
method.body.il_sha256 === expectedMethod.il_sha256,
|
||||
`method ${expectedMethod.token} IL sha256 mismatch: expected ${expectedMethod.il_sha256}, observed ${method.body.il_sha256 ?? "null"}`,
|
||||
);
|
||||
ensure(
|
||||
method.body.normalized_il_sha256 === expectedMethod.normalized_il_sha256,
|
||||
`method ${expectedMethod.token} normalized IL sha256 mismatch: expected ${expectedMethod.normalized_il_sha256}, observed ${method.body.normalized_il_sha256 ?? "null"}`,
|
||||
);
|
||||
assertions += expectedMethod.il_sha256 === undefined ? 4 : 5;
|
||||
inspectedMethods.set(expectedMethod.token, method);
|
||||
methods.push({
|
||||
label: expectedMethod.label ?? null,
|
||||
token: method.token,
|
||||
declaring_type: method.declaring_type,
|
||||
name: method.name,
|
||||
signature_sha256: method.signature.raw_sha256,
|
||||
il_size: method.body.il_size,
|
||||
il_sha256: method.body.il_sha256,
|
||||
normalized_il_sha256: method.body.normalized_il_sha256,
|
||||
});
|
||||
}
|
||||
return { methods, inspectedMethods, assertions };
|
||||
}
|
||||
|
||||
function verifyManagedAppManifestApplicationGraph({
|
||||
context,
|
||||
graphManifest,
|
||||
bytes,
|
||||
target,
|
||||
artifact,
|
||||
manifestMethods,
|
||||
inspectedMethods,
|
||||
}) {
|
||||
const graphByToken = new Map();
|
||||
const projectionState = {
|
||||
context,
|
||||
graphByToken,
|
||||
inspectedMethods,
|
||||
bytes,
|
||||
target,
|
||||
artifact,
|
||||
};
|
||||
const firstToken = manifestMethods[0]?.token;
|
||||
ensure(
|
||||
firstToken !== undefined,
|
||||
"application graph verification requires at least one manifest method",
|
||||
);
|
||||
const baseline = projectManifestMethod(projectionState, firstToken);
|
||||
let assertions = 1;
|
||||
for (const expectedKind of graphManifest.expected_node_kinds) {
|
||||
ensure(
|
||||
baseline.nodeKinds.includes(expectedKind),
|
||||
`application graph is missing expected node kind ${expectedKind}`,
|
||||
);
|
||||
assertions += 1;
|
||||
}
|
||||
|
||||
const traces = [];
|
||||
for (const expectedTrace of graphManifest.feature_traces) {
|
||||
const projection = projectManifestMethod(
|
||||
projectionState,
|
||||
expectedTrace.method_token,
|
||||
);
|
||||
const traced = traceApplicationFeatureEvidence({
|
||||
application: projection.evidence,
|
||||
native_observations: [],
|
||||
seed: {
|
||||
kind: "string",
|
||||
value: expectedTrace.seed,
|
||||
match: expectedTrace.match,
|
||||
case_sensitive: expectedTrace.case_sensitive,
|
||||
},
|
||||
direction: "incoming",
|
||||
});
|
||||
ensure(
|
||||
traced.ok,
|
||||
`application graph trace failed for method ${expectedTrace.method_token}`,
|
||||
);
|
||||
const matched = traced.value.normalized_result.summary.matched_seeds;
|
||||
ensure(
|
||||
matched >= expectedTrace.min_matched_seeds,
|
||||
`application graph trace ${expectedTrace.seed} matched ${String(matched)} seeds, expected at least ${String(expectedTrace.min_matched_seeds)}`,
|
||||
);
|
||||
assertions += 1;
|
||||
traces.push({
|
||||
label: expectedTrace.label ?? null,
|
||||
method_token: expectedTrace.method_token,
|
||||
seed: expectedTrace.seed,
|
||||
matched_seeds: matched,
|
||||
trace_evidence_id: traced.value.evidence_id,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
assertions,
|
||||
summary: {
|
||||
projections: [...graphByToken.values()].map((projection) => ({
|
||||
method_token: projection.method.token,
|
||||
graph_evidence_id: projection.evidence.evidence_id,
|
||||
node_kinds: projection.nodeKinds,
|
||||
summary: projection.summary,
|
||||
})),
|
||||
expected_node_kinds: graphManifest.expected_node_kinds,
|
||||
feature_traces: traces,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const projectManifestMethod = (state, token) => {
|
||||
const { appManifestInspectionLimits, appManifestMemberLimits } =
|
||||
state.context;
|
||||
const existing = state.graphByToken.get(token);
|
||||
if (existing !== undefined) return existing;
|
||||
const method = state.inspectedMethods.get(token);
|
||||
ensure(
|
||||
method !== undefined,
|
||||
`application graph method ${token} must also be declared in manifest.methods`,
|
||||
);
|
||||
const members = inspectManagedMethodPageByToken(
|
||||
state.context,
|
||||
state.bytes,
|
||||
state.target,
|
||||
token,
|
||||
);
|
||||
const artifactEvidence = createEvidence(
|
||||
state.target,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
{
|
||||
operation: "inspect_managed_artifact",
|
||||
parameters: appManifestInspectionLimits,
|
||||
result: state.artifact,
|
||||
rawResult: null,
|
||||
limitations: state.artifact.limitations,
|
||||
locations: [{ kind: "artifact-path", path: state.target.path }],
|
||||
},
|
||||
);
|
||||
const memberEvidence = createEvidence(state.target, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {
|
||||
...appManifestMemberLimits,
|
||||
methodOffset: methodTokenRow(token) - 1,
|
||||
},
|
||||
result: members,
|
||||
rawResult: null,
|
||||
limitations: members.limitations,
|
||||
locations: [{ kind: "artifact-path", path: state.target.path }],
|
||||
});
|
||||
const projected = projectManagedApplicationGraphEvidence({
|
||||
managed_artifact: artifactEvidence,
|
||||
managed_members: memberEvidence,
|
||||
});
|
||||
ensure(
|
||||
projected.ok,
|
||||
`application graph projection failed for method ${token}`,
|
||||
);
|
||||
const projection = {
|
||||
method,
|
||||
evidence: projected.value,
|
||||
nodeKinds: [
|
||||
...new Set(
|
||||
projected.value.normalized_result.graph.nodes.map(({ kind }) => kind),
|
||||
),
|
||||
].sort(),
|
||||
summary: projected.value.normalized_result.summary,
|
||||
};
|
||||
state.graphByToken.set(token, projection);
|
||||
return projection;
|
||||
};
|
||||
|
||||
function inspectManagedMethodByToken(context, bytes, target, expectedMethod) {
|
||||
const members = inspectManagedMethodPageByToken(
|
||||
context,
|
||||
bytes,
|
||||
target,
|
||||
expectedMethod.token,
|
||||
);
|
||||
const method = members.methods.find(
|
||||
({ token }) => token === expectedMethod.token,
|
||||
);
|
||||
ensure(
|
||||
method !== undefined,
|
||||
`method ${expectedMethod.token} was not returned by the member inspector`,
|
||||
);
|
||||
ensure(
|
||||
method.body.status === "present",
|
||||
`method ${expectedMethod.token} body status is ${method.body.status}, expected present`,
|
||||
);
|
||||
return method;
|
||||
}
|
||||
|
||||
function inspectManagedMethodPageByToken(context, bytes, target, token) {
|
||||
const { appManifestMemberLimits } = context;
|
||||
const row = methodTokenRow(token);
|
||||
return inspectManagedMembersBytes(bytes, target, {
|
||||
...appManifestMemberLimits,
|
||||
methodOffset: row - 1,
|
||||
});
|
||||
}
|
||||
@@ -1,306 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { constants } from "node:fs";
|
||||
import { access, readFile } from "node:fs/promises";
|
||||
import { basename, isAbsolute, join, resolve } from "node:path";
|
||||
import assert from "node:assert/strict";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { inspectManagedArtifactBytes } from "../../dist/dotnet/ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "../../dist/dotnet/ManagedMemberInspector.js";
|
||||
import { importManagedReconstructionEvidence } from "../../dist/application/ManagedReconstructionService.js";
|
||||
import { createEvidence } from "../../dist/domain/evidence.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../../dist/application/InvestigationProviders.js";
|
||||
import { createManagedManifestVerifier } from "./managed-conformance-manifest.mjs";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
export const createManagedConformanceOracleSupport = (context) => {
|
||||
const verifier = createManagedManifestVerifier(context);
|
||||
const support = { ...context, ...verifier };
|
||||
return {
|
||||
runManagedAppManifestSelfTest: () => runManagedAppManifestSelfTest(support),
|
||||
runOptionalManagedAppManifest: () => runOptionalManagedAppManifest(support),
|
||||
runOptionalIlspyOracle: () => runOptionalIlspyOracle(support),
|
||||
};
|
||||
};
|
||||
|
||||
async function runManagedAppManifestSelfTest(context) {
|
||||
const sample = await context.fixture("manifest-self-test.exe", {
|
||||
methodName: "PinnedSemanticSlice",
|
||||
ilBody: context.defaultIlBody,
|
||||
});
|
||||
const artifact = inspectManagedArtifactBytes(
|
||||
sample.bytes,
|
||||
sample.target,
|
||||
context.inspectionLimits,
|
||||
);
|
||||
const members = inspectManagedMembersBytes(
|
||||
sample.bytes,
|
||||
sample.target,
|
||||
context.memberLimits,
|
||||
);
|
||||
const method = members.methods[0];
|
||||
assert.ok(method);
|
||||
const summary = await context.verifyManagedAppManifest(
|
||||
{
|
||||
label: "source-owned manifest verifier self-test",
|
||||
target: {
|
||||
path: sample.path,
|
||||
sha256: sample.target.sha256,
|
||||
mvid: artifact.module?.mvid,
|
||||
assembly_name: artifact.assembly?.name,
|
||||
runtime_family: artifact.classification.runtime_family,
|
||||
managed_architecture: artifact.classification.managed_architecture,
|
||||
},
|
||||
methods: [
|
||||
{
|
||||
label: "pinned-semantic-slice",
|
||||
token: method.token,
|
||||
signature_sha256: method.signature.raw_sha256,
|
||||
il_size: method.body.il_size,
|
||||
il_sha256: method.body.il_sha256,
|
||||
normalized_il_sha256: method.body.normalized_il_sha256,
|
||||
},
|
||||
],
|
||||
application_graph: {
|
||||
expected_node_kinds: [
|
||||
"artifact",
|
||||
"managed-assembly",
|
||||
"managed-module",
|
||||
"managed-type",
|
||||
"managed-method",
|
||||
],
|
||||
feature_traces: [
|
||||
{
|
||||
label: "trace pinned method by name",
|
||||
method_token: method.token,
|
||||
seed: "PinnedSemanticSlice",
|
||||
match: "exact",
|
||||
min_matched_seeds: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
join(context.workspace, "source-owned-managed-app-manifest.json"),
|
||||
);
|
||||
return {
|
||||
verified: true,
|
||||
assertions: summary.assertions,
|
||||
methods: summary.methods.length,
|
||||
applicationGraph: summary.application_graph ?? null,
|
||||
target: summary.target,
|
||||
};
|
||||
}
|
||||
|
||||
async function runOptionalManagedAppManifest(context) {
|
||||
const manifestPath = process.env.REA_MANAGED_APP_MANIFEST_PATH;
|
||||
if (manifestPath === undefined) return null;
|
||||
if (manifestPath.trim().length === 0)
|
||||
throw new Error("REA_MANAGED_APP_MANIFEST_PATH is set but empty");
|
||||
const resolvedManifestPath = resolve(process.cwd(), manifestPath);
|
||||
const text = await readFile(resolvedManifestPath, "utf8");
|
||||
let manifest;
|
||||
try {
|
||||
manifest = JSON.parse(text);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(
|
||||
`managed app manifest ${resolvedManifestPath} is not valid JSON: ${message}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
configured: true,
|
||||
...(await context.verifyManagedAppManifest(manifest, resolvedManifestPath)),
|
||||
};
|
||||
}
|
||||
|
||||
async function runOptionalIlspyOracle(context) {
|
||||
const ilspyPath = process.env.REA_ILSPY_CMD_PATH;
|
||||
if (ilspyPath === undefined) return null;
|
||||
ensureIlspy(
|
||||
ilspyPath.trim().length > 0,
|
||||
"REA_ILSPY_CMD_PATH is set but empty",
|
||||
);
|
||||
ensureIlspy(
|
||||
isAbsolute(ilspyPath),
|
||||
"REA_ILSPY_CMD_PATH must be an absolute path",
|
||||
);
|
||||
await ensureExecutable(ilspyPath);
|
||||
const versionOutput = await runIlspy(ilspyPath, ["--version"], 64 * 1024);
|
||||
const version = ilspyVersion(versionOutput);
|
||||
const executableSha256 = context.sha256(await readFile(ilspyPath));
|
||||
const sample = await context.fixture("ilspy-oracle.exe", {
|
||||
methodName: "PinnedSemanticSlice",
|
||||
});
|
||||
const artifact = inspectManagedArtifactBytes(
|
||||
sample.bytes,
|
||||
sample.target,
|
||||
context.inspectionLimits,
|
||||
);
|
||||
const members = inspectManagedMembersBytes(
|
||||
sample.bytes,
|
||||
sample.target,
|
||||
context.memberLimits,
|
||||
);
|
||||
const method = members.methods[0];
|
||||
ensureIlspy(method !== undefined, "source-owned fixture has no method");
|
||||
const listOutput = await runIlspy(
|
||||
ilspyPath,
|
||||
["--disable-updatecheck", "-l", "c", sample.path],
|
||||
256 * 1024,
|
||||
);
|
||||
ensureIlspy(
|
||||
listOutput.includes("Class Fixture.Program"),
|
||||
"ilspycmd class listing did not include Fixture.Program",
|
||||
);
|
||||
const csharp = await runIlspy(
|
||||
ilspyPath,
|
||||
["--disable-updatecheck", "--type", "Fixture.Program", sample.path],
|
||||
256 * 1024,
|
||||
);
|
||||
ensureIlspy(
|
||||
csharp.includes("PinnedSemanticSlice"),
|
||||
"ilspycmd C# output did not include the pinned method name",
|
||||
);
|
||||
ensureIlspy(
|
||||
csharp.length <= 65_536,
|
||||
"ilspycmd C# output exceeded the managed reconstruction import bound",
|
||||
);
|
||||
const reconstructionImport = importIlspyReconstruction({
|
||||
context,
|
||||
sample,
|
||||
method,
|
||||
members,
|
||||
version,
|
||||
executableSha256,
|
||||
csharp,
|
||||
});
|
||||
const imported = reconstructionImport.value.normalized_result;
|
||||
return {
|
||||
env: "REA_ILSPY_CMD_PATH",
|
||||
configured: true,
|
||||
version,
|
||||
executable_sha256: executableSha256,
|
||||
fixture: {
|
||||
file_name: basename(sample.path),
|
||||
sha256: sample.target.sha256,
|
||||
mvid: artifact.module?.mvid ?? null,
|
||||
assembly_name: artifact.assembly?.name ?? null,
|
||||
method: {
|
||||
token: method.token,
|
||||
declaring_type: method.declaring_type,
|
||||
name: method.name,
|
||||
signature_sha256: method.signature.raw_sha256,
|
||||
il_size: method.body.il_size,
|
||||
normalized_il_sha256: method.body.normalized_il_sha256,
|
||||
},
|
||||
},
|
||||
output: {
|
||||
class_listing_sha256: context.sha256(Buffer.from(listOutput)),
|
||||
decompiled_csharp_sha256: context.sha256(Buffer.from(csharp)),
|
||||
decompiled_csharp_bytes: Buffer.byteLength(csharp),
|
||||
imported_evidence_id: reconstructionImport.value.evidence_id,
|
||||
reconstruction_id: imported.reconstruction_id,
|
||||
canonical_observation:
|
||||
imported.methods[0]?.validation.canonical_observation ?? null,
|
||||
confidence_floor:
|
||||
imported.methods[0]?.validation.confidence_floor ?? null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function importIlspyReconstruction({
|
||||
context,
|
||||
sample,
|
||||
method,
|
||||
members,
|
||||
version,
|
||||
executableSha256,
|
||||
csharp,
|
||||
}) {
|
||||
const memberEvidence = createEvidence(
|
||||
sample.target,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
{
|
||||
operation: "inspect_managed_members",
|
||||
parameters: context.memberLimits,
|
||||
result: members,
|
||||
rawResult: null,
|
||||
limitations: members.limitations,
|
||||
locations: [{ kind: "artifact-path", path: sample.target.path }],
|
||||
},
|
||||
);
|
||||
const reconstructionImport = importManagedReconstructionEvidence({
|
||||
static_members: memberEvidence,
|
||||
decompiler: {
|
||||
name: "ilspycmd",
|
||||
version,
|
||||
family: "ilspy",
|
||||
executable_sha256: executableSha256,
|
||||
options: ["--disable-updatecheck", "--type", "Fixture.Program"],
|
||||
},
|
||||
methods: [
|
||||
{
|
||||
token: method.token,
|
||||
signature_sha256: method.signature.raw_sha256,
|
||||
normalized_il_sha256: method.body.normalized_il_sha256,
|
||||
reconstruction: {
|
||||
kind: "decompiled-csharp",
|
||||
language: "csharp",
|
||||
text: csharp,
|
||||
},
|
||||
},
|
||||
],
|
||||
notes: [
|
||||
"source-owned real ilspycmd oracle; output is imported as reconstruction inference",
|
||||
],
|
||||
});
|
||||
ensureIlspy(reconstructionImport.ok, "managed reconstruction import failed");
|
||||
const imported = reconstructionImport.value.normalized_result;
|
||||
ensureIlspy(
|
||||
imported.summary.decompiled_csharp_methods === 1,
|
||||
"managed reconstruction import did not record one decompiled C# method",
|
||||
);
|
||||
return reconstructionImport;
|
||||
}
|
||||
|
||||
async function ensureExecutable(path) {
|
||||
try {
|
||||
await access(path, constants.X_OK);
|
||||
} catch {
|
||||
throw new Error(`managed ILSpy oracle failed: ${path} is not executable`);
|
||||
}
|
||||
}
|
||||
|
||||
async function runIlspy(path, args, maxBuffer) {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(path, args, {
|
||||
timeout: 30_000,
|
||||
maxBuffer,
|
||||
env: {
|
||||
...process.env,
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: "1",
|
||||
},
|
||||
});
|
||||
return stdout;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`managed ILSpy oracle failed: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
function ilspyVersion(output) {
|
||||
const version = output
|
||||
.split(/\r?\n/u)
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.startsWith("ilspycmd:"));
|
||||
ensureIlspy(
|
||||
version !== undefined,
|
||||
"ilspycmd --version did not identify ilspycmd",
|
||||
);
|
||||
return version;
|
||||
}
|
||||
|
||||
function ensureIlspy(condition, message) {
|
||||
if (!condition) throw new Error(`managed ILSpy oracle failed: ${message}`);
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { parseBinaryTarget } from "../../dist/application/BinaryTargetResolver.js";
|
||||
import { buildManagedPeFixture } from "./managed-pe-fixture.mjs";
|
||||
import { createManagedConformanceOracleSupport } from "./managed-conformance-oracles.mjs";
|
||||
|
||||
export const createManagedConformanceSupport = (context) => {
|
||||
const fixtureBytes = async (name, bytes) => {
|
||||
const path = join(context.workspace, name);
|
||||
await writeFile(path, bytes);
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
return { bytes, path, target: parsed.value };
|
||||
};
|
||||
const fixture = (name, options) =>
|
||||
fixtureBytes(name, buildManagedPeFixture(options));
|
||||
const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
||||
const appManifestInspectionLimits = {
|
||||
...context.inspectionLimits,
|
||||
maxMetadataBytes: 64 * 1024 * 1024,
|
||||
maxTableRows: 250_000,
|
||||
maxHeapItemBytes: 16 * 1024 * 1024,
|
||||
};
|
||||
const appManifestMemberLimits = {
|
||||
...context.memberLimits,
|
||||
typeLimit: 1,
|
||||
methodLimit: 1,
|
||||
fieldLimit: 1,
|
||||
memberRefLimit: 1,
|
||||
edgeLimit: 1,
|
||||
maxMetadataBytes: 64 * 1024 * 1024,
|
||||
maxTableRows: 250_000,
|
||||
maxHeapItemBytes: 16 * 1024 * 1024,
|
||||
maxMethodBodyBytes: 4 * 1024 * 1024,
|
||||
maxMethodInstructions: 20_000,
|
||||
};
|
||||
const base = {
|
||||
...context,
|
||||
fixture,
|
||||
fixtureBytes,
|
||||
sha256,
|
||||
appManifestInspectionLimits,
|
||||
appManifestMemberLimits,
|
||||
};
|
||||
return { ...base, ...createManagedConformanceOracleSupport(base) };
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
export interface ManagedPeFixtureMethod {
|
||||
readonly body?: Buffer;
|
||||
readonly flags?: number;
|
||||
readonly implFlags?: number;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
export interface ManagedPeFixtureOptions {
|
||||
readonly cliFlags?: number;
|
||||
readonly corruptMetadataSignature?: boolean;
|
||||
readonly fieldName?: string;
|
||||
readonly ilBody?: Buffer;
|
||||
readonly machine?: number;
|
||||
readonly metadataValidMaskExtra?: bigint;
|
||||
readonly methodImplFlags?: number;
|
||||
readonly methodName?: string;
|
||||
readonly methods?: readonly ManagedPeFixtureMethod[];
|
||||
readonly mvid?: Buffer;
|
||||
readonly pinvoke?: {
|
||||
readonly importName?: string;
|
||||
readonly mappingFlags?: number;
|
||||
readonly moduleName?: string;
|
||||
};
|
||||
readonly readyToRun?: boolean;
|
||||
readonly references?: readonly string[];
|
||||
readonly resourceData?: Buffer;
|
||||
readonly targetFramework?: string;
|
||||
readonly typeName?: string;
|
||||
readonly typeNamespace?: string;
|
||||
}
|
||||
|
||||
export const alternateMvid: Buffer;
|
||||
export function buildManagedPeFixture(
|
||||
options?: ManagedPeFixtureOptions,
|
||||
): Buffer;
|
||||
export function buildNativePeFixture(): Buffer;
|
||||
@@ -1,402 +0,0 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
|
||||
const DEFAULT_MVID = Buffer.from([
|
||||
0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0x77, 0x66, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
|
||||
0xdd, 0xee, 0xff,
|
||||
]);
|
||||
|
||||
const align4 = (value) => (value + 3) & ~3;
|
||||
const cString = (value) => Buffer.from(`${value}\0`, "utf8");
|
||||
|
||||
class StringHeap {
|
||||
#chunks = [Buffer.from([0])];
|
||||
#size = 1;
|
||||
|
||||
add(value) {
|
||||
if (value.length === 0) return 0;
|
||||
const index = this.#size;
|
||||
const chunk = cString(value);
|
||||
this.#chunks.push(chunk);
|
||||
this.#size += chunk.length;
|
||||
return index;
|
||||
}
|
||||
|
||||
toBuffer() {
|
||||
return Buffer.concat(this.#chunks);
|
||||
}
|
||||
}
|
||||
|
||||
class BlobHeap {
|
||||
#chunks = [Buffer.from([0])];
|
||||
#size = 1;
|
||||
|
||||
add(value) {
|
||||
if (value.length === 0) return 0;
|
||||
if (value.length > 0x7f)
|
||||
throw new RangeError("Managed PE fixture blob is too large");
|
||||
const index = this.#size;
|
||||
this.#chunks.push(Buffer.from([value.length]), value);
|
||||
this.#size += value.length + 1;
|
||||
return index;
|
||||
}
|
||||
|
||||
toBuffer() {
|
||||
return Buffer.concat(this.#chunks);
|
||||
}
|
||||
}
|
||||
|
||||
const u16 = (value) => {
|
||||
const bytes = Buffer.alloc(2);
|
||||
bytes.writeUInt16LE(value, 0);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const u32 = (value) => {
|
||||
const bytes = Buffer.alloc(4);
|
||||
bytes.writeUInt32LE(value, 0);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const guidHeap = (mvid = DEFAULT_MVID) => {
|
||||
if (mvid.length !== 16)
|
||||
throw new RangeError("Managed PE fixture MVID must be 16 bytes");
|
||||
return Buffer.from(mvid);
|
||||
};
|
||||
|
||||
const moduleRow = (name) =>
|
||||
Buffer.concat([u16(0), u16(name), u16(1), u16(0), u16(0)]);
|
||||
|
||||
const typeRefRow = (name, namespace) =>
|
||||
Buffer.concat([u16(0), u16(name), u16(namespace)]);
|
||||
|
||||
const typeDefRow = (name, namespace, fieldList, methodList) =>
|
||||
Buffer.concat([
|
||||
u32(0x0010_0001),
|
||||
u16(name),
|
||||
u16(namespace),
|
||||
u16((1 << 2) | 1),
|
||||
u16(fieldList),
|
||||
u16(methodList),
|
||||
]);
|
||||
|
||||
const fieldRow = (name, signature) =>
|
||||
Buffer.concat([u16(0x0001), u16(name), u16(signature)]);
|
||||
|
||||
const methodDefRow = ({
|
||||
flags = 0x0016,
|
||||
implFlags = 0,
|
||||
name,
|
||||
rva,
|
||||
signature,
|
||||
}) =>
|
||||
Buffer.concat([
|
||||
u32(rva),
|
||||
u16(implFlags),
|
||||
u16(flags),
|
||||
u16(name),
|
||||
u16(signature),
|
||||
u16(0),
|
||||
]);
|
||||
|
||||
const memberRefRow = (name, signature) =>
|
||||
Buffer.concat([u16((1 << 3) | 1), u16(name), u16(signature)]);
|
||||
|
||||
const moduleRefRow = (name) => Buffer.concat([u16(name)]);
|
||||
|
||||
const implMapRow = (importName, importScope, mappingFlags, memberRow = 1) =>
|
||||
Buffer.concat([
|
||||
u16(mappingFlags),
|
||||
u16((memberRow << 1) | 1),
|
||||
u16(importName),
|
||||
u16(importScope),
|
||||
]);
|
||||
|
||||
const assemblyRow = (name) =>
|
||||
Buffer.concat([
|
||||
u32(0x0000_8004),
|
||||
u16(1),
|
||||
u16(2),
|
||||
u16(3),
|
||||
u16(4),
|
||||
u32(0),
|
||||
u16(0),
|
||||
u16(name),
|
||||
u16(0),
|
||||
]);
|
||||
|
||||
const assemblyRefRow = (name, keyOrToken) =>
|
||||
Buffer.concat([
|
||||
u16(8),
|
||||
u16(0),
|
||||
u16(0),
|
||||
u16(0),
|
||||
u32(0),
|
||||
u16(keyOrToken),
|
||||
u16(name),
|
||||
u16(0),
|
||||
u16(0),
|
||||
]);
|
||||
|
||||
const customAttributeRow = (value) =>
|
||||
Buffer.concat([u16((1 << 5) | 14), u16((1 << 3) | 3), u16(value)]);
|
||||
|
||||
const manifestResourceRow = (name) =>
|
||||
Buffer.concat([u32(0), u32(2), u16(name), u16(0)]);
|
||||
|
||||
const fixedStringAttributeBlob = (value) => {
|
||||
const bytes = Buffer.from(textEncoder.encode(value));
|
||||
if (bytes.length > 0x7f)
|
||||
throw new RangeError("Managed PE fixture target framework is too long");
|
||||
return Buffer.concat([Buffer.from([1, 0, bytes.length]), bytes, u16(0)]);
|
||||
};
|
||||
|
||||
const metadataStreamHeader = (relativeOffset, size, name) => {
|
||||
const named = cString(name);
|
||||
const paddedName = Buffer.alloc(align4(named.length));
|
||||
named.copy(paddedName);
|
||||
return Buffer.concat([u32(relativeOffset), u32(size), paddedName]);
|
||||
};
|
||||
|
||||
const metadataRoot = (tables, strings, guid, blob) => {
|
||||
const version = Buffer.from("v4.0.30319\0\0", "utf8");
|
||||
const header = Buffer.concat([
|
||||
u32(0x424a_5342),
|
||||
u16(1),
|
||||
u16(1),
|
||||
u32(0),
|
||||
u32(version.length),
|
||||
version,
|
||||
u16(0),
|
||||
u16(4),
|
||||
]);
|
||||
const streamHeaderSize =
|
||||
metadataStreamHeader(0, 0, "#~").length +
|
||||
metadataStreamHeader(0, 0, "#Strings").length +
|
||||
metadataStreamHeader(0, 0, "#GUID").length +
|
||||
metadataStreamHeader(0, 0, "#Blob").length;
|
||||
let offset = align4(header.length + streamHeaderSize);
|
||||
const tablesOffset = offset;
|
||||
offset = align4(offset + tables.length);
|
||||
const stringsOffset = offset;
|
||||
offset = align4(offset + strings.length);
|
||||
const guidOffset = offset;
|
||||
offset = align4(offset + guid.length);
|
||||
const blobOffset = offset;
|
||||
const headers = Buffer.concat([
|
||||
metadataStreamHeader(tablesOffset, tables.length, "#~"),
|
||||
metadataStreamHeader(stringsOffset, strings.length, "#Strings"),
|
||||
metadataStreamHeader(guidOffset, guid.length, "#GUID"),
|
||||
metadataStreamHeader(blobOffset, blob.length, "#Blob"),
|
||||
]);
|
||||
const root = Buffer.alloc(align4(blobOffset + blob.length));
|
||||
header.copy(root, 0);
|
||||
headers.copy(root, header.length);
|
||||
tables.copy(root, tablesOffset);
|
||||
strings.copy(root, stringsOffset);
|
||||
guid.copy(root, guidOffset);
|
||||
blob.copy(root, blobOffset);
|
||||
return root;
|
||||
};
|
||||
|
||||
const tablesStream = (rows, extraValidMask = 0n) => {
|
||||
let valid = extraValidMask;
|
||||
for (const table of rows.keys()) valid |= 1n << BigInt(table);
|
||||
const header = Buffer.alloc(24);
|
||||
header.writeUInt8(2, 4);
|
||||
header.writeUInt8(1, 7);
|
||||
header.writeBigUInt64LE(valid, 8);
|
||||
const counts = [];
|
||||
for (let index = 0; index <= 44; index += 1) {
|
||||
const tableRows = rows.get(index);
|
||||
if (tableRows !== undefined) counts.push(u32(tableRows.length));
|
||||
}
|
||||
const data = [];
|
||||
for (let index = 0; index <= 44; index += 1) {
|
||||
const tableRows = rows.get(index);
|
||||
if (tableRows !== undefined) data.push(...tableRows);
|
||||
}
|
||||
return Buffer.concat([header, ...counts, ...data]);
|
||||
};
|
||||
|
||||
const defaultIlBody = Buffer.from([
|
||||
0x32, 0x02, 0x7b, 0x01, 0x00, 0x00, 0x04, 0x28, 0x01, 0x00, 0x00, 0x0a, 0x2a,
|
||||
]);
|
||||
|
||||
const retOnlyIlBody = Buffer.from([0x2a]);
|
||||
|
||||
export const alternateMvid = Buffer.from([
|
||||
0xde, 0xad, 0xbe, 0xef, 0x44, 0x33, 0x66, 0x55, 0xaa, 0xbb, 0xcc, 0xdd, 0xee,
|
||||
0xff, 0x11, 0x22,
|
||||
]);
|
||||
|
||||
/** Build a source-owned PE/CLI fixture without committing compiled binaries. */
|
||||
const managedFixtureMethods = (options) =>
|
||||
options.methods ?? [
|
||||
{
|
||||
name: options.methodName ?? "Main",
|
||||
body: options.ilBody ?? defaultIlBody,
|
||||
flags: options.pinvoke === undefined ? 0x0016 : 0x2016,
|
||||
implFlags: options.methodImplFlags ?? 0,
|
||||
},
|
||||
];
|
||||
|
||||
const buildManagedMetadata = (options, methods) => {
|
||||
const strings = new StringHeap();
|
||||
const blobs = new BlobHeap();
|
||||
const stringsForMethods = methods.map((method) => strings.add(method.name));
|
||||
const moduleName = strings.add("Fixture.dll");
|
||||
const assemblyName = strings.add("Fixture.Managed");
|
||||
const attributeName = strings.add("TargetFrameworkAttribute");
|
||||
const attributeNamespace = strings.add("System.Runtime.Versioning");
|
||||
const constructorName = strings.add(".ctor");
|
||||
const typeName = strings.add(options.typeName ?? "Program");
|
||||
const typeNamespace = strings.add(options.typeNamespace ?? "Fixture");
|
||||
const fieldName = strings.add(options.fieldName ?? "counter");
|
||||
const pinvokeModuleName =
|
||||
options.pinvoke === undefined
|
||||
? null
|
||||
: strings.add(options.pinvoke.moduleName ?? "user32.dll");
|
||||
const pinvokeImportName =
|
||||
options.pinvoke === undefined
|
||||
? null
|
||||
: strings.add(options.pinvoke.importName ?? "MessageBoxW");
|
||||
const resourceName = strings.add("Fixture.resources");
|
||||
const referenceNames = options.references ?? ["System.Runtime"];
|
||||
const referenceStringIndexes = referenceNames.map((name) =>
|
||||
strings.add(name),
|
||||
);
|
||||
const tokenBlob = blobs.add(Buffer.from("b77a5c561934e089", "hex"));
|
||||
const fieldSignature = blobs.add(Buffer.from([0x06, 0x08]));
|
||||
const methodSignature = blobs.add(Buffer.from([0x00, 0x00, 0x01]));
|
||||
const constructorSignature = blobs.add(Buffer.from([0x20, 0x01, 0x01, 0x0e]));
|
||||
const attributeBlob = blobs.add(
|
||||
fixedStringAttributeBlob(
|
||||
options.targetFramework ?? ".NETCoreApp,Version=v8.0",
|
||||
),
|
||||
);
|
||||
const methodRows = methods.map((method, index) =>
|
||||
methodDefRow({
|
||||
name: stringsForMethods[index],
|
||||
signature: methodSignature,
|
||||
rva: method.rva ?? 0x2800 + index * 0x20,
|
||||
flags: method.flags ?? 0x0016,
|
||||
implFlags: method.implFlags ?? 0,
|
||||
}),
|
||||
);
|
||||
const rows = new Map([
|
||||
[0, [moduleRow(moduleName)]],
|
||||
[1, [typeRefRow(attributeName, attributeNamespace)]],
|
||||
[2, [typeDefRow(typeName, typeNamespace, 1, 1)]],
|
||||
[4, [fieldRow(fieldName, fieldSignature)]],
|
||||
[6, methodRows],
|
||||
[10, [memberRefRow(constructorName, constructorSignature)]],
|
||||
[12, [customAttributeRow(attributeBlob)]],
|
||||
...(pinvokeModuleName === null
|
||||
? []
|
||||
: [[26, [moduleRefRow(pinvokeModuleName)]]]),
|
||||
...(pinvokeImportName === null
|
||||
? []
|
||||
: [
|
||||
[
|
||||
28,
|
||||
[
|
||||
implMapRow(
|
||||
pinvokeImportName,
|
||||
1,
|
||||
options.pinvoke?.mappingFlags ?? 0x0344,
|
||||
options.pinvoke?.memberRow ?? 1,
|
||||
),
|
||||
],
|
||||
],
|
||||
]),
|
||||
[32, [assemblyRow(assemblyName)]],
|
||||
[35, referenceStringIndexes.map((name) => assemblyRefRow(name, tokenBlob))],
|
||||
[40, [manifestResourceRow(resourceName)]],
|
||||
]);
|
||||
const metadata = metadataRoot(
|
||||
tablesStream(rows, options.metadataValidMaskExtra ?? 0n),
|
||||
strings.toBuffer(),
|
||||
guidHeap(options.mvid),
|
||||
blobs.toBuffer(),
|
||||
);
|
||||
if (options.corruptMetadataSignature === true) metadata.writeUInt32LE(0, 0);
|
||||
return metadata;
|
||||
};
|
||||
|
||||
const buildManagedImage = (options, methods, metadata) => {
|
||||
const resourceData = options.resourceData ?? Buffer.from("resource-data");
|
||||
const resourceDirectory = Buffer.concat([
|
||||
u32(resourceData.length),
|
||||
resourceData,
|
||||
]);
|
||||
const image = Buffer.alloc(0x1000);
|
||||
image.write("MZ", 0, "ascii");
|
||||
image.writeUInt32LE(0x80, 0x3c);
|
||||
image.writeUInt32LE(0x0000_4550, 0x80);
|
||||
const coff = 0x84;
|
||||
const machine = options.machine ?? 0x014c;
|
||||
const pe32Plus = machine === 0x8664 || machine === 0xaa64;
|
||||
const optionalSize = pe32Plus ? 0x00f0 : 0x00e0;
|
||||
const directoryOffset = pe32Plus ? 112 : 96;
|
||||
image.writeUInt16LE(machine, coff);
|
||||
image.writeUInt16LE(1, coff + 2);
|
||||
image.writeUInt16LE(optionalSize, coff + 16);
|
||||
image.writeUInt16LE(0x0102, coff + 18);
|
||||
const optional = coff + 20;
|
||||
image.writeUInt16LE(pe32Plus ? 0x020b : 0x010b, optional);
|
||||
image.writeUInt32LE(0x2000, optional + 20);
|
||||
if (pe32Plus) image.writeBigUInt64LE(0x0040_0000n, optional + 24);
|
||||
else image.writeUInt32LE(0x0040_0000, optional + 28);
|
||||
image.writeUInt32LE(0x1000, optional + 32);
|
||||
image.writeUInt32LE(0x200, optional + 36);
|
||||
image.writeUInt32LE(0x3000, optional + 56);
|
||||
image.writeUInt32LE(0x200, optional + 60);
|
||||
image.writeUInt32LE(16, optional + directoryOffset - 4);
|
||||
image.writeUInt32LE(0x2000, optional + directoryOffset + 14 * 8);
|
||||
image.writeUInt32LE(72, optional + directoryOffset + 14 * 8 + 4);
|
||||
const section = optional + optionalSize;
|
||||
image.write(".text\0\0\0", section, "ascii");
|
||||
image.writeUInt32LE(0x1000, section + 8);
|
||||
image.writeUInt32LE(0x2000, section + 12);
|
||||
image.writeUInt32LE(0x0e00, section + 16);
|
||||
image.writeUInt32LE(0x0200, section + 20);
|
||||
image.writeUInt32LE(0x6000_0020, section + 36);
|
||||
const cli = 0x0200;
|
||||
image.writeUInt32LE(72, cli);
|
||||
image.writeUInt16LE(2, cli + 4);
|
||||
image.writeUInt16LE(5, cli + 6);
|
||||
image.writeUInt32LE(0x2100, cli + 8);
|
||||
image.writeUInt32LE(metadata.length, cli + 12);
|
||||
image.writeUInt32LE(options.cliFlags ?? 1, cli + 16);
|
||||
image.writeUInt32LE(0x0600_0001, cli + 20);
|
||||
image.writeUInt32LE(0x2600, cli + 24);
|
||||
image.writeUInt32LE(resourceDirectory.length, cli + 28);
|
||||
if (options.readyToRun === true) {
|
||||
image.writeUInt32LE(0x2700, cli + 64);
|
||||
image.writeUInt32LE(4, cli + 68);
|
||||
image.write("RTR\0", 0x0900, "ascii");
|
||||
}
|
||||
methods.forEach((method, index) => {
|
||||
const offset = 0x0a00 + index * 0x20;
|
||||
(method.body ?? retOnlyIlBody).copy(image, offset);
|
||||
});
|
||||
metadata.copy(image, 0x0300);
|
||||
resourceDirectory.copy(image, 0x0800);
|
||||
return image;
|
||||
};
|
||||
|
||||
/** Build a source-owned PE/CLI fixture without committing compiled binaries. */
|
||||
export const buildManagedPeFixture = (options = {}) => {
|
||||
const methods = managedFixtureMethods(options);
|
||||
const metadata = buildManagedMetadata(options, methods);
|
||||
return buildManagedImage(options, methods, metadata);
|
||||
};
|
||||
export const buildNativePeFixture = () => {
|
||||
const image = buildManagedPeFixture();
|
||||
const cliDirectory = 0x84 + 20 + 96 + 14 * 8;
|
||||
image.writeUInt32LE(0, cliDirectory);
|
||||
image.writeUInt32LE(0, cliDirectory + 4);
|
||||
return image;
|
||||
};
|
||||
Reference in New Issue
Block a user