@exploitlens/verify 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/cli.js +1981 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +1919 -0
- package/package.json +59 -3
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1981 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
5
|
+
|
|
6
|
+
// ../verifier/src/safe-read.ts
|
|
7
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
8
|
+
import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2, sep as sep2 } from "node:path";
|
|
9
|
+
|
|
10
|
+
// ../trace-ir/src/errors.ts
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
var ERROR_CODES = [
|
|
13
|
+
"SCHEMA_VALIDATION",
|
|
14
|
+
"PATH_POLICY_VIOLATION",
|
|
15
|
+
"BASELINE_NOT_REPRODUCED",
|
|
16
|
+
"EXECUTION_TIMEOUT",
|
|
17
|
+
"PROCESS_NONZERO_EXIT",
|
|
18
|
+
"TOOLCHAIN_MISMATCH",
|
|
19
|
+
"ARTIFACT_MISSING",
|
|
20
|
+
"ARTIFACT_TAMPERED",
|
|
21
|
+
"GATE_INCONCLUSIVE",
|
|
22
|
+
"ALIGNMENT_AMBIGUOUS",
|
|
23
|
+
"INTERNAL"
|
|
24
|
+
];
|
|
25
|
+
var ErrorCodeSchema = z.enum(ERROR_CODES);
|
|
26
|
+
var ErrorDetailSchema = z.object({
|
|
27
|
+
code: ErrorCodeSchema,
|
|
28
|
+
message: z.string().min(1),
|
|
29
|
+
details: z.unknown().optional()
|
|
30
|
+
});
|
|
31
|
+
function ok(value) {
|
|
32
|
+
return { ok: true, value };
|
|
33
|
+
}
|
|
34
|
+
function err(code, message, details) {
|
|
35
|
+
return { ok: false, error: { code, message, details } };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// ../trace-ir/src/integrity.ts
|
|
39
|
+
var DEFAULT_TRACE_LIMITS = {
|
|
40
|
+
maxNodes: 5e4,
|
|
41
|
+
maxDepth: 1024,
|
|
42
|
+
maxChildrenPerNode: 4096
|
|
43
|
+
};
|
|
44
|
+
function validateTraceIntegrity(trace, limits = DEFAULT_TRACE_LIMITS) {
|
|
45
|
+
const { nodes, rootId } = trace;
|
|
46
|
+
if (nodes.length > limits.maxNodes) {
|
|
47
|
+
return err(
|
|
48
|
+
"SCHEMA_VALIDATION",
|
|
49
|
+
`trace has ${nodes.length} nodes, above the ${limits.maxNodes}-node limit`
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
const byId = /* @__PURE__ */ new Map();
|
|
53
|
+
for (const node of nodes) {
|
|
54
|
+
if (byId.has(node.id)) {
|
|
55
|
+
return err("SCHEMA_VALIDATION", `trace contains duplicate node id "${node.id}"`);
|
|
56
|
+
}
|
|
57
|
+
byId.set(node.id, node);
|
|
58
|
+
}
|
|
59
|
+
const claimedBy = /* @__PURE__ */ new Map();
|
|
60
|
+
for (const node of nodes) {
|
|
61
|
+
if (node.children.length > limits.maxChildrenPerNode) {
|
|
62
|
+
return err(
|
|
63
|
+
"SCHEMA_VALIDATION",
|
|
64
|
+
`node "${node.id}" has ${node.children.length} children, above the ${limits.maxChildrenPerNode}-child limit`
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
const seen = /* @__PURE__ */ new Set();
|
|
68
|
+
for (const childId of node.children) {
|
|
69
|
+
if (seen.has(childId)) {
|
|
70
|
+
return err(
|
|
71
|
+
"SCHEMA_VALIDATION",
|
|
72
|
+
`node "${node.id}" lists child "${childId}" more than once`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
seen.add(childId);
|
|
76
|
+
const child = byId.get(childId);
|
|
77
|
+
if (!child) {
|
|
78
|
+
return err(
|
|
79
|
+
"SCHEMA_VALIDATION",
|
|
80
|
+
`node "${node.id}" references child "${childId}", which is not present in the trace`
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
const existingParent = claimedBy.get(childId);
|
|
84
|
+
if (existingParent !== void 0) {
|
|
85
|
+
return err(
|
|
86
|
+
"SCHEMA_VALIDATION",
|
|
87
|
+
`node "${childId}" is listed as a child of both "${existingParent}" and "${node.id}"`
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
claimedBy.set(childId, node.id);
|
|
91
|
+
if (child.parentId !== node.id) {
|
|
92
|
+
return err(
|
|
93
|
+
"SCHEMA_VALIDATION",
|
|
94
|
+
`node "${childId}" is a child of "${node.id}" but its parentId is ${child.parentId === null ? "null" : `"${child.parentId}"`}`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const root = byId.get(rootId);
|
|
100
|
+
if (!root) {
|
|
101
|
+
return err("SCHEMA_VALIDATION", `rootId "${rootId}" is not present in the trace`);
|
|
102
|
+
}
|
|
103
|
+
if (root.parentId !== null) {
|
|
104
|
+
return err(
|
|
105
|
+
"SCHEMA_VALIDATION",
|
|
106
|
+
`root node "${rootId}" has parentId "${root.parentId}"; the root must have no parent`
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
for (const node of nodes) {
|
|
110
|
+
if (node.id === rootId) continue;
|
|
111
|
+
if (node.parentId === null) {
|
|
112
|
+
return err(
|
|
113
|
+
"SCHEMA_VALIDATION",
|
|
114
|
+
`node "${node.id}" has no parent but is not the root; a trace must have exactly one root`
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
if (!byId.has(node.parentId)) {
|
|
118
|
+
return err(
|
|
119
|
+
"SCHEMA_VALIDATION",
|
|
120
|
+
`node "${node.id}" references parent "${node.parentId}", which is not present in the trace`
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
if (claimedBy.get(node.id) !== node.parentId) {
|
|
124
|
+
return err(
|
|
125
|
+
"SCHEMA_VALIDATION",
|
|
126
|
+
`node "${node.id}" claims parent "${node.parentId}", but that node does not list it as a child`
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
let reachable = 0;
|
|
131
|
+
const stack = [{ id: rootId, depth: 1 }];
|
|
132
|
+
while (stack.length > 0) {
|
|
133
|
+
const entry = stack.pop();
|
|
134
|
+
if (!entry) break;
|
|
135
|
+
if (entry.depth > limits.maxDepth) {
|
|
136
|
+
return err(
|
|
137
|
+
"SCHEMA_VALIDATION",
|
|
138
|
+
`trace nests deeper than the ${limits.maxDepth}-level limit at node "${entry.id}"`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
reachable += 1;
|
|
142
|
+
const node = byId.get(entry.id);
|
|
143
|
+
if (!node) continue;
|
|
144
|
+
for (const childId of node.children) {
|
|
145
|
+
stack.push({ id: childId, depth: entry.depth + 1 });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (reachable !== nodes.length) {
|
|
149
|
+
return err(
|
|
150
|
+
"SCHEMA_VALIDATION",
|
|
151
|
+
`only ${reachable} of ${nodes.length} nodes are reachable from root "${rootId}"; the trace is not a single connected tree`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
return ok(void 0);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ../trace-ir/src/schema.ts
|
|
158
|
+
import { z as z2 } from "zod";
|
|
159
|
+
var SCHEMA_VERSION_1_0 = "1.0";
|
|
160
|
+
var HexAddressSchema = z2.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte 0x-prefixed hex address");
|
|
161
|
+
var HexHashSchema = z2.string().regex(/^0x[0-9a-fA-F]{64}$/, "must be a 32-byte 0x-prefixed hex hash");
|
|
162
|
+
var HexDataSchema = z2.string().regex(/^0x([0-9a-fA-F]{2})*$/, "must be even-length 0x-prefixed hex data");
|
|
163
|
+
var HexSelectorSchema = z2.string().regex(/^0x[0-9a-fA-F]{8}$/, "must be a 4-byte 0x-prefixed function selector");
|
|
164
|
+
var AmountSchema = z2.string().regex(/^\d+$/, "must be a base-10 integer string");
|
|
165
|
+
var GitCommitShaSchema = z2.string().regex(/^[0-9a-f]{40}$/i, "must be a 40-character git commit SHA");
|
|
166
|
+
var IsoTimestampSchema = z2.string().regex(
|
|
167
|
+
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/,
|
|
168
|
+
"must be a UTC ISO-8601 timestamp ending in Z"
|
|
169
|
+
);
|
|
170
|
+
var CallTypeSchema = z2.enum(["CALL", "STATICCALL", "DELEGATECALL", "CREATE", "CREATE2"]);
|
|
171
|
+
var ResultClassSchema = z2.enum(["return", "revert", "halt"]);
|
|
172
|
+
var StorageAccessSchema = z2.object({
|
|
173
|
+
slot: HexHashSchema,
|
|
174
|
+
value: HexHashSchema,
|
|
175
|
+
decoded: z2.string().optional()
|
|
176
|
+
});
|
|
177
|
+
var EventRefSchema = z2.object({
|
|
178
|
+
address: HexAddressSchema,
|
|
179
|
+
topics: z2.array(HexHashSchema).max(4),
|
|
180
|
+
data: HexDataSchema,
|
|
181
|
+
name: z2.string().optional()
|
|
182
|
+
});
|
|
183
|
+
var EffectRefSchema = z2.object({
|
|
184
|
+
id: z2.string().min(1),
|
|
185
|
+
type: z2.enum(["native-transfer", "token-transfer", "event", "storage-write"])
|
|
186
|
+
});
|
|
187
|
+
var CallResultSchema = z2.object({
|
|
188
|
+
class: ResultClassSchema,
|
|
189
|
+
label: z2.string().optional()
|
|
190
|
+
});
|
|
191
|
+
var CallNodeSchema = z2.object({
|
|
192
|
+
id: z2.string().min(1),
|
|
193
|
+
parentId: z2.string().min(1).nullable(),
|
|
194
|
+
depth: z2.number().int().nonnegative(),
|
|
195
|
+
contractRole: z2.string().optional(),
|
|
196
|
+
address: HexAddressSchema,
|
|
197
|
+
codeIdentity: z2.string().optional(),
|
|
198
|
+
selector: HexSelectorSchema.optional(),
|
|
199
|
+
functionName: z2.string().optional(),
|
|
200
|
+
callType: CallTypeSchema,
|
|
201
|
+
semanticPath: z2.string().min(1),
|
|
202
|
+
msgValue: AmountSchema,
|
|
203
|
+
effects: z2.array(EffectRefSchema),
|
|
204
|
+
storageReads: z2.array(StorageAccessSchema),
|
|
205
|
+
storageWrites: z2.array(StorageAccessSchema),
|
|
206
|
+
events: z2.array(EventRefSchema),
|
|
207
|
+
result: CallResultSchema,
|
|
208
|
+
children: z2.array(z2.string().min(1))
|
|
209
|
+
});
|
|
210
|
+
var TraceSchema = z2.object({
|
|
211
|
+
schemaVersion: z2.literal(SCHEMA_VERSION_1_0),
|
|
212
|
+
caseId: z2.string().min(1),
|
|
213
|
+
side: z2.enum(["vulnerable", "patched"]),
|
|
214
|
+
rootId: z2.string().min(1),
|
|
215
|
+
nodes: z2.array(CallNodeSchema).min(1)
|
|
216
|
+
}).refine((trace) => trace.nodes.some((node) => node.id === trace.rootId), {
|
|
217
|
+
message: "rootId must reference one of the trace's own nodes",
|
|
218
|
+
path: ["rootId"]
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
// ../manifest/src/schema.ts
|
|
222
|
+
import { z as z3 } from "zod";
|
|
223
|
+
var RepositorySchema = z3.object({
|
|
224
|
+
path: z3.string().min(1),
|
|
225
|
+
baselineCommit: GitCommitShaSchema,
|
|
226
|
+
patchedCommit: GitCommitShaSchema
|
|
227
|
+
});
|
|
228
|
+
var SolidityIdentifierSchema = z3.string().regex(
|
|
229
|
+
/^[A-Za-z_][A-Za-z0-9_]*$/,
|
|
230
|
+
"must be a Solidity function identifier (letters, digits and underscore; not starting with a digit) \u2014 regular expressions are not accepted"
|
|
231
|
+
).max(128, "must be at most 128 characters");
|
|
232
|
+
var FoundryConfigSchema = z3.object({
|
|
233
|
+
testPath: z3.string().min(1),
|
|
234
|
+
testSelector: SolidityIdentifierSchema,
|
|
235
|
+
controlSelector: SolidityIdentifierSchema,
|
|
236
|
+
profile: z3.string().optional(),
|
|
237
|
+
fuzzSeed: z3.string().min(1),
|
|
238
|
+
compilerVersion: z3.string().min(1),
|
|
239
|
+
evmVersion: z3.string().min(1)
|
|
240
|
+
});
|
|
241
|
+
var ForkConfigSchema = z3.object({
|
|
242
|
+
chainId: z3.number().int().positive(),
|
|
243
|
+
blockNumber: z3.number().int().nonnegative(),
|
|
244
|
+
rpcAlias: z3.string().min(1)
|
|
245
|
+
});
|
|
246
|
+
var ExpectedExploitSchema = z3.object({
|
|
247
|
+
effectType: z3.string().min(1),
|
|
248
|
+
asset: z3.string().optional(),
|
|
249
|
+
minimumDelta: z3.string().regex(/^\d+$/, "must be a base-10 integer string").optional(),
|
|
250
|
+
/**
|
|
251
|
+
* The attacker's own address. Kept for schema/view-model compatibility
|
|
252
|
+
* with `@exploitlens/ui-contracts`' `ExpectedExploitView` (ported from the
|
|
253
|
+
* Workbench branch) -- no evaluator in this package's `evaluate.ts`
|
|
254
|
+
* reads this field. `vaultSolvencyEvaluator` here infers beneficiary and
|
|
255
|
+
* counterparty from the effect flow itself rather than a declared
|
|
256
|
+
* address (see that module's doc for why). Optional and inert: a
|
|
257
|
+
* manifest may set it for documentation purposes, but nothing in the
|
|
258
|
+
* evaluation path depends on it being present or correct.
|
|
259
|
+
*/
|
|
260
|
+
attackerAddress: HexAddressSchema.optional()
|
|
261
|
+
});
|
|
262
|
+
var InvariantRefSchema = z3.object({
|
|
263
|
+
id: z3.string().min(1),
|
|
264
|
+
description: z3.string().min(1),
|
|
265
|
+
evaluator: z3.string().min(1)
|
|
266
|
+
});
|
|
267
|
+
var VariantConfigSchema = z3.object({
|
|
268
|
+
strategy: z3.string().min(1),
|
|
269
|
+
count: z3.number().int().positive(),
|
|
270
|
+
seed: z3.string().min(1)
|
|
271
|
+
});
|
|
272
|
+
var ExploitBundleSchema = z3.object({
|
|
273
|
+
schemaVersion: z3.literal("1.0"),
|
|
274
|
+
caseId: z3.string().min(1),
|
|
275
|
+
repository: RepositorySchema,
|
|
276
|
+
foundry: FoundryConfigSchema,
|
|
277
|
+
fork: ForkConfigSchema.optional(),
|
|
278
|
+
expectedExploit: ExpectedExploitSchema,
|
|
279
|
+
invariant: InvariantRefSchema,
|
|
280
|
+
variants: VariantConfigSchema
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
// ../manifest/src/canonical.ts
|
|
284
|
+
import { createHash } from "node:crypto";
|
|
285
|
+
function sortKeysDeep(value) {
|
|
286
|
+
if (Array.isArray(value)) {
|
|
287
|
+
return value.map(sortKeysDeep);
|
|
288
|
+
}
|
|
289
|
+
if (value !== null && typeof value === "object") {
|
|
290
|
+
const sorted = /* @__PURE__ */ Object.create(null);
|
|
291
|
+
for (const key of Object.keys(value).sort()) {
|
|
292
|
+
sorted[key] = sortKeysDeep(value[key]);
|
|
293
|
+
}
|
|
294
|
+
return sorted;
|
|
295
|
+
}
|
|
296
|
+
return value;
|
|
297
|
+
}
|
|
298
|
+
function canonicalizeJson(value) {
|
|
299
|
+
return JSON.stringify(sortKeysDeep(value));
|
|
300
|
+
}
|
|
301
|
+
function hashCanonicalJson(canonicalJson) {
|
|
302
|
+
return createHash("sha256").update(canonicalJson, "utf8").digest("hex");
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ../manifest/src/paths.ts
|
|
306
|
+
import { isAbsolute, posix, relative, resolve, sep } from "node:path";
|
|
307
|
+
var WINDOWS_DRIVE_PREFIX = /^[a-zA-Z]:[\\/]/;
|
|
308
|
+
function isSafeRelativePath(candidatePath) {
|
|
309
|
+
if (WINDOWS_DRIVE_PREFIX.test(candidatePath)) {
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
const normalized = posix.normalize(candidatePath.replace(/\\/g, "/"));
|
|
313
|
+
return normalized !== ".." && !normalized.startsWith("../") && !posix.isAbsolute(normalized);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// ../verifier/src/safe-read.ts
|
|
317
|
+
var DEFAULT_BUNDLE_LIMITS = {
|
|
318
|
+
maxFileBytes: 32 * 1024 * 1024,
|
|
319
|
+
maxTotalBytes: 256 * 1024 * 1024,
|
|
320
|
+
maxIndexedFiles: 1024,
|
|
321
|
+
maxJsonDepth: 64
|
|
322
|
+
};
|
|
323
|
+
var ReadBudget = class {
|
|
324
|
+
constructor(limits = DEFAULT_BUNDLE_LIMITS) {
|
|
325
|
+
this.limits = limits;
|
|
326
|
+
}
|
|
327
|
+
limits;
|
|
328
|
+
used = 0;
|
|
329
|
+
get limitsInUse() {
|
|
330
|
+
return this.limits;
|
|
331
|
+
}
|
|
332
|
+
/** Charges `bytes`, or reports that the bundle-wide budget is exhausted. */
|
|
333
|
+
spend(relPath, bytes) {
|
|
334
|
+
if (this.used + bytes > this.limits.maxTotalBytes) {
|
|
335
|
+
return err(
|
|
336
|
+
"SCHEMA_VALIDATION",
|
|
337
|
+
`reading "${relPath}" would exceed the ${this.limits.maxTotalBytes}-byte total bundle read limit`
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
this.used += bytes;
|
|
341
|
+
return ok(void 0);
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
async function resolveInsideBundle(bundleDir, relPath) {
|
|
345
|
+
if (!isSafeRelativePath(relPath)) {
|
|
346
|
+
return err(
|
|
347
|
+
"PATH_POLICY_VIOLATION",
|
|
348
|
+
`"${relPath}" is not a safe bundle-relative path (absolute, or escapes the bundle root)`
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
let realBundleDir;
|
|
352
|
+
try {
|
|
353
|
+
realBundleDir = await realpath(resolve2(bundleDir));
|
|
354
|
+
} catch (cause) {
|
|
355
|
+
return err("PATH_POLICY_VIOLATION", `bundle directory "${bundleDir}" could not be resolved`, {
|
|
356
|
+
cause: cause instanceof Error ? cause.message : String(cause)
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
const candidate = resolve2(realBundleDir, relPath);
|
|
360
|
+
let stats;
|
|
361
|
+
try {
|
|
362
|
+
stats = await lstat(candidate);
|
|
363
|
+
} catch (cause) {
|
|
364
|
+
return err("ARTIFACT_MISSING", `"${relPath}" could not be read from the bundle`, {
|
|
365
|
+
cause: cause instanceof Error ? cause.message : String(cause)
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
if (stats.isSymbolicLink()) {
|
|
369
|
+
return err(
|
|
370
|
+
"PATH_POLICY_VIOLATION",
|
|
371
|
+
`"${relPath}" is a symbolic link; an evidence bundle must contain only ordinary files`
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
if (!stats.isFile()) {
|
|
375
|
+
return err(
|
|
376
|
+
"PATH_POLICY_VIOLATION",
|
|
377
|
+
`"${relPath}" is not an ordinary file; an evidence bundle must contain only ordinary files`
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
let realCandidate;
|
|
381
|
+
try {
|
|
382
|
+
realCandidate = await realpath(candidate);
|
|
383
|
+
} catch (cause) {
|
|
384
|
+
return err("PATH_POLICY_VIOLATION", `"${relPath}" could not be resolved to a real path`, {
|
|
385
|
+
cause: cause instanceof Error ? cause.message : String(cause)
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
const rel = relative2(realBundleDir, realCandidate);
|
|
389
|
+
if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute2(rel)) {
|
|
390
|
+
return err(
|
|
391
|
+
"PATH_POLICY_VIOLATION",
|
|
392
|
+
`"${relPath}" resolves to "${realCandidate}", outside the bundle root`
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
return ok(realCandidate);
|
|
396
|
+
}
|
|
397
|
+
async function bundleFileExists(bundleDir, relPath) {
|
|
398
|
+
return (await resolveInsideBundle(bundleDir, relPath)).ok;
|
|
399
|
+
}
|
|
400
|
+
async function readBundleFile(bundleDir, relPath, budget) {
|
|
401
|
+
const resolved = await resolveInsideBundle(bundleDir, relPath);
|
|
402
|
+
if (!resolved.ok) return resolved;
|
|
403
|
+
const limits = budget.limitsInUse;
|
|
404
|
+
let sizeBytes;
|
|
405
|
+
try {
|
|
406
|
+
sizeBytes = (await lstat(resolved.value)).size;
|
|
407
|
+
} catch (cause) {
|
|
408
|
+
return err("ARTIFACT_MISSING", `"${relPath}" could not be measured`, {
|
|
409
|
+
cause: cause instanceof Error ? cause.message : String(cause)
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
if (sizeBytes > limits.maxFileBytes) {
|
|
413
|
+
return err(
|
|
414
|
+
"SCHEMA_VALIDATION",
|
|
415
|
+
`"${relPath}" is ${sizeBytes} bytes, above the ${limits.maxFileBytes}-byte per-artifact limit`
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
const charged = budget.spend(relPath, sizeBytes);
|
|
419
|
+
if (!charged.ok) return charged;
|
|
420
|
+
try {
|
|
421
|
+
return ok({ bytes: await readFile(resolved.value), path: resolved.value });
|
|
422
|
+
} catch (cause) {
|
|
423
|
+
return err("ARTIFACT_MISSING", `"${relPath}" could not be read`, {
|
|
424
|
+
cause: cause instanceof Error ? cause.message : String(cause)
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
function maxJsonDepth(text) {
|
|
429
|
+
const BACKSLASH = "\\";
|
|
430
|
+
let depth = 0;
|
|
431
|
+
let deepest = 0;
|
|
432
|
+
let inString = false;
|
|
433
|
+
let escaped = false;
|
|
434
|
+
for (const char of text) {
|
|
435
|
+
if (inString) {
|
|
436
|
+
if (escaped) escaped = false;
|
|
437
|
+
else if (char === BACKSLASH) escaped = true;
|
|
438
|
+
else if (char === '"') inString = false;
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
if (char === '"') inString = true;
|
|
442
|
+
else if (char === "{" || char === "[") {
|
|
443
|
+
depth += 1;
|
|
444
|
+
if (depth > deepest) deepest = depth;
|
|
445
|
+
} else if (char === "}" || char === "]") depth -= 1;
|
|
446
|
+
}
|
|
447
|
+
return deepest;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
// ../verifier/src/verify.ts
|
|
451
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
452
|
+
|
|
453
|
+
// ../aligner/src/schema.ts
|
|
454
|
+
import { z as z4 } from "zod";
|
|
455
|
+
var AlignmentRelationSchema = z4.enum([
|
|
456
|
+
"match",
|
|
457
|
+
"insert",
|
|
458
|
+
"delete",
|
|
459
|
+
"replace",
|
|
460
|
+
"ambiguous"
|
|
461
|
+
]);
|
|
462
|
+
var AlignmentRecordSchema = z4.object({
|
|
463
|
+
baselineNodeId: z4.string().min(1).optional(),
|
|
464
|
+
patchedNodeId: z4.string().min(1).optional(),
|
|
465
|
+
relation: AlignmentRelationSchema,
|
|
466
|
+
score: z4.number().min(0).max(1),
|
|
467
|
+
reasons: z4.array(z4.string().min(1))
|
|
468
|
+
}).refine((record) => record.baselineNodeId !== void 0 || record.patchedNodeId !== void 0, {
|
|
469
|
+
message: "an alignment record must reference at least one side",
|
|
470
|
+
path: ["baselineNodeId"]
|
|
471
|
+
});
|
|
472
|
+
var AlignmentFileSchema = z4.object({
|
|
473
|
+
schemaVersion: z4.literal("1.0"),
|
|
474
|
+
caseId: z4.string().min(1),
|
|
475
|
+
records: z4.array(AlignmentRecordSchema)
|
|
476
|
+
});
|
|
477
|
+
var DivergenceStatusSchema = z4.enum(["found", "inconclusive"]);
|
|
478
|
+
var DivergenceRecordSchema = z4.object({
|
|
479
|
+
status: DivergenceStatusSchema,
|
|
480
|
+
/** The earliest baseline node on the causal path to the prohibited effect, when known. */
|
|
481
|
+
baselineNodeId: z4.string().min(1).optional(),
|
|
482
|
+
/** Its aligned patched counterpart, when the seam is a paired node rather than a pure insertion/deletion. */
|
|
483
|
+
patchedNodeId: z4.string().min(1).optional(),
|
|
484
|
+
/** The `AlignmentRecord.relation` the seam was drawn from, when a seam was identified. */
|
|
485
|
+
alignmentRelation: AlignmentRelationSchema.optional(),
|
|
486
|
+
/** Baseline `effects.json` ids this divergence explains the absence/change of. */
|
|
487
|
+
explainedEffectIds: z4.array(z4.string().min(1)),
|
|
488
|
+
/** Patched-side `effects.json` ids observed at the seam's patched counterpart, if any. */
|
|
489
|
+
patchedEffectIds: z4.array(z4.string().min(1)),
|
|
490
|
+
reasons: z4.array(z4.string().min(1))
|
|
491
|
+
}).refine(
|
|
492
|
+
(record) => record.status === "inconclusive" || record.baselineNodeId !== void 0 || record.patchedNodeId !== void 0,
|
|
493
|
+
{
|
|
494
|
+
message: "a 'found' divergence must reference evidence on at least one side",
|
|
495
|
+
path: ["baselineNodeId"]
|
|
496
|
+
}
|
|
497
|
+
);
|
|
498
|
+
var DivergenceFileSchema = z4.object({
|
|
499
|
+
schemaVersion: z4.literal("1.0"),
|
|
500
|
+
caseId: z4.string().min(1),
|
|
501
|
+
divergence: DivergenceRecordSchema
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
// ../aligner/src/scoring.ts
|
|
505
|
+
var AMBIGUOUS_THRESHOLD = 0.4;
|
|
506
|
+
var GAP_COST = 1 - AMBIGUOUS_THRESHOLD;
|
|
507
|
+
|
|
508
|
+
// ../effects/src/schema.ts
|
|
509
|
+
import { z as z5 } from "zod";
|
|
510
|
+
var NativeTransferEffectSchema = z5.object({
|
|
511
|
+
type: z5.literal("native-transfer"),
|
|
512
|
+
id: z5.string().min(1),
|
|
513
|
+
from: HexAddressSchema,
|
|
514
|
+
to: HexAddressSchema,
|
|
515
|
+
amountWei: AmountSchema
|
|
516
|
+
});
|
|
517
|
+
var TokenStandardSchema = z5.enum(["ERC20", "ERC721", "ERC1155"]);
|
|
518
|
+
var TokenTransferEffectSchema = z5.object({
|
|
519
|
+
type: z5.literal("token-transfer"),
|
|
520
|
+
id: z5.string().min(1),
|
|
521
|
+
token: HexAddressSchema,
|
|
522
|
+
from: HexAddressSchema,
|
|
523
|
+
to: HexAddressSchema,
|
|
524
|
+
amount: AmountSchema,
|
|
525
|
+
standard: TokenStandardSchema
|
|
526
|
+
});
|
|
527
|
+
var EventEffectSchema = z5.object({
|
|
528
|
+
type: z5.literal("event"),
|
|
529
|
+
id: z5.string().min(1),
|
|
530
|
+
address: HexAddressSchema,
|
|
531
|
+
name: z5.string().optional(),
|
|
532
|
+
topics: z5.array(HexHashSchema).max(4),
|
|
533
|
+
data: HexDataSchema
|
|
534
|
+
});
|
|
535
|
+
var StorageWriteEffectSchema = z5.object({
|
|
536
|
+
type: z5.literal("storage-write"),
|
|
537
|
+
id: z5.string().min(1),
|
|
538
|
+
address: HexAddressSchema,
|
|
539
|
+
slot: HexHashSchema,
|
|
540
|
+
before: HexHashSchema,
|
|
541
|
+
after: HexHashSchema
|
|
542
|
+
});
|
|
543
|
+
var EffectRecordSchema = z5.discriminatedUnion("type", [
|
|
544
|
+
NativeTransferEffectSchema,
|
|
545
|
+
TokenTransferEffectSchema,
|
|
546
|
+
EventEffectSchema,
|
|
547
|
+
StorageWriteEffectSchema
|
|
548
|
+
]);
|
|
549
|
+
var EffectsFileSchema = z5.object({
|
|
550
|
+
schemaVersion: z5.literal("1.0"),
|
|
551
|
+
caseId: z5.string().min(1),
|
|
552
|
+
side: z5.enum(["vulnerable", "patched"]),
|
|
553
|
+
effects: z5.array(EffectRecordSchema)
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
// ../effects/src/join.ts
|
|
557
|
+
function parseEffectId(id) {
|
|
558
|
+
const parts = id.split(":");
|
|
559
|
+
if (parts.length < 3) return void 0;
|
|
560
|
+
const [stage, rawIndex] = parts;
|
|
561
|
+
if (stage === void 0 || stage.length === 0 || rawIndex === void 0) return void 0;
|
|
562
|
+
if (!/^\d+$/.test(rawIndex)) return void 0;
|
|
563
|
+
return { stage, nodeIndex: Number(rawIndex) };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// ../executor/src/foundry-config.ts
|
|
567
|
+
var MAX_FOUNDRY_CONFIG_BYTES = 256 * 1024;
|
|
568
|
+
|
|
569
|
+
// ../executor/src/kill.ts
|
|
570
|
+
var isWindows = process.platform === "win32";
|
|
571
|
+
|
|
572
|
+
// ../executor/src/process.ts
|
|
573
|
+
var DEFAULT_MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
|
|
574
|
+
var DEFAULT_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
575
|
+
|
|
576
|
+
// ../executor/src/workspace.ts
|
|
577
|
+
import { join, resolve as resolve3 } from "node:path";
|
|
578
|
+
import { fileURLToPath } from "node:url";
|
|
579
|
+
var monorepoRoot = resolve3(fileURLToPath(new URL(".", import.meta.url)), "..", "..", "..");
|
|
580
|
+
var DEFAULT_ALLOWED_REPOSITORY_ROOT = resolve3(
|
|
581
|
+
monorepoRoot,
|
|
582
|
+
"fixtures/demo-exploit-origin.git"
|
|
583
|
+
);
|
|
584
|
+
var STAX_ALLOWED_REPOSITORY_ROOT = resolve3(
|
|
585
|
+
monorepoRoot,
|
|
586
|
+
"fixtures/stax-lpstaking-origin.git"
|
|
587
|
+
);
|
|
588
|
+
|
|
589
|
+
// ../executor/src/coordinator.ts
|
|
590
|
+
function isEnvironmentEnforced(records) {
|
|
591
|
+
return records.length > 0 && records.every((record) => record.environmentEnforcement?.enforced === true);
|
|
592
|
+
}
|
|
593
|
+
function runPassed(record) {
|
|
594
|
+
return record.result.outcome.kind === "success";
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// ../invariants/src/schema.ts
|
|
598
|
+
import { z as z6 } from "zod";
|
|
599
|
+
var GateNameSchema = z6.enum([
|
|
600
|
+
"baseline",
|
|
601
|
+
"exact-replay",
|
|
602
|
+
"legitimate-control",
|
|
603
|
+
"neighborhood"
|
|
604
|
+
]);
|
|
605
|
+
var GateStatusSchema = z6.enum(["pass", "fail", "inconclusive"]);
|
|
606
|
+
var GateResultSchema = z6.object({
|
|
607
|
+
gate: GateNameSchema,
|
|
608
|
+
status: GateStatusSchema,
|
|
609
|
+
evidenceRefs: z6.array(z6.string().min(1)),
|
|
610
|
+
explanation: z6.string().min(1)
|
|
611
|
+
});
|
|
612
|
+
var GateReportSchema = z6.object({
|
|
613
|
+
schemaVersion: z6.literal("1.0"),
|
|
614
|
+
caseId: z6.string().min(1),
|
|
615
|
+
gates: z6.array(GateResultSchema).min(1)
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
// ../invariants/src/evaluate.ts
|
|
619
|
+
var SUPPORTED_EFFECT_TYPES = ["native-transfer"];
|
|
620
|
+
var TOKEN_SUPPORTED_EFFECT_TYPES = ["token-transfer"];
|
|
621
|
+
var NATIVE_ASSET_NAMES = ["ETH", "WEI", "NATIVE"];
|
|
622
|
+
var EXPLOIT_STAGE = "Execution";
|
|
623
|
+
function notViolated(reason) {
|
|
624
|
+
return { status: "not-violated", violatingEffectIds: [], reasons: [reason] };
|
|
625
|
+
}
|
|
626
|
+
function inconclusive(reason) {
|
|
627
|
+
return { status: "inconclusive", violatingEffectIds: [], reasons: [reason] };
|
|
628
|
+
}
|
|
629
|
+
function buildNativeFlowLedger(effects, stage) {
|
|
630
|
+
const netByAddress = /* @__PURE__ */ new Map();
|
|
631
|
+
const receivedInboundAnyStage = /* @__PURE__ */ new Set();
|
|
632
|
+
const sent = /* @__PURE__ */ new Map();
|
|
633
|
+
const effectsByAddress = /* @__PURE__ */ new Map();
|
|
634
|
+
let consideredEffects = 0;
|
|
635
|
+
const credit = (address, amount, effect) => {
|
|
636
|
+
netByAddress.set(address, (netByAddress.get(address) ?? 0n) + amount);
|
|
637
|
+
const list = effectsByAddress.get(address) ?? [];
|
|
638
|
+
list.push(effect);
|
|
639
|
+
effectsByAddress.set(address, list);
|
|
640
|
+
};
|
|
641
|
+
for (const effect of effects.effects) {
|
|
642
|
+
if (effect.type !== "native-transfer") continue;
|
|
643
|
+
const parsed = parseEffectId(effect.id);
|
|
644
|
+
if (!parsed) continue;
|
|
645
|
+
const amount = BigInt(effect.amountWei);
|
|
646
|
+
if (amount === 0n) continue;
|
|
647
|
+
const from = effect.from.toLowerCase();
|
|
648
|
+
const to = effect.to.toLowerCase();
|
|
649
|
+
receivedInboundAnyStage.add(to);
|
|
650
|
+
if (parsed.stage !== stage) continue;
|
|
651
|
+
consideredEffects += 1;
|
|
652
|
+
credit(to, amount, effect);
|
|
653
|
+
credit(from, -amount, effect);
|
|
654
|
+
const edges = sent.get(from) ?? /* @__PURE__ */ new Map();
|
|
655
|
+
edges.set(to, (edges.get(to) ?? 0n) + amount);
|
|
656
|
+
sent.set(from, edges);
|
|
657
|
+
}
|
|
658
|
+
return { netByAddress, receivedInboundAnyStage, sent, effectsByAddress, consideredEffects };
|
|
659
|
+
}
|
|
660
|
+
function buildTokenFlowLedger(effects, stage, scopedToken) {
|
|
661
|
+
const netByAddress = /* @__PURE__ */ new Map();
|
|
662
|
+
const receivedInboundAnyStage = /* @__PURE__ */ new Set();
|
|
663
|
+
const sent = /* @__PURE__ */ new Map();
|
|
664
|
+
const effectsByAddress = /* @__PURE__ */ new Map();
|
|
665
|
+
let consideredEffects = 0;
|
|
666
|
+
const credit = (address, amount, effect) => {
|
|
667
|
+
netByAddress.set(address, (netByAddress.get(address) ?? 0n) + amount);
|
|
668
|
+
const list = effectsByAddress.get(address) ?? [];
|
|
669
|
+
list.push(effect);
|
|
670
|
+
effectsByAddress.set(address, list);
|
|
671
|
+
};
|
|
672
|
+
for (const effect of effects.effects) {
|
|
673
|
+
if (effect.type !== "token-transfer") continue;
|
|
674
|
+
if (effect.standard !== "ERC20") continue;
|
|
675
|
+
if (scopedToken !== void 0 && effect.token.toLowerCase() !== scopedToken) continue;
|
|
676
|
+
const parsed = parseEffectId(effect.id);
|
|
677
|
+
if (!parsed) continue;
|
|
678
|
+
const amount = BigInt(effect.amount);
|
|
679
|
+
if (amount === 0n) continue;
|
|
680
|
+
const from = effect.from.toLowerCase();
|
|
681
|
+
const to = effect.to.toLowerCase();
|
|
682
|
+
receivedInboundAnyStage.add(to);
|
|
683
|
+
if (parsed.stage !== stage) continue;
|
|
684
|
+
consideredEffects += 1;
|
|
685
|
+
credit(to, amount, effect);
|
|
686
|
+
credit(from, -amount, effect);
|
|
687
|
+
const edges = sent.get(from) ?? /* @__PURE__ */ new Map();
|
|
688
|
+
edges.set(to, (edges.get(to) ?? 0n) + amount);
|
|
689
|
+
sent.set(from, edges);
|
|
690
|
+
}
|
|
691
|
+
return { netByAddress, receivedInboundAnyStage, sent, effectsByAddress, consideredEffects };
|
|
692
|
+
}
|
|
693
|
+
function pairwiseNet(ledger, a, b) {
|
|
694
|
+
const received = ledger.sent.get(b)?.get(a) ?? 0n;
|
|
695
|
+
const paid = ledger.sent.get(a)?.get(b) ?? 0n;
|
|
696
|
+
return received - paid;
|
|
697
|
+
}
|
|
698
|
+
var vaultSolvencyEvaluator = ({ expectedExploit, effects }) => {
|
|
699
|
+
if (!SUPPORTED_EFFECT_TYPES.includes(expectedExploit.effectType)) {
|
|
700
|
+
return inconclusive(
|
|
701
|
+
`this evaluator can only observe ${SUPPORTED_EFFECT_TYPES.join(", ")} effects, and the manifest declares "${expectedExploit.effectType}" \u2014 no verdict can be reached from the evidence this pipeline captures`
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
if (expectedExploit.asset !== void 0 && !NATIVE_ASSET_NAMES.includes(expectedExploit.asset.toUpperCase())) {
|
|
705
|
+
return inconclusive(
|
|
706
|
+
`expectedExploit.asset "${expectedExploit.asset}" is not the native asset, but expectedExploit.effectType is "native-transfer"; the manifest is internally inconsistent`
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
if (expectedExploit.minimumDelta === void 0) {
|
|
710
|
+
return inconclusive(
|
|
711
|
+
"expectedExploit.minimumDelta is required to decide whether a net gain constitutes a violation; without a threshold every nonzero transfer would qualify"
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
let minimumDelta;
|
|
715
|
+
try {
|
|
716
|
+
minimumDelta = BigInt(expectedExploit.minimumDelta);
|
|
717
|
+
} catch {
|
|
718
|
+
return inconclusive(
|
|
719
|
+
`expectedExploit.minimumDelta "${expectedExploit.minimumDelta}" is not a valid integer`
|
|
720
|
+
);
|
|
721
|
+
}
|
|
722
|
+
if (minimumDelta <= 0n) {
|
|
723
|
+
return inconclusive("expectedExploit.minimumDelta must be greater than zero");
|
|
724
|
+
}
|
|
725
|
+
const ledger = buildNativeFlowLedger(effects, EXPLOIT_STAGE);
|
|
726
|
+
if (ledger.consideredEffects === 0) {
|
|
727
|
+
return notViolated(
|
|
728
|
+
`no native-transfer effect occurred during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json (setup and deployment transfers are excluded by design)`
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
const counterparties = [...ledger.netByAddress.entries()].filter(([address, net]) => ledger.receivedInboundAnyStage.has(address) && -net >= minimumDelta).sort((a, b) => a[1] === b[1] ? a[0].localeCompare(b[0]) : a[1] > b[1] ? 1 : -1);
|
|
732
|
+
if (counterparties.length === 0) {
|
|
733
|
+
return notViolated(
|
|
734
|
+
`no account that received value during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json ended it down by ${minimumDelta} wei or more; nothing was drained from a party holding value (transfers into the run from the test harness are not losses)`
|
|
735
|
+
);
|
|
736
|
+
}
|
|
737
|
+
for (const [counterparty, counterpartyNet] of counterparties) {
|
|
738
|
+
const candidates = [...ledger.netByAddress.keys()].filter((address) => address !== counterparty).map((address) => [address, pairwiseNet(ledger, address, counterparty)]).filter(([, net]) => net >= minimumDelta).sort((a, b) => b[1] === a[1] ? a[0].localeCompare(b[0]) : b[1] > a[1] ? 1 : -1);
|
|
739
|
+
const top = candidates[0];
|
|
740
|
+
if (!top) continue;
|
|
741
|
+
const [beneficiary, netGain] = top;
|
|
742
|
+
const violatingEffectIds = (ledger.effectsByAddress.get(beneficiary) ?? []).filter((effect) => {
|
|
743
|
+
const from = effect.from.toLowerCase();
|
|
744
|
+
const to = effect.to.toLowerCase();
|
|
745
|
+
return from === counterparty && to === beneficiary || from === beneficiary && to === counterparty;
|
|
746
|
+
}).map((effect) => effect.id);
|
|
747
|
+
return {
|
|
748
|
+
status: "violated",
|
|
749
|
+
violatingEffectIds,
|
|
750
|
+
beneficiary,
|
|
751
|
+
counterparty,
|
|
752
|
+
netGainAmount: netGain.toString(10),
|
|
753
|
+
reasons: [
|
|
754
|
+
`account ${beneficiary} took ${netGain} wei more out of ${counterparty} than it put in during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json, at or above the declared minimumDelta of ${minimumDelta} wei; ${counterparty} ended the stage down ${-counterpartyNet} wei overall`
|
|
755
|
+
]
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
return notViolated(
|
|
759
|
+
`no account withdrew at least ${minimumDelta} wei more than it deposited from any party that lost value during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json`
|
|
760
|
+
);
|
|
761
|
+
};
|
|
762
|
+
var HEX_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
|
|
763
|
+
var tokenSolvencyEvaluator = ({ expectedExploit, effects }) => {
|
|
764
|
+
if (!TOKEN_SUPPORTED_EFFECT_TYPES.includes(expectedExploit.effectType)) {
|
|
765
|
+
return inconclusive(
|
|
766
|
+
`this evaluator can only observe ${TOKEN_SUPPORTED_EFFECT_TYPES.join(", ")} effects, and the manifest declares "${expectedExploit.effectType}" \u2014 no verdict can be reached from the evidence this pipeline captures`
|
|
767
|
+
);
|
|
768
|
+
}
|
|
769
|
+
let scopedToken;
|
|
770
|
+
if (expectedExploit.asset !== void 0) {
|
|
771
|
+
if (!HEX_ADDRESS_REGEX.test(expectedExploit.asset)) {
|
|
772
|
+
return inconclusive(
|
|
773
|
+
`expectedExploit.asset "${expectedExploit.asset}" is not a valid 20-byte 0x-prefixed token contract address; for token-transfer effects, asset must be a token address if specified`
|
|
774
|
+
);
|
|
775
|
+
}
|
|
776
|
+
scopedToken = expectedExploit.asset.toLowerCase();
|
|
777
|
+
}
|
|
778
|
+
if (expectedExploit.minimumDelta === void 0) {
|
|
779
|
+
return inconclusive(
|
|
780
|
+
"expectedExploit.minimumDelta is required to decide whether a net gain constitutes a violation; without a threshold every nonzero transfer would qualify"
|
|
781
|
+
);
|
|
782
|
+
}
|
|
783
|
+
let minimumDelta;
|
|
784
|
+
try {
|
|
785
|
+
minimumDelta = BigInt(expectedExploit.minimumDelta);
|
|
786
|
+
} catch {
|
|
787
|
+
return inconclusive(
|
|
788
|
+
`expectedExploit.minimumDelta "${expectedExploit.minimumDelta}" is not a valid integer`
|
|
789
|
+
);
|
|
790
|
+
}
|
|
791
|
+
if (minimumDelta <= 0n) {
|
|
792
|
+
return inconclusive("expectedExploit.minimumDelta must be greater than zero");
|
|
793
|
+
}
|
|
794
|
+
for (const effect of effects.effects) {
|
|
795
|
+
if (effect.type === "token-transfer" && effect.standard !== "ERC20") {
|
|
796
|
+
if (scopedToken === void 0 || effect.token.toLowerCase() === scopedToken) {
|
|
797
|
+
return inconclusive(
|
|
798
|
+
`token-solvency-evaluator only supports standard "ERC20" token transfers, but encountered standard "${effect.standard}" in effect "${effect.id}"`
|
|
799
|
+
);
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
const ledger = buildTokenFlowLedger(effects, EXPLOIT_STAGE, scopedToken);
|
|
804
|
+
if (ledger.consideredEffects === 0) {
|
|
805
|
+
return notViolated(
|
|
806
|
+
`no token-transfer effect occurred during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json (setup and deployment transfers are excluded by design)`
|
|
807
|
+
);
|
|
808
|
+
}
|
|
809
|
+
const counterparties = [...ledger.netByAddress.entries()].filter(([address, net]) => ledger.receivedInboundAnyStage.has(address) && -net >= minimumDelta).sort((a, b) => a[1] === b[1] ? a[0].localeCompare(b[0]) : a[1] > b[1] ? 1 : -1);
|
|
810
|
+
if (counterparties.length === 0) {
|
|
811
|
+
return notViolated(
|
|
812
|
+
`no account that received value during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json ended it down by ${minimumDelta} tokens or more; nothing was drained from a party holding value (transfers into the run from the test harness are not losses)`
|
|
813
|
+
);
|
|
814
|
+
}
|
|
815
|
+
for (const [counterparty, counterpartyNet] of counterparties) {
|
|
816
|
+
const candidates = [...ledger.netByAddress.keys()].filter((address) => address !== counterparty).map((address) => [address, pairwiseNet(ledger, address, counterparty)]).filter(([, net]) => net >= minimumDelta).sort((a, b) => b[1] === a[1] ? a[0].localeCompare(b[0]) : b[1] > a[1] ? 1 : -1);
|
|
817
|
+
const top = candidates[0];
|
|
818
|
+
if (!top) continue;
|
|
819
|
+
const [beneficiary, netGain] = top;
|
|
820
|
+
const violatingEffectIds = (ledger.effectsByAddress.get(beneficiary) ?? []).filter((effect) => {
|
|
821
|
+
const from = effect.from.toLowerCase();
|
|
822
|
+
const to = effect.to.toLowerCase();
|
|
823
|
+
return from === counterparty && to === beneficiary || from === beneficiary && to === counterparty;
|
|
824
|
+
}).map((effect) => effect.id);
|
|
825
|
+
return {
|
|
826
|
+
status: "violated",
|
|
827
|
+
violatingEffectIds,
|
|
828
|
+
beneficiary,
|
|
829
|
+
counterparty,
|
|
830
|
+
netGainAmount: netGain.toString(10),
|
|
831
|
+
reasons: [
|
|
832
|
+
`account ${beneficiary} took ${netGain} tokens more out of ${counterparty} than it put in during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json, at or above the declared minimumDelta of ${minimumDelta}; ${counterparty} ended the stage down ${-counterpartyNet} tokens overall`
|
|
833
|
+
]
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
return notViolated(
|
|
837
|
+
`no account withdrew at least ${minimumDelta} tokens more than it deposited from any party that lost value during the ${EXPLOIT_STAGE} stage of ${effects.side}/effects.json`
|
|
838
|
+
);
|
|
839
|
+
};
|
|
840
|
+
var BUILTIN_EVALUATORS = {
|
|
841
|
+
"vault-solvency-evaluator": vaultSolvencyEvaluator,
|
|
842
|
+
"token-solvency-evaluator": tokenSolvencyEvaluator
|
|
843
|
+
};
|
|
844
|
+
function evaluateInvariant(input, registry = BUILTIN_EVALUATORS) {
|
|
845
|
+
const evaluator = registry[input.invariant.evaluator];
|
|
846
|
+
if (!evaluator) {
|
|
847
|
+
return inconclusive(`unsupported invariant evaluator "${input.invariant.evaluator}"`);
|
|
848
|
+
}
|
|
849
|
+
return evaluator(input);
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// ../invariants/src/gates.ts
|
|
853
|
+
var NEIGHBORHOOD_MINIMUM_VALID_CANDIDATES = 6;
|
|
854
|
+
function computeBaselineGate(input) {
|
|
855
|
+
const evaluation = evaluateInvariant({
|
|
856
|
+
expectedExploit: input.expectedExploit,
|
|
857
|
+
invariant: input.invariant,
|
|
858
|
+
effects: input.vulnerableEffects
|
|
859
|
+
});
|
|
860
|
+
if (evaluation.status === "inconclusive") {
|
|
861
|
+
return {
|
|
862
|
+
gate: "baseline",
|
|
863
|
+
status: "inconclusive",
|
|
864
|
+
evidenceRefs: ["vulnerable/effects.json"],
|
|
865
|
+
explanation: `could not evaluate the declared invariant against the baseline run: ${evaluation.reasons.join("; ")}`
|
|
866
|
+
};
|
|
867
|
+
}
|
|
868
|
+
if (evaluation.status === "violated") {
|
|
869
|
+
return {
|
|
870
|
+
gate: "baseline",
|
|
871
|
+
status: "pass",
|
|
872
|
+
evidenceRefs: [
|
|
873
|
+
"vulnerable/effects.json",
|
|
874
|
+
...evaluation.violatingEffectIds.map((id) => `vulnerable/effects.json#${id}`)
|
|
875
|
+
],
|
|
876
|
+
explanation: "The vulnerable-side run reproduced the declared exploit effect."
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
return {
|
|
880
|
+
gate: "baseline",
|
|
881
|
+
status: "fail",
|
|
882
|
+
evidenceRefs: ["vulnerable/effects.json"],
|
|
883
|
+
explanation: "The vulnerable-side run did not reproduce the declared exploit effect; the run's premise is invalid."
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
function computeExactReplayGate(input) {
|
|
887
|
+
const evaluation = evaluateInvariant({
|
|
888
|
+
expectedExploit: input.expectedExploit,
|
|
889
|
+
invariant: input.invariant,
|
|
890
|
+
effects: input.patchedEffects
|
|
891
|
+
});
|
|
892
|
+
if (evaluation.status === "inconclusive") {
|
|
893
|
+
return {
|
|
894
|
+
gate: "exact-replay",
|
|
895
|
+
status: "inconclusive",
|
|
896
|
+
evidenceRefs: ["patched/effects.json"],
|
|
897
|
+
explanation: `could not evaluate the declared invariant against the patched exploit replay: ${evaluation.reasons.join("; ")}`
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
if (evaluation.status === "not-violated") {
|
|
901
|
+
return {
|
|
902
|
+
gate: "exact-replay",
|
|
903
|
+
status: "pass",
|
|
904
|
+
evidenceRefs: ["patched/effects.json"],
|
|
905
|
+
explanation: "The patched-side exploit replay did not reproduce the declared exploit effect."
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
return {
|
|
909
|
+
gate: "exact-replay",
|
|
910
|
+
status: "fail",
|
|
911
|
+
evidenceRefs: [
|
|
912
|
+
"patched/effects.json",
|
|
913
|
+
...evaluation.violatingEffectIds.map((id) => `patched/effects.json#${id}`)
|
|
914
|
+
],
|
|
915
|
+
explanation: "The patched-side exploit replay still reproduced the declared exploit effect."
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
function computeLegitimateControlGate(input) {
|
|
919
|
+
const record = input.patchedControlResult;
|
|
920
|
+
const evidenceRefs = ["patched/control-result.json"];
|
|
921
|
+
const outcome = record.testOutcome;
|
|
922
|
+
if (!outcome) {
|
|
923
|
+
return {
|
|
924
|
+
gate: "legitimate-control",
|
|
925
|
+
status: "inconclusive",
|
|
926
|
+
evidenceRefs,
|
|
927
|
+
explanation: `The patched legitimate-control run carries no execution evidence for selector "${record.testSelector}" (process outcome: "${record.result.outcome.kind}"), so it cannot be shown that the control test ran at all.`
|
|
928
|
+
};
|
|
929
|
+
}
|
|
930
|
+
if (outcome.matchedTests.length === 0) {
|
|
931
|
+
return {
|
|
932
|
+
gate: "legitimate-control",
|
|
933
|
+
status: "fail",
|
|
934
|
+
evidenceRefs,
|
|
935
|
+
explanation: `The patched legitimate-control run matched no test for selector "${record.testSelector}" in "${record.testPath}". forge exits zero when nothing matches, so this is a vacuous run, not a passing control path.`
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
if (!runPassed(record) || !outcome.allPassed) {
|
|
939
|
+
return {
|
|
940
|
+
gate: "legitimate-control",
|
|
941
|
+
status: "fail",
|
|
942
|
+
evidenceRefs,
|
|
943
|
+
explanation: `The patched legitimate-control run did not succeed (process outcome: "${record.result.outcome.kind}"; matched ${outcome.matchedTests.length} test(s) with status ${outcome.statuses.join(", ")}).`
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
return {
|
|
947
|
+
gate: "legitimate-control",
|
|
948
|
+
status: "pass",
|
|
949
|
+
evidenceRefs,
|
|
950
|
+
explanation: `The patched legitimate-control run executed ${outcome.matchedTests.join(", ")} for selector "${record.testSelector}" and every matched test passed.`
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
function computeNeighborhoodGate(ledger) {
|
|
954
|
+
if (!ledger) {
|
|
955
|
+
return {
|
|
956
|
+
gate: "neighborhood",
|
|
957
|
+
status: "inconclusive",
|
|
958
|
+
evidenceRefs: [],
|
|
959
|
+
explanation: "The variant neighborhood was not run for this case, so no neighborhood evidence exists. This is not a finding about the patch."
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
const evidenceRefs = ["variants/ledger.json"];
|
|
963
|
+
if (ledger.validDenominator < NEIGHBORHOOD_MINIMUM_VALID_CANDIDATES) {
|
|
964
|
+
return {
|
|
965
|
+
gate: "neighborhood",
|
|
966
|
+
status: "inconclusive",
|
|
967
|
+
evidenceRefs,
|
|
968
|
+
explanation: `only ${ledger.validDenominator} of ${ledger.results.length} candidate(s) validated on the vulnerable commit; at least ${NEIGHBORHOOD_MINIMUM_VALID_CANDIDATES} valid candidates are required before the neighborhood gate can report a definitive verdict.`
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
const validResults = ledger.results.filter((r) => r.vulnerableValidity === "valid");
|
|
972
|
+
const failed = validResults.filter((r) => r.patchedStatus === "fail");
|
|
973
|
+
const undetermined = validResults.filter(
|
|
974
|
+
(r) => r.patchedStatus === void 0 || r.patchedStatus === "inconclusive"
|
|
975
|
+
);
|
|
976
|
+
if (failed.length > 0) {
|
|
977
|
+
return {
|
|
978
|
+
gate: "neighborhood",
|
|
979
|
+
status: "fail",
|
|
980
|
+
evidenceRefs,
|
|
981
|
+
explanation: `${failed.length} of ${validResults.length} valid candidates still reproduced the declared exploit effect on the patched replay.`
|
|
982
|
+
};
|
|
983
|
+
}
|
|
984
|
+
if (undetermined.length > 0) {
|
|
985
|
+
return {
|
|
986
|
+
gate: "neighborhood",
|
|
987
|
+
status: "inconclusive",
|
|
988
|
+
evidenceRefs,
|
|
989
|
+
explanation: `${undetermined.length} of ${validResults.length} valid candidates have no definitive patched replay result yet (missing or inconclusive).`
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
return {
|
|
993
|
+
gate: "neighborhood",
|
|
994
|
+
status: "pass",
|
|
995
|
+
evidenceRefs,
|
|
996
|
+
explanation: `All ${validResults.length} valid candidates (of ${ledger.results.length} attempted) did not reproduce the declared exploit effect on the patched replay.`
|
|
997
|
+
};
|
|
998
|
+
}
|
|
999
|
+
function computeGateReport(input) {
|
|
1000
|
+
return {
|
|
1001
|
+
schemaVersion: "1.0",
|
|
1002
|
+
caseId: input.caseId,
|
|
1003
|
+
gates: [
|
|
1004
|
+
computeBaselineGate(input),
|
|
1005
|
+
computeExactReplayGate(input),
|
|
1006
|
+
computeLegitimateControlGate(input),
|
|
1007
|
+
computeNeighborhoodGate(input.variantLedger)
|
|
1008
|
+
]
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// ../receipt/src/digest.ts
|
|
1013
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1014
|
+
function entryLine(entry) {
|
|
1015
|
+
return `${entry.path}\0${entry.sha256.toLowerCase()}\0${entry.bytes}`;
|
|
1016
|
+
}
|
|
1017
|
+
function computeBundleDigest(entries) {
|
|
1018
|
+
const lines = entries.filter((entry) => entry.path !== "receipt.json").map(entryLine).sort();
|
|
1019
|
+
const hash = createHash2("sha256");
|
|
1020
|
+
for (const line of lines) {
|
|
1021
|
+
hash.update(line, "utf8");
|
|
1022
|
+
hash.update("\n", "utf8");
|
|
1023
|
+
}
|
|
1024
|
+
return `0x${hash.digest("hex")}`;
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
// ../receipt/src/schema.ts
|
|
1028
|
+
import { z as z7 } from "zod";
|
|
1029
|
+
var ReceiptScopeSchema = z7.object({
|
|
1030
|
+
claim: z7.string().min(1),
|
|
1031
|
+
limitations: z7.array(z7.string().min(1))
|
|
1032
|
+
});
|
|
1033
|
+
var ReceiptEnvironmentSchema = z7.object({
|
|
1034
|
+
/** `forge --version` output captured for the run. */
|
|
1035
|
+
toolchainVersion: z7.string().min(1),
|
|
1036
|
+
compilerVersion: z7.string().min(1),
|
|
1037
|
+
evmVersion: z7.string().min(1),
|
|
1038
|
+
fuzzSeed: z7.string().min(1),
|
|
1039
|
+
profile: z7.string().optional(),
|
|
1040
|
+
/** True when the checkout's own config was confirmed to pin the values above. */
|
|
1041
|
+
enforced: z7.boolean()
|
|
1042
|
+
});
|
|
1043
|
+
var ReceiptCausalDivergenceSchema = z7.object({
|
|
1044
|
+
status: z7.enum(["found", "inconclusive"]),
|
|
1045
|
+
baselineNodeId: z7.string().min(1).optional(),
|
|
1046
|
+
patchedNodeId: z7.string().min(1).optional()
|
|
1047
|
+
});
|
|
1048
|
+
var RECEIPT_SCHEMA_VERSION = "1.1";
|
|
1049
|
+
var ReceiptSchema = z7.object({
|
|
1050
|
+
schemaVersion: z7.literal(RECEIPT_SCHEMA_VERSION),
|
|
1051
|
+
caseId: z7.string().min(1),
|
|
1052
|
+
manifestHash: HexHashSchema,
|
|
1053
|
+
/**
|
|
1054
|
+
* Deterministic digest over the whole indexed artifact set (P6). Anchors
|
|
1055
|
+
* `artifact-index.json`, which cannot cover itself: without this, dropping
|
|
1056
|
+
* an entry from the index removed a file from hash coverage entirely and
|
|
1057
|
+
* verification still passed.
|
|
1058
|
+
*/
|
|
1059
|
+
bundleDigest: HexHashSchema,
|
|
1060
|
+
repository: z7.object({
|
|
1061
|
+
baselineCommit: GitCommitShaSchema,
|
|
1062
|
+
patchedCommit: GitCommitShaSchema
|
|
1063
|
+
}),
|
|
1064
|
+
environment: ReceiptEnvironmentSchema,
|
|
1065
|
+
gates: z7.array(GateResultSchema).min(1),
|
|
1066
|
+
variantDenominator: z7.number().int().nonnegative(),
|
|
1067
|
+
causalDivergence: ReceiptCausalDivergenceSchema,
|
|
1068
|
+
scope: ReceiptScopeSchema,
|
|
1069
|
+
evidenceRefs: z7.array(z7.string().min(1)).min(1),
|
|
1070
|
+
generatedAt: IsoTimestampSchema
|
|
1071
|
+
});
|
|
1072
|
+
var ArtifactEntrySchema = z7.object({
|
|
1073
|
+
path: z7.string().min(1),
|
|
1074
|
+
sha256: HexHashSchema,
|
|
1075
|
+
bytes: z7.number().int().nonnegative()
|
|
1076
|
+
});
|
|
1077
|
+
var ArtifactIndexSchema = z7.object({
|
|
1078
|
+
schemaVersion: z7.literal("1.0"),
|
|
1079
|
+
caseId: z7.string().min(1),
|
|
1080
|
+
generatedAt: IsoTimestampSchema,
|
|
1081
|
+
files: z7.array(ArtifactEntrySchema).min(1)
|
|
1082
|
+
});
|
|
1083
|
+
|
|
1084
|
+
// ../variants/src/schema.ts
|
|
1085
|
+
import { z as z8 } from "zod";
|
|
1086
|
+
var VariantStrategySchema = z8.enum([
|
|
1087
|
+
"amount",
|
|
1088
|
+
"repetition",
|
|
1089
|
+
"timing",
|
|
1090
|
+
"actor",
|
|
1091
|
+
"boundary"
|
|
1092
|
+
]);
|
|
1093
|
+
var VariantCandidateSchema = z8.object({
|
|
1094
|
+
id: z8.string().min(1),
|
|
1095
|
+
strategy: VariantStrategySchema,
|
|
1096
|
+
seed: z8.string().min(1),
|
|
1097
|
+
parameters: z8.record(z8.string(), z8.unknown())
|
|
1098
|
+
});
|
|
1099
|
+
var VariantValiditySchema = z8.enum(["valid", "invalid"]);
|
|
1100
|
+
var VariantResultSchema = z8.object({
|
|
1101
|
+
candidate: VariantCandidateSchema,
|
|
1102
|
+
vulnerableValidity: VariantValiditySchema,
|
|
1103
|
+
invalidReason: z8.string().min(1).optional(),
|
|
1104
|
+
patchedStatus: GateStatusSchema.optional()
|
|
1105
|
+
}).refine((result) => result.vulnerableValidity === "valid" || result.invalidReason !== void 0, {
|
|
1106
|
+
message: "an invalid candidate must record why it was excluded from the denominator",
|
|
1107
|
+
path: ["invalidReason"]
|
|
1108
|
+
});
|
|
1109
|
+
var VariantLedgerSchema = z8.object({
|
|
1110
|
+
schemaVersion: z8.literal("1.0"),
|
|
1111
|
+
caseId: z8.string().min(1),
|
|
1112
|
+
seed: z8.string().min(1),
|
|
1113
|
+
budget: z8.number().int().positive(),
|
|
1114
|
+
results: z8.array(VariantResultSchema),
|
|
1115
|
+
validDenominator: z8.number().int().nonnegative()
|
|
1116
|
+
});
|
|
1117
|
+
|
|
1118
|
+
// ../variants/src/generate.ts
|
|
1119
|
+
import { z as z9 } from "zod";
|
|
1120
|
+
var AmountRecordSchema = z9.object({
|
|
1121
|
+
victimDepositWei: z9.string().regex(/^\d+$/),
|
|
1122
|
+
attackerStakeWei: z9.string().regex(/^\d+$/)
|
|
1123
|
+
});
|
|
1124
|
+
|
|
1125
|
+
// ../variants/src/overlay.ts
|
|
1126
|
+
var VARIANT_TEST_SELECTOR = "test_VariantExploit";
|
|
1127
|
+
var VARIANT_VICTIM_DEPOSIT_ENV = "EXPLOITLENS_VARIANT_VICTIM_DEPOSIT_WEI";
|
|
1128
|
+
var VARIANT_ATTACKER_STAKE_ENV = "EXPLOITLENS_VARIANT_ATTACKER_STAKE_WEI";
|
|
1129
|
+
var VARIANT_OVERLAY_SOURCE = `// SPDX-License-Identifier: MIT
|
|
1130
|
+
pragma solidity 0.8.26;
|
|
1131
|
+
|
|
1132
|
+
import {Vault} from "../src/Vault.sol";
|
|
1133
|
+
|
|
1134
|
+
interface Vm {
|
|
1135
|
+
function deal(address account, uint256 newBalance) external;
|
|
1136
|
+
function prank(address sender) external;
|
|
1137
|
+
function envUint(string calldata name) external view returns (uint256);
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/// Harness generated by the exploitlens variants package (EL-070..072).
|
|
1141
|
+
/// Never part of the pinned fixture's checkout: written into a materialized
|
|
1142
|
+
/// workspace immediately before \`forge test\` runs, then discarded with the
|
|
1143
|
+
/// rest of that workspace. See packages/variants/src/overlay.ts for why this
|
|
1144
|
+
/// exists and what it deliberately does and does not change about the real
|
|
1145
|
+
/// Vault.
|
|
1146
|
+
contract VariantAttacker {
|
|
1147
|
+
Vault public immutable vault;
|
|
1148
|
+
uint256 public immutable stakeWei;
|
|
1149
|
+
bool private reentering;
|
|
1150
|
+
|
|
1151
|
+
constructor(Vault vault_, uint256 stakeWei_) {
|
|
1152
|
+
vault = vault_;
|
|
1153
|
+
stakeWei = stakeWei_;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
function attack() external payable {
|
|
1157
|
+
require(msg.value == stakeWei, "attack requires exactly stakeWei");
|
|
1158
|
+
reentering = true;
|
|
1159
|
+
vault.deposit{value: msg.value}();
|
|
1160
|
+
vault.withdraw();
|
|
1161
|
+
reentering = false;
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
receive() external payable {
|
|
1165
|
+
if (reentering && address(vault).balance >= stakeWei && vault.balances(address(this)) > 0) {
|
|
1166
|
+
vault.withdraw();
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
contract VariantTest {
|
|
1172
|
+
Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code")))));
|
|
1173
|
+
address private constant VICTIM = address(0xFEED);
|
|
1174
|
+
|
|
1175
|
+
Vault private vault;
|
|
1176
|
+
VariantAttacker private attacker;
|
|
1177
|
+
uint256 private attackerStakeWei;
|
|
1178
|
+
|
|
1179
|
+
function setUp() public {
|
|
1180
|
+
uint256 victimDepositWei = vm.envUint("${VARIANT_VICTIM_DEPOSIT_ENV}");
|
|
1181
|
+
attackerStakeWei = vm.envUint("${VARIANT_ATTACKER_STAKE_ENV}");
|
|
1182
|
+
|
|
1183
|
+
vault = new Vault();
|
|
1184
|
+
attacker = new VariantAttacker(vault, attackerStakeWei);
|
|
1185
|
+
|
|
1186
|
+
vm.deal(VICTIM, victimDepositWei);
|
|
1187
|
+
vm.prank(VICTIM);
|
|
1188
|
+
vault.deposit{value: victimDepositWei}();
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
/// Generalizes test_ExploitDrainsVault's oracle to parameterized amounts:
|
|
1192
|
+
/// passes when the attacker's net ETH gain from attack() exceeds what it
|
|
1193
|
+
/// staked. See this file's module doc for why this require() passing or
|
|
1194
|
+
/// reverting is not itself how a candidate's validity is decided.
|
|
1195
|
+
function ${VARIANT_TEST_SELECTOR}() public {
|
|
1196
|
+
uint256 beforeBalance = address(attacker).balance;
|
|
1197
|
+
|
|
1198
|
+
vm.deal(address(this), attackerStakeWei);
|
|
1199
|
+
attacker.attack{value: attackerStakeWei}();
|
|
1200
|
+
|
|
1201
|
+
uint256 attackerGain = address(attacker).balance - beforeBalance;
|
|
1202
|
+
require(attackerGain > attackerStakeWei, "no prohibited gain occurred");
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
`;
|
|
1206
|
+
|
|
1207
|
+
// ../variants/src/stax-overlay.ts
|
|
1208
|
+
var STAX_VARIANT_OVERLAY_SOURCE = `// SPDX-License-Identifier: MIT
|
|
1209
|
+
pragma solidity 0.8.26;
|
|
1210
|
+
|
|
1211
|
+
import {FakeMigrator} from "../src/FakeMigrator.sol";
|
|
1212
|
+
import {StakeLPToken} from "../src/StakeLPToken.sol";
|
|
1213
|
+
import {StaxLPStaking} from "../src/StaxLPStaking.sol";
|
|
1214
|
+
|
|
1215
|
+
interface Vm {
|
|
1216
|
+
function prank(address sender) external;
|
|
1217
|
+
function envUint(string calldata name) external view returns (uint256);
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
/// Harness generated by the exploitlens variants package (EL-070..072) for
|
|
1221
|
+
/// the temple-stax-migratestake-2022 case. Never part of the pinned
|
|
1222
|
+
/// fixture's checkout: written into a materialized workspace immediately
|
|
1223
|
+
/// before \`forge test\` runs, then discarded with the rest of that
|
|
1224
|
+
/// workspace. See packages/variants/src/stax-overlay.ts for the parameter
|
|
1225
|
+
/// mapping and packages/variants/src/case-overlay.ts for how this file is
|
|
1226
|
+
/// selected over the demo overlay.
|
|
1227
|
+
contract VariantTest {
|
|
1228
|
+
Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code")))));
|
|
1229
|
+
address private constant VICTIM = address(0xBEEF);
|
|
1230
|
+
address private constant ATTACKER = address(0xBAD1);
|
|
1231
|
+
|
|
1232
|
+
StakeLPToken private lpToken;
|
|
1233
|
+
StaxLPStaking private staking;
|
|
1234
|
+
uint256 private claimedAmountWei;
|
|
1235
|
+
|
|
1236
|
+
function setUp() public {
|
|
1237
|
+
uint256 victimDepositWei = vm.envUint("${VARIANT_VICTIM_DEPOSIT_ENV}");
|
|
1238
|
+
claimedAmountWei = vm.envUint("${VARIANT_ATTACKER_STAKE_ENV}");
|
|
1239
|
+
|
|
1240
|
+
lpToken = new StakeLPToken();
|
|
1241
|
+
staking = new StaxLPStaking(lpToken);
|
|
1242
|
+
|
|
1243
|
+
lpToken.mint(VICTIM, victimDepositWei);
|
|
1244
|
+
vm.prank(VICTIM);
|
|
1245
|
+
lpToken.approve(address(staking), victimDepositWei);
|
|
1246
|
+
vm.prank(VICTIM);
|
|
1247
|
+
staking.stake(victimDepositWei);
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/// Generalizes test_ExploitCreditsUnbackedStake's oracle to
|
|
1251
|
+
/// parameterized amounts. Whether this require() passes or reverts
|
|
1252
|
+
/// does NOT decide a candidate's vulnerableValidity -- run.ts reads
|
|
1253
|
+
/// that from evaluateInvariant against the run's extracted
|
|
1254
|
+
/// token-transfer effects (see overlay.ts's module doc for the same
|
|
1255
|
+
/// rule applied to the demo case).
|
|
1256
|
+
function ${VARIANT_TEST_SELECTOR}() public {
|
|
1257
|
+
FakeMigrator fake = new FakeMigrator();
|
|
1258
|
+
|
|
1259
|
+
vm.prank(ATTACKER);
|
|
1260
|
+
staking.migrateStake(address(fake), claimedAmountWei);
|
|
1261
|
+
|
|
1262
|
+
vm.prank(ATTACKER);
|
|
1263
|
+
staking.withdrawAll();
|
|
1264
|
+
|
|
1265
|
+
require(lpToken.balanceOf(ATTACKER) == claimedAmountWei, "no prohibited gain occurred");
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
`;
|
|
1269
|
+
|
|
1270
|
+
// ../verifier/src/verify.ts
|
|
1271
|
+
var REQUIRED_BUNDLE_FILES = [
|
|
1272
|
+
"artifact-index.json",
|
|
1273
|
+
"manifest.json",
|
|
1274
|
+
"receipt.json",
|
|
1275
|
+
"vulnerable/trace.json",
|
|
1276
|
+
"vulnerable/effects.json",
|
|
1277
|
+
"vulnerable/result.json",
|
|
1278
|
+
"patched/trace.json",
|
|
1279
|
+
"patched/effects.json",
|
|
1280
|
+
"patched/result.json",
|
|
1281
|
+
"patched/control-result.json"
|
|
1282
|
+
];
|
|
1283
|
+
var VARIANT_LEDGER_FILE = "variants/ledger.json";
|
|
1284
|
+
var OPTIONAL_BUNDLE_FILES = [
|
|
1285
|
+
"alignment.json",
|
|
1286
|
+
"divergence.json",
|
|
1287
|
+
VARIANT_LEDGER_FILE
|
|
1288
|
+
];
|
|
1289
|
+
var REQUIRED_GATE_NAMES = [
|
|
1290
|
+
"baseline",
|
|
1291
|
+
"exact-replay",
|
|
1292
|
+
"legitimate-control",
|
|
1293
|
+
"neighborhood"
|
|
1294
|
+
];
|
|
1295
|
+
async function readJson(bundleDir, relPath, budget) {
|
|
1296
|
+
const read = await readBundleFile(bundleDir, relPath, budget);
|
|
1297
|
+
if (!read.ok) {
|
|
1298
|
+
return { message: `could not read "${relPath}": ${read.error.message}` };
|
|
1299
|
+
}
|
|
1300
|
+
const text = read.value.bytes.toString("utf8");
|
|
1301
|
+
const depth = maxJsonDepth(text);
|
|
1302
|
+
const { maxJsonDepth: depthLimit } = budget.limitsInUse;
|
|
1303
|
+
if (depth > depthLimit) {
|
|
1304
|
+
return {
|
|
1305
|
+
message: `"${relPath}" nests ${depth} levels deep, above the ${depthLimit}-level JSON depth limit`
|
|
1306
|
+
};
|
|
1307
|
+
}
|
|
1308
|
+
try {
|
|
1309
|
+
return { bytes: read.value.bytes, value: JSON.parse(text) };
|
|
1310
|
+
} catch (cause) {
|
|
1311
|
+
return {
|
|
1312
|
+
message: `"${relPath}" is not valid JSON: ${cause instanceof Error ? cause.message : String(cause)}`
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
function isReadFailure(result) {
|
|
1317
|
+
return !("bytes" in result);
|
|
1318
|
+
}
|
|
1319
|
+
function recordSchemaIssues(relPath, error, issues) {
|
|
1320
|
+
const detail = error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ");
|
|
1321
|
+
issues.push({
|
|
1322
|
+
check: "schema",
|
|
1323
|
+
path: relPath,
|
|
1324
|
+
message: `"${relPath}" failed schema validation: ${detail}`
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
async function loadAndValidate(bundleDir, relPath, present, schema, budget, issues) {
|
|
1328
|
+
if (!present) return void 0;
|
|
1329
|
+
const raw = await readJson(bundleDir, relPath, budget);
|
|
1330
|
+
if (isReadFailure(raw)) {
|
|
1331
|
+
issues.push({ check: "schema", path: relPath, message: raw.message });
|
|
1332
|
+
return void 0;
|
|
1333
|
+
}
|
|
1334
|
+
const parsed = schema.safeParse(raw.value);
|
|
1335
|
+
if (!parsed.success) {
|
|
1336
|
+
recordSchemaIssues(relPath, parsed.error, issues);
|
|
1337
|
+
return void 0;
|
|
1338
|
+
}
|
|
1339
|
+
return { value: parsed.data, bytes: raw.bytes };
|
|
1340
|
+
}
|
|
1341
|
+
function checkTraceIntegrity(relPath, loaded, issues) {
|
|
1342
|
+
if (!loaded) return void 0;
|
|
1343
|
+
const integrity = validateTraceIntegrity(loaded.value);
|
|
1344
|
+
if (!integrity.ok) {
|
|
1345
|
+
issues.push({
|
|
1346
|
+
check: "schema",
|
|
1347
|
+
path: relPath,
|
|
1348
|
+
message: `"${relPath}" is not a well-formed call tree: ${integrity.error.message}`
|
|
1349
|
+
});
|
|
1350
|
+
return void 0;
|
|
1351
|
+
}
|
|
1352
|
+
return loaded;
|
|
1353
|
+
}
|
|
1354
|
+
async function checkRequiredFiles(bundleDir, issues) {
|
|
1355
|
+
const presence = {};
|
|
1356
|
+
for (const relPath of [...REQUIRED_BUNDLE_FILES, ...OPTIONAL_BUNDLE_FILES]) {
|
|
1357
|
+
presence[relPath] = await bundleFileExists(bundleDir, relPath);
|
|
1358
|
+
}
|
|
1359
|
+
for (const relPath of REQUIRED_BUNDLE_FILES) {
|
|
1360
|
+
if (!presence[relPath]) {
|
|
1361
|
+
issues.push({
|
|
1362
|
+
check: "required-file",
|
|
1363
|
+
path: relPath,
|
|
1364
|
+
message: `required file "${relPath}" is missing`
|
|
1365
|
+
});
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
return presence;
|
|
1369
|
+
}
|
|
1370
|
+
function sha256Hex(bytes) {
|
|
1371
|
+
return `0x${createHash3("sha256").update(bytes).digest("hex")}`;
|
|
1372
|
+
}
|
|
1373
|
+
async function checkIndexedHashes(bundleDir, index, budget, issues) {
|
|
1374
|
+
const { maxIndexedFiles } = budget.limitsInUse;
|
|
1375
|
+
if (index.files.length > maxIndexedFiles) {
|
|
1376
|
+
issues.push({
|
|
1377
|
+
check: "hash",
|
|
1378
|
+
path: "artifact-index.json",
|
|
1379
|
+
message: `artifact-index.json lists ${index.files.length} files, above the ${maxIndexedFiles}-entry limit`
|
|
1380
|
+
});
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
for (const entry of index.files) {
|
|
1384
|
+
const read = await readBundleFile(bundleDir, entry.path, budget);
|
|
1385
|
+
if (!read.ok) {
|
|
1386
|
+
issues.push({
|
|
1387
|
+
check: "hash",
|
|
1388
|
+
path: entry.path,
|
|
1389
|
+
message: `artifact-index.json references "${entry.path}", which could not be read as an ordinary file inside the bundle: ${read.error.message}`
|
|
1390
|
+
});
|
|
1391
|
+
continue;
|
|
1392
|
+
}
|
|
1393
|
+
const bytes = read.value.bytes;
|
|
1394
|
+
if (bytes.length !== entry.bytes) {
|
|
1395
|
+
issues.push({
|
|
1396
|
+
check: "hash",
|
|
1397
|
+
path: entry.path,
|
|
1398
|
+
message: `"${entry.path}" is ${bytes.length} bytes on disk but artifact-index.json records ${entry.bytes}`
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
const actual = sha256Hex(bytes);
|
|
1402
|
+
if (actual !== entry.sha256) {
|
|
1403
|
+
issues.push({
|
|
1404
|
+
check: "hash",
|
|
1405
|
+
path: entry.path,
|
|
1406
|
+
message: `"${entry.path}" hash mismatch: artifact-index.json records ${entry.sha256}, computed ${actual} from the file on disk`
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
async function checkEvidenceRefs(bundleDir, receipt, index, issues) {
|
|
1412
|
+
const indexed = new Set(index.files.map((entry) => entry.path));
|
|
1413
|
+
for (const ref of receipt.evidenceRefs) {
|
|
1414
|
+
if (!isSafeRelativePath(ref)) {
|
|
1415
|
+
issues.push({
|
|
1416
|
+
check: "internal-reference",
|
|
1417
|
+
path: ref,
|
|
1418
|
+
message: `receipt.evidenceRefs entry "${ref}" is not a safe bundle-relative path`
|
|
1419
|
+
});
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
if (!await bundleFileExists(bundleDir, ref)) {
|
|
1423
|
+
issues.push({
|
|
1424
|
+
check: "internal-reference",
|
|
1425
|
+
path: ref,
|
|
1426
|
+
message: `receipt.evidenceRefs entry "${ref}" does not exist in the bundle as an ordinary file`
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
if (!indexed.has(ref)) {
|
|
1430
|
+
issues.push({
|
|
1431
|
+
check: "internal-reference",
|
|
1432
|
+
path: ref,
|
|
1433
|
+
message: `receipt.evidenceRefs entry "${ref}" is not listed in artifact-index.json`
|
|
1434
|
+
});
|
|
1435
|
+
}
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
function checkManifestHash(manifest, receipt, issues) {
|
|
1439
|
+
const recomputed = `0x${hashCanonicalJson(canonicalizeJson(manifest))}`;
|
|
1440
|
+
if (recomputed !== receipt.manifestHash) {
|
|
1441
|
+
issues.push({
|
|
1442
|
+
check: "internal-reference",
|
|
1443
|
+
path: "manifest.json",
|
|
1444
|
+
message: `receipt.manifestHash (${receipt.manifestHash}) does not match the hash recomputed from manifest.json (${recomputed})`
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
function nodeIds(trace) {
|
|
1449
|
+
return new Set((trace?.nodes ?? []).map((node) => node.id));
|
|
1450
|
+
}
|
|
1451
|
+
function effectIds(effects) {
|
|
1452
|
+
return new Set((effects?.effects ?? []).map((effect) => effect.id));
|
|
1453
|
+
}
|
|
1454
|
+
function checkAlignmentReferences(alignment, vulnerableNodeIds, patchedNodeIds, issues) {
|
|
1455
|
+
alignment.records.forEach((record, i) => {
|
|
1456
|
+
if (record.baselineNodeId !== void 0 && !vulnerableNodeIds.has(record.baselineNodeId)) {
|
|
1457
|
+
issues.push({
|
|
1458
|
+
check: "internal-reference",
|
|
1459
|
+
path: `alignment.json.records[${i}].baselineNodeId`,
|
|
1460
|
+
message: `references node id "${record.baselineNodeId}", not found in vulnerable/trace.json`
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
if (record.patchedNodeId !== void 0 && !patchedNodeIds.has(record.patchedNodeId)) {
|
|
1464
|
+
issues.push({
|
|
1465
|
+
check: "internal-reference",
|
|
1466
|
+
path: `alignment.json.records[${i}].patchedNodeId`,
|
|
1467
|
+
message: `references node id "${record.patchedNodeId}", not found in patched/trace.json`
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
function checkDivergenceReferences(divergence, vulnerableNodeIds, patchedNodeIds, vulnerableEffectIds, patchedEffectIds, issues) {
|
|
1473
|
+
const record = divergence.divergence;
|
|
1474
|
+
if (record.baselineNodeId !== void 0 && !vulnerableNodeIds.has(record.baselineNodeId)) {
|
|
1475
|
+
issues.push({
|
|
1476
|
+
check: "internal-reference",
|
|
1477
|
+
path: "divergence.json.divergence.baselineNodeId",
|
|
1478
|
+
message: `references node id "${record.baselineNodeId}", not found in vulnerable/trace.json`
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
if (record.patchedNodeId !== void 0 && !patchedNodeIds.has(record.patchedNodeId)) {
|
|
1482
|
+
issues.push({
|
|
1483
|
+
check: "internal-reference",
|
|
1484
|
+
path: "divergence.json.divergence.patchedNodeId",
|
|
1485
|
+
message: `references node id "${record.patchedNodeId}", not found in patched/trace.json`
|
|
1486
|
+
});
|
|
1487
|
+
}
|
|
1488
|
+
record.explainedEffectIds.forEach((id, i) => {
|
|
1489
|
+
if (!vulnerableEffectIds.has(id)) {
|
|
1490
|
+
issues.push({
|
|
1491
|
+
check: "internal-reference",
|
|
1492
|
+
path: `divergence.json.divergence.explainedEffectIds[${i}]`,
|
|
1493
|
+
message: `references effect id "${id}", not found in vulnerable/effects.json`
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
});
|
|
1497
|
+
record.patchedEffectIds.forEach((id, i) => {
|
|
1498
|
+
if (!patchedEffectIds.has(id)) {
|
|
1499
|
+
issues.push({
|
|
1500
|
+
check: "internal-reference",
|
|
1501
|
+
path: `divergence.json.divergence.patchedEffectIds[${i}]`,
|
|
1502
|
+
message: `references effect id "${id}", not found in patched/effects.json`
|
|
1503
|
+
});
|
|
1504
|
+
}
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
function checkGateConsistency(receipt, issues) {
|
|
1508
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1509
|
+
for (const result of receipt.gates) {
|
|
1510
|
+
if (seen.has(result.gate)) {
|
|
1511
|
+
issues.push({
|
|
1512
|
+
check: "gate-consistency",
|
|
1513
|
+
path: "receipt.gates",
|
|
1514
|
+
message: `duplicate gate result for "${result.gate}"`
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
seen.add(result.gate);
|
|
1518
|
+
}
|
|
1519
|
+
for (const required of REQUIRED_GATE_NAMES) {
|
|
1520
|
+
if (!seen.has(required)) {
|
|
1521
|
+
issues.push({
|
|
1522
|
+
check: "gate-consistency",
|
|
1523
|
+
path: "receipt.gates",
|
|
1524
|
+
message: `missing required gate "${required}"`
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
function checkBundleDigest(receipt, index, issues) {
|
|
1530
|
+
const recomputed = computeBundleDigest(index.files);
|
|
1531
|
+
if (recomputed !== receipt.bundleDigest) {
|
|
1532
|
+
issues.push({
|
|
1533
|
+
check: "hash",
|
|
1534
|
+
path: "artifact-index.json",
|
|
1535
|
+
message: `receipt.bundleDigest (${receipt.bundleDigest}) does not match the digest recomputed from artifact-index.json's entries (${recomputed}); the indexed artifact set is not the one the receipt was generated from`
|
|
1536
|
+
});
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
function checkIndexCoverage(index, presence, issues) {
|
|
1540
|
+
const indexed = new Set(index.files.map((entry) => entry.path));
|
|
1541
|
+
for (const relPath of REQUIRED_BUNDLE_FILES) {
|
|
1542
|
+
if (relPath === "artifact-index.json") continue;
|
|
1543
|
+
if (!presence[relPath]) continue;
|
|
1544
|
+
if (!indexed.has(relPath)) {
|
|
1545
|
+
issues.push({
|
|
1546
|
+
check: "hash",
|
|
1547
|
+
path: relPath,
|
|
1548
|
+
message: `required file "${relPath}" is present in the bundle but absent from artifact-index.json, so its contents are not covered by any hash`
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
for (const relPath of OPTIONAL_BUNDLE_FILES) {
|
|
1553
|
+
if (presence[relPath] && !indexed.has(relPath)) {
|
|
1554
|
+
issues.push({
|
|
1555
|
+
check: "hash",
|
|
1556
|
+
path: relPath,
|
|
1557
|
+
message: `"${relPath}" is present in the bundle but absent from artifact-index.json, so its contents are not covered by any hash`
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
function checkCausalClaim(receipt, presence, divergence, issues) {
|
|
1563
|
+
if (receipt.causalDivergence.status !== "found") return;
|
|
1564
|
+
for (const relPath of ["alignment.json", "divergence.json"]) {
|
|
1565
|
+
if (!presence[relPath]) {
|
|
1566
|
+
issues.push({
|
|
1567
|
+
check: "internal-reference",
|
|
1568
|
+
path: relPath,
|
|
1569
|
+
message: `receipt.causalDivergence claims a first causal divergence was found, but "${relPath}" is not present in the bundle to support it`
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
if (!divergence) return;
|
|
1574
|
+
if (divergence.divergence.status !== "found") {
|
|
1575
|
+
issues.push({
|
|
1576
|
+
check: "internal-reference",
|
|
1577
|
+
path: "divergence.json",
|
|
1578
|
+
message: `receipt.causalDivergence claims status "found" but divergence.json reports "${divergence.divergence.status}"`
|
|
1579
|
+
});
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
const pairs = [
|
|
1583
|
+
[
|
|
1584
|
+
"baselineNodeId",
|
|
1585
|
+
receipt.causalDivergence.baselineNodeId,
|
|
1586
|
+
divergence.divergence.baselineNodeId
|
|
1587
|
+
],
|
|
1588
|
+
["patchedNodeId", receipt.causalDivergence.patchedNodeId, divergence.divergence.patchedNodeId]
|
|
1589
|
+
];
|
|
1590
|
+
for (const [field, claimed, actual] of pairs) {
|
|
1591
|
+
if (claimed !== actual) {
|
|
1592
|
+
issues.push({
|
|
1593
|
+
check: "internal-reference",
|
|
1594
|
+
path: `receipt.causalDivergence.${field}`,
|
|
1595
|
+
message: `receipt claims ${field} ${claimed ?? "(none)"} but divergence.json records ${actual ?? "(none)"}`
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
async function checkVariantClaim(bundleDir, receipt, presence, budget, issues) {
|
|
1601
|
+
const ledgerPresent = presence[VARIANT_LEDGER_FILE] ?? false;
|
|
1602
|
+
const claimedNeighborhood = receipt.gates.find((gate) => gate.gate === "neighborhood");
|
|
1603
|
+
if (receipt.variantDenominator > 0 && !ledgerPresent) {
|
|
1604
|
+
issues.push({
|
|
1605
|
+
check: "internal-reference",
|
|
1606
|
+
path: VARIANT_LEDGER_FILE,
|
|
1607
|
+
message: `receipt.variantDenominator is ${receipt.variantDenominator} but "${VARIANT_LEDGER_FILE}" is not present in the bundle to support it`
|
|
1608
|
+
});
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
if (!ledgerPresent) {
|
|
1612
|
+
if (claimedNeighborhood && claimedNeighborhood.status !== "inconclusive") {
|
|
1613
|
+
issues.push({
|
|
1614
|
+
check: "gate-consistency",
|
|
1615
|
+
path: "receipt.gates.neighborhood",
|
|
1616
|
+
message: `receipt claims gate "neighborhood" is "${claimedNeighborhood.status}" but the bundle carries no "${VARIANT_LEDGER_FILE}" to support any verdict but "inconclusive"`
|
|
1617
|
+
});
|
|
1618
|
+
}
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
const ledger = await loadAndValidate(
|
|
1622
|
+
bundleDir,
|
|
1623
|
+
VARIANT_LEDGER_FILE,
|
|
1624
|
+
true,
|
|
1625
|
+
VariantLedgerSchema,
|
|
1626
|
+
budget,
|
|
1627
|
+
issues
|
|
1628
|
+
);
|
|
1629
|
+
if (!ledger) return;
|
|
1630
|
+
const recountedValid = ledger.value.results.filter(
|
|
1631
|
+
(result) => result.vulnerableValidity === "valid"
|
|
1632
|
+
).length;
|
|
1633
|
+
if (ledger.value.validDenominator !== recountedValid) {
|
|
1634
|
+
issues.push({
|
|
1635
|
+
check: "internal-reference",
|
|
1636
|
+
path: `${VARIANT_LEDGER_FILE}.validDenominator`,
|
|
1637
|
+
message: `ledger records validDenominator ${ledger.value.validDenominator} but ${recountedValid} of its ${ledger.value.results.length} results are marked valid on the vulnerable commit`
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
if (receipt.variantDenominator !== ledger.value.validDenominator) {
|
|
1641
|
+
issues.push({
|
|
1642
|
+
check: "internal-reference",
|
|
1643
|
+
path: "receipt.variantDenominator",
|
|
1644
|
+
message: `receipt.variantDenominator is ${receipt.variantDenominator} but ${VARIANT_LEDGER_FILE} records validDenominator ${ledger.value.validDenominator}`
|
|
1645
|
+
});
|
|
1646
|
+
}
|
|
1647
|
+
if (claimedNeighborhood) {
|
|
1648
|
+
const derived = computeNeighborhoodGate(ledger.value);
|
|
1649
|
+
if (derived.status !== claimedNeighborhood.status) {
|
|
1650
|
+
issues.push({
|
|
1651
|
+
check: "gate-consistency",
|
|
1652
|
+
path: "receipt.gates.neighborhood",
|
|
1653
|
+
message: `receipt claims gate "neighborhood" is "${claimedNeighborhood.status}", but re-deriving it from ${VARIANT_LEDGER_FILE} yields "${derived.status}"`
|
|
1654
|
+
});
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
async function checkGatesAgainstEvidence(bundleDir, receipt, manifest, vulnerableEffects, patchedEffects, budget, issues) {
|
|
1659
|
+
const controlRaw = await readJson(bundleDir, "patched/control-result.json", budget);
|
|
1660
|
+
if (isReadFailure(controlRaw)) {
|
|
1661
|
+
issues.push({
|
|
1662
|
+
check: "gate-consistency",
|
|
1663
|
+
path: "patched/control-result.json",
|
|
1664
|
+
message: `gates could not be re-evaluated: ${controlRaw.message}`
|
|
1665
|
+
});
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
const controlRecord = controlRaw.value;
|
|
1669
|
+
if (typeof controlRecord !== "object" || controlRecord === null || !controlRecord.result) {
|
|
1670
|
+
issues.push({
|
|
1671
|
+
check: "gate-consistency",
|
|
1672
|
+
path: "patched/control-result.json",
|
|
1673
|
+
message: "gates could not be re-evaluated: control-result.json is not a run record"
|
|
1674
|
+
});
|
|
1675
|
+
return;
|
|
1676
|
+
}
|
|
1677
|
+
const recomputed = computeGateReport({
|
|
1678
|
+
caseId: manifest.caseId,
|
|
1679
|
+
expectedExploit: manifest.expectedExploit,
|
|
1680
|
+
invariant: manifest.invariant,
|
|
1681
|
+
vulnerableEffects,
|
|
1682
|
+
patchedEffects,
|
|
1683
|
+
patchedControlResult: controlRecord
|
|
1684
|
+
});
|
|
1685
|
+
const recomputedByName = new Map(recomputed.gates.map((gate) => [gate.gate, gate.status]));
|
|
1686
|
+
for (const claimed of receipt.gates) {
|
|
1687
|
+
if (claimed.gate === "neighborhood") continue;
|
|
1688
|
+
const derived = recomputedByName.get(claimed.gate);
|
|
1689
|
+
if (derived === void 0) continue;
|
|
1690
|
+
if (derived !== claimed.status) {
|
|
1691
|
+
issues.push({
|
|
1692
|
+
check: "gate-consistency",
|
|
1693
|
+
path: `receipt.gates.${claimed.gate}`,
|
|
1694
|
+
message: `receipt claims gate "${claimed.gate}" is "${claimed.status}", but re-evaluating it from this bundle's own evidence yields "${derived}"`
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
async function checkEnvironmentEnforcement(bundleDir, receipt, budget, issues) {
|
|
1700
|
+
const phaseFiles = [
|
|
1701
|
+
"vulnerable/result.json",
|
|
1702
|
+
"patched/result.json",
|
|
1703
|
+
"patched/control-result.json"
|
|
1704
|
+
];
|
|
1705
|
+
const records = [];
|
|
1706
|
+
for (const relPath of phaseFiles) {
|
|
1707
|
+
const raw = await readJson(bundleDir, relPath, budget);
|
|
1708
|
+
if (isReadFailure(raw)) {
|
|
1709
|
+
issues.push({
|
|
1710
|
+
check: "gate-consistency",
|
|
1711
|
+
path: relPath,
|
|
1712
|
+
message: `environment enforcement could not be re-derived: ${raw.message}`
|
|
1713
|
+
});
|
|
1714
|
+
return;
|
|
1715
|
+
}
|
|
1716
|
+
const record = raw.value;
|
|
1717
|
+
if (typeof record !== "object" || record === null) {
|
|
1718
|
+
issues.push({
|
|
1719
|
+
check: "gate-consistency",
|
|
1720
|
+
path: relPath,
|
|
1721
|
+
message: "environment enforcement could not be re-derived: not a run record"
|
|
1722
|
+
});
|
|
1723
|
+
return;
|
|
1724
|
+
}
|
|
1725
|
+
records.push(record);
|
|
1726
|
+
}
|
|
1727
|
+
const derived = isEnvironmentEnforced(records);
|
|
1728
|
+
if (derived !== receipt.environment.enforced) {
|
|
1729
|
+
const enforcedPhases = records.filter(
|
|
1730
|
+
(record) => record.environmentEnforcement?.enforced === true
|
|
1731
|
+
).length;
|
|
1732
|
+
issues.push({
|
|
1733
|
+
check: "gate-consistency",
|
|
1734
|
+
path: "receipt.environment.enforced",
|
|
1735
|
+
message: `receipt claims environment.enforced is ${receipt.environment.enforced}, but only ${enforcedPhases} of ${records.length} phase records carry a passing environment check, which re-derives as ${derived}`
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
function checkReceiptScope(receipt, issues) {
|
|
1740
|
+
if (receipt.scope.claim.trim().length === 0) {
|
|
1741
|
+
issues.push({
|
|
1742
|
+
check: "receipt-scope",
|
|
1743
|
+
path: "receipt.scope.claim",
|
|
1744
|
+
message: "scope.claim is empty"
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
if (receipt.scope.limitations.length === 0) {
|
|
1748
|
+
issues.push({
|
|
1749
|
+
check: "receipt-scope",
|
|
1750
|
+
path: "receipt.scope.limitations",
|
|
1751
|
+
message: "scope.limitations must list at least one limitation"
|
|
1752
|
+
});
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
async function verifyBundle(bundleDir, limits = DEFAULT_BUNDLE_LIMITS) {
|
|
1756
|
+
const issues = [];
|
|
1757
|
+
const budget = new ReadBudget(limits);
|
|
1758
|
+
const presence = await checkRequiredFiles(bundleDir, issues);
|
|
1759
|
+
const index = await loadAndValidate(
|
|
1760
|
+
bundleDir,
|
|
1761
|
+
"artifact-index.json",
|
|
1762
|
+
presence["artifact-index.json"] ?? false,
|
|
1763
|
+
ArtifactIndexSchema,
|
|
1764
|
+
budget,
|
|
1765
|
+
issues
|
|
1766
|
+
);
|
|
1767
|
+
const receipt = await loadAndValidate(
|
|
1768
|
+
bundleDir,
|
|
1769
|
+
"receipt.json",
|
|
1770
|
+
presence["receipt.json"] ?? false,
|
|
1771
|
+
ReceiptSchema,
|
|
1772
|
+
budget,
|
|
1773
|
+
issues
|
|
1774
|
+
);
|
|
1775
|
+
const manifest = await loadAndValidate(
|
|
1776
|
+
bundleDir,
|
|
1777
|
+
"manifest.json",
|
|
1778
|
+
presence["manifest.json"] ?? false,
|
|
1779
|
+
ExploitBundleSchema,
|
|
1780
|
+
budget,
|
|
1781
|
+
issues
|
|
1782
|
+
);
|
|
1783
|
+
const vulnerableTrace = checkTraceIntegrity(
|
|
1784
|
+
"vulnerable/trace.json",
|
|
1785
|
+
await loadAndValidate(
|
|
1786
|
+
bundleDir,
|
|
1787
|
+
"vulnerable/trace.json",
|
|
1788
|
+
presence["vulnerable/trace.json"] ?? false,
|
|
1789
|
+
TraceSchema,
|
|
1790
|
+
budget,
|
|
1791
|
+
issues
|
|
1792
|
+
),
|
|
1793
|
+
issues
|
|
1794
|
+
);
|
|
1795
|
+
const patchedTrace = checkTraceIntegrity(
|
|
1796
|
+
"patched/trace.json",
|
|
1797
|
+
await loadAndValidate(
|
|
1798
|
+
bundleDir,
|
|
1799
|
+
"patched/trace.json",
|
|
1800
|
+
presence["patched/trace.json"] ?? false,
|
|
1801
|
+
TraceSchema,
|
|
1802
|
+
budget,
|
|
1803
|
+
issues
|
|
1804
|
+
),
|
|
1805
|
+
issues
|
|
1806
|
+
);
|
|
1807
|
+
const vulnerableEffects = await loadAndValidate(
|
|
1808
|
+
bundleDir,
|
|
1809
|
+
"vulnerable/effects.json",
|
|
1810
|
+
presence["vulnerable/effects.json"] ?? false,
|
|
1811
|
+
EffectsFileSchema,
|
|
1812
|
+
budget,
|
|
1813
|
+
issues
|
|
1814
|
+
);
|
|
1815
|
+
const patchedEffects = await loadAndValidate(
|
|
1816
|
+
bundleDir,
|
|
1817
|
+
"patched/effects.json",
|
|
1818
|
+
presence["patched/effects.json"] ?? false,
|
|
1819
|
+
EffectsFileSchema,
|
|
1820
|
+
budget,
|
|
1821
|
+
issues
|
|
1822
|
+
);
|
|
1823
|
+
const alignment = await loadAndValidate(
|
|
1824
|
+
bundleDir,
|
|
1825
|
+
"alignment.json",
|
|
1826
|
+
presence["alignment.json"] ?? false,
|
|
1827
|
+
AlignmentFileSchema,
|
|
1828
|
+
budget,
|
|
1829
|
+
issues
|
|
1830
|
+
);
|
|
1831
|
+
const divergence = await loadAndValidate(
|
|
1832
|
+
bundleDir,
|
|
1833
|
+
"divergence.json",
|
|
1834
|
+
presence["divergence.json"] ?? false,
|
|
1835
|
+
DivergenceFileSchema,
|
|
1836
|
+
budget,
|
|
1837
|
+
issues
|
|
1838
|
+
);
|
|
1839
|
+
if (index) {
|
|
1840
|
+
await checkIndexedHashes(bundleDir, index.value, budget, issues);
|
|
1841
|
+
}
|
|
1842
|
+
if (receipt && index) {
|
|
1843
|
+
await checkEvidenceRefs(bundleDir, receipt.value, index.value, issues);
|
|
1844
|
+
}
|
|
1845
|
+
if (receipt && manifest) {
|
|
1846
|
+
checkManifestHash(manifest.value, receipt.value, issues);
|
|
1847
|
+
}
|
|
1848
|
+
if (vulnerableTrace && patchedTrace) {
|
|
1849
|
+
const vulnerableNodeIds = nodeIds(vulnerableTrace.value);
|
|
1850
|
+
const patchedNodeIds = nodeIds(patchedTrace.value);
|
|
1851
|
+
if (alignment) {
|
|
1852
|
+
checkAlignmentReferences(alignment.value, vulnerableNodeIds, patchedNodeIds, issues);
|
|
1853
|
+
}
|
|
1854
|
+
if (divergence && vulnerableEffects && patchedEffects) {
|
|
1855
|
+
checkDivergenceReferences(
|
|
1856
|
+
divergence.value,
|
|
1857
|
+
vulnerableNodeIds,
|
|
1858
|
+
patchedNodeIds,
|
|
1859
|
+
effectIds(vulnerableEffects.value),
|
|
1860
|
+
effectIds(patchedEffects.value),
|
|
1861
|
+
issues
|
|
1862
|
+
);
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
if (receipt) {
|
|
1866
|
+
checkGateConsistency(receipt.value, issues);
|
|
1867
|
+
checkReceiptScope(receipt.value, issues);
|
|
1868
|
+
}
|
|
1869
|
+
if (receipt && index) {
|
|
1870
|
+
checkBundleDigest(receipt.value, index.value, issues);
|
|
1871
|
+
checkIndexCoverage(index.value, presence, issues);
|
|
1872
|
+
}
|
|
1873
|
+
if (receipt) {
|
|
1874
|
+
await checkEnvironmentEnforcement(bundleDir, receipt.value, budget, issues);
|
|
1875
|
+
checkCausalClaim(receipt.value, presence, divergence?.value, issues);
|
|
1876
|
+
await checkVariantClaim(bundleDir, receipt.value, presence, budget, issues);
|
|
1877
|
+
}
|
|
1878
|
+
if (receipt && manifest && vulnerableEffects && patchedEffects) {
|
|
1879
|
+
await checkGatesAgainstEvidence(
|
|
1880
|
+
bundleDir,
|
|
1881
|
+
receipt.value,
|
|
1882
|
+
manifest.value,
|
|
1883
|
+
vulnerableEffects.value,
|
|
1884
|
+
patchedEffects.value,
|
|
1885
|
+
budget,
|
|
1886
|
+
issues
|
|
1887
|
+
);
|
|
1888
|
+
}
|
|
1889
|
+
return { bundleDir, ok: issues.length === 0, issues };
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
// ../verifier/src/format.ts
|
|
1893
|
+
function formatReport(report) {
|
|
1894
|
+
if (report.ok) {
|
|
1895
|
+
return [`Bundle valid: ${report.bundleDir}`];
|
|
1896
|
+
}
|
|
1897
|
+
const lines = [`Bundle invalid: ${report.bundleDir}`];
|
|
1898
|
+
for (const issue of report.issues) {
|
|
1899
|
+
lines.push(` - [${issue.check}] ${issue.path}: ${issue.message}`);
|
|
1900
|
+
}
|
|
1901
|
+
return lines;
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
// ../verifier/src/bundle.ts
|
|
1905
|
+
var INDEXED_BUNDLE_FILES = [...REQUIRED_BUNDLE_FILES, ...OPTIONAL_BUNDLE_FILES].filter(
|
|
1906
|
+
// `artifact-index.json` cannot list itself; the variant ledger is added
|
|
1907
|
+
// back per-run, only when one was actually produced.
|
|
1908
|
+
(relPath) => relPath !== "artifact-index.json" && relPath !== VARIANT_LEDGER_FILE
|
|
1909
|
+
);
|
|
1910
|
+
|
|
1911
|
+
// src/index.ts
|
|
1912
|
+
async function verifyBundle2(bundleDir) {
|
|
1913
|
+
const report = await verifyBundle(bundleDir);
|
|
1914
|
+
return report;
|
|
1915
|
+
}
|
|
1916
|
+
function formatReport2(report) {
|
|
1917
|
+
return formatReport(report);
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
// src/cli.ts
|
|
1921
|
+
var USAGE = "Usage: exploitlens-verify <bundle-dir> [--json]\n\n Verify an ExploitLens Fix Receipt offline. Reads the bundle, re-hashes\n every file, and re-derives the verdict from the evidence. Runs nothing.\n\n --json print the full report as JSON instead of lines\n --help print this\n";
|
|
1922
|
+
async function run(argv) {
|
|
1923
|
+
const args = [...argv];
|
|
1924
|
+
let json = false;
|
|
1925
|
+
const positional = [];
|
|
1926
|
+
for (const arg of args) {
|
|
1927
|
+
if (arg === "--help" || arg === "-h") {
|
|
1928
|
+
process.stdout.write(USAGE);
|
|
1929
|
+
return 0;
|
|
1930
|
+
} else if (arg === "--json") {
|
|
1931
|
+
json = true;
|
|
1932
|
+
} else if (arg.startsWith("-")) {
|
|
1933
|
+
process.stderr.write(`Unknown flag: ${arg}
|
|
1934
|
+
|
|
1935
|
+
${USAGE}`);
|
|
1936
|
+
return 1;
|
|
1937
|
+
} else {
|
|
1938
|
+
positional.push(arg);
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
if (positional.length !== 1) {
|
|
1942
|
+
process.stderr.write(`${USAGE}`);
|
|
1943
|
+
return 1;
|
|
1944
|
+
}
|
|
1945
|
+
const bundleDir = positional[0];
|
|
1946
|
+
let report;
|
|
1947
|
+
try {
|
|
1948
|
+
report = await verifyBundle2(bundleDir);
|
|
1949
|
+
} catch (error) {
|
|
1950
|
+
process.stderr.write(`Could not read bundle at ${bundleDir}: ${error.message}
|
|
1951
|
+
`);
|
|
1952
|
+
return 1;
|
|
1953
|
+
}
|
|
1954
|
+
if (json) {
|
|
1955
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}
|
|
1956
|
+
`);
|
|
1957
|
+
} else {
|
|
1958
|
+
const write = report.ok ? process.stdout : process.stderr;
|
|
1959
|
+
for (const line of formatReport2(report)) {
|
|
1960
|
+
write.write(`${line}
|
|
1961
|
+
`);
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
return report.ok ? 0 : 1;
|
|
1965
|
+
}
|
|
1966
|
+
var isDirectRun = process.argv[1] !== void 0 && fileURLToPath2(import.meta.url) === process.argv[1];
|
|
1967
|
+
if (isDirectRun) {
|
|
1968
|
+
run(process.argv.slice(2)).then(
|
|
1969
|
+
(code) => {
|
|
1970
|
+
process.exitCode = code;
|
|
1971
|
+
},
|
|
1972
|
+
(error) => {
|
|
1973
|
+
process.stderr.write(`exploitlens-verify crashed: ${error.message}
|
|
1974
|
+
`);
|
|
1975
|
+
process.exitCode = 1;
|
|
1976
|
+
}
|
|
1977
|
+
);
|
|
1978
|
+
}
|
|
1979
|
+
export {
|
|
1980
|
+
run
|
|
1981
|
+
};
|