Skip to content

Commit aa88f89

Browse files
authored
fix: audit batch — enable-mode install bypass (H), factory-nonce replay (M), validity-format ordering (M) (#58)
* fix: gate enable-mode install on root signature success * test: enable-mode install rejected on failed root signature * fix: advance factory nonce on direct approval changes * test: direct factory approval advances nonce * fix: normalize validity ranges before format classification * test: validity-format ordering regressions * fix: RP-01 checkValidation EntryPoint v0.9 parity (#59) * fix: checkValidation block-mode and exclusive validAfter per EntryPoint v0.9 * test: cover checkValidation EntryPoint v0.9 boundaries * fix: vendor canonical EntryPoint v0.9 release initcode and address
1 parent 3ec9fcd commit aa88f89

11 files changed

Lines changed: 345 additions & 32 deletions

‎CHANGELOG_AUDIT.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Added support for ERC-4337 EntryPoint version 0.9.
1717
- Gas snapshot updates reflecting v0.9 optimizations (reduced gas costs across all test scenarios)
1818
- **Breaking Change:** UserOperation hash calculation has been changed in EntryPoint v0.9
1919
- **Files:** `foundry.toml`, `remappings.txt`, `soldeer.lock`, `test/utils/EntryPointLib.sol`, `test/KernelUserOpTest.sol`, `test/KernelValidatorTest.sol`
20-
- **EntryPoint Address:** `0x43370900c8de573dB349BEd8DD53b4Ebd3Cce709`
20+
- **EntryPoint Address:** `0x433709009B8330FDa32311DF1C2AFA402eD8D009`
2121
- **Commits:** 977ca07, aa91ef1, 110c7af, 3e72921
2222
- **Note:** The module type ID was updated from 8 to 10 for `MODULE_TYPE_STATELESS_VALIDATOR_WITH_SENDER` as part of this upgrade
2323
- you can find the release docs in [here](https://docs.google.com/document/d/1RKkKZsP1eYkOoBEkzJ1vWRK_bcWXaewoGPzawMjsleM/edit?usp=drivesdk), please do note that this document is not in public yet

‎src/Kernel.sol‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,15 @@ abstract contract Kernel is ModuleManager, ExecutionManager, IERC7579Account {
146146
sig := signature.offset
147147
}
148148
validationData = _verifyInstallSignatureRaw(enableReplayable, sig.nonce, sig.packages, sig.enableSignature);
149+
// Root did not authorize this install -> surface the failure and install nothing.
150+
// Compare only the failure field: a valid enable signature may carry nonzero
151+
// validity bounds, so the full packed word must not be compared against 1.
152+
// Without this guard, a call to validateUserOp outside the EntryPoint validation
153+
// phase (where the returned validationData is ignored) would install modules and
154+
// advance the nonce despite a failed root signature.
155+
if (uint160(validationData) == 1) {
156+
return validationData;
157+
}
149158
_checkAndIncrementNonce(sig.nonce);
150159
_install(sig.packages);
151160
signature = sig.userOpSignature;

‎src/Staker.sol‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ contract Staker is Ownable, EIP712 {
4040
/// @param _factory The factory address to approve or revoke.
4141
/// @param approval True to approve, false to revoke.
4242
function approveFactory(address _factory, bool approval) external payable onlyOwner {
43+
// Advance the per-factory nonce so any outstanding signed approval is invalidated,
44+
// even when `approval` already matches the stored value. Otherwise a revoked factory
45+
// could be re-approved by replaying a previously signed, never-consumed approval.
46+
nonces[_factory]++;
4347
approved[_factory] = approval;
4448
emit FactoryApprovalChanged(_factory, approval);
4549
}

‎src/lib/Lib4337.sol‎

Lines changed: 49 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,20 @@ library Lib4337 {
3232
}
3333

3434
function checkValidation(uint256 validationData) internal view returns (bool) {
35+
if (validationData == 0) {
36+
return true;
37+
}
3538
(uint48 vAfter, uint48 vUntil, address res) = Lib4337.parseValidationData(validationData);
36-
if (vAfter > block.timestamp || vUntil < block.timestamp) {
37-
return false;
39+
uint256 current;
40+
if (_usesBlockNumberFormat(vAfter, vUntil)) {
41+
vAfter &= MODE_BIT - 1;
42+
vUntil &= MODE_BIT - 1;
43+
current = block.number;
44+
} else {
45+
current = block.timestamp;
3846
}
39-
return res == address(0);
47+
// Canonical EntryPoint v0.9 interval: (validAfter, validUntil].
48+
return res == address(0) && current > vAfter && current <= vUntil;
4049
}
4150

4251
/// @dev Variant of `_hashTypedData` that excludes the chain ID.
@@ -78,25 +87,8 @@ library Lib4337 {
7887
return preValidationData | validationRes;
7988
}
8089

81-
// Extract raw time bounds
82-
uint48 validUntil1 = uint48(preValidationData >> 160);
83-
uint48 validUntil2 = uint48(validationRes >> 160);
84-
uint48 validAfter1 = uint48(preValidationData >> 208);
85-
uint48 validAfter2 = uint48(validationRes >> 208);
86-
87-
// Check for validity format mismatch (EP v0.9: block number vs timestamp)
88-
// Block number format: both validAfter and validUntil have highest bit set
89-
bool preUsesBlock = _usesBlockNumberFormat(validAfter1, validUntil1);
90-
bool resUsesBlock = _usesBlockNumberFormat(validAfter2, validUntil2);
91-
require(preUsesBlock == resUsesBlock, ValidityFormatMismatch());
92-
93-
// Convert validUntil=0 to max (no expiry)
94-
if (validUntil1 == 0) validUntil1 = type(uint48).max;
95-
if (validUntil2 == 0) validUntil2 = type(uint48).max;
96-
97-
resValidationData = uint256(validUntil1 > validUntil2 ? validUntil2 : validUntil1) << 160;
98-
resValidationData |= uint256(validAfter1 < validAfter2 ? validAfter2 : validAfter1) << 208;
99-
90+
// Aggregator FIRST: resolve success / failure / conflict before touching the ranges.
91+
//
10092
// Aggregator values: 0 = success, 1 = failure, >1 = aggregator address
10193
//
10294
// Rules (in precedence order):
@@ -109,20 +101,51 @@ library Lib4337 {
109101
uint160 preAgg = uint160(preValidationData);
110102
uint160 resAgg = uint160(validationRes);
111103

112-
uint160 finalAgg;
113-
114-
finalAgg = (preAgg == 1 || resAgg == 1)
104+
uint160 finalAgg = (preAgg == 1 || resAgg == 1)
115105
? 1 // Any failure
116106
: (preAgg == 0 && resAgg == 0)
117107
? 0 // Both success
118108
: (preAgg > 1 && resAgg == 0)
119-
? preAgg // Preserve aggregator (FIX)
109+
? preAgg // Preserve aggregator
120110
: (preAgg == 0 && resAgg > 1)
121111
? resAgg // Use new aggregator
122112
: (preAgg == resAgg)
123113
? preAgg // Same aggregator
124114
: 1; // Conflict or unknown
125115

116+
// Extract raw time bounds
117+
uint48 validUntil1 = uint48(preValidationData >> 160);
118+
uint48 validUntil2 = uint48(validationRes >> 160);
119+
uint48 validAfter1 = uint48(preValidationData >> 208);
120+
uint48 validAfter2 = uint48(validationRes >> 208);
121+
122+
// Normalize validUntil=0 to max (no expiry) BEFORE classifying the format. Doing this
123+
// after the format check misclassifies an unbounded block range (validUntil=0) as a
124+
// timestamp range, letting a mixed intersection drop a future timestamp start.
125+
if (validUntil1 == 0) validUntil1 = type(uint48).max;
126+
if (validUntil2 == 0) validUntil2 = type(uint48).max;
127+
128+
// Only enforce format compatibility for a usable (non-failure) result. When either side
129+
// reports signature failure (finalAgg == 1) the op is rejected regardless of its time
130+
// bounds, and a failed operand carries zeroed bounds that must not trigger a spurious
131+
// ValidityFormatMismatch revert — so the check is skipped. A neutral [0, max] range
132+
// carries no restriction and no format and is likewise exempt (its normalized validUntil
133+
// has MODE_BIT set, which would otherwise misclassify it as a block range).
134+
if (finalAgg != 1) {
135+
bool preNeutral = validAfter1 == 0 && validUntil1 == type(uint48).max;
136+
bool resNeutral = validAfter2 == 0 && validUntil2 == type(uint48).max;
137+
// Block number format: both validAfter and validUntil have the highest bit set.
138+
if (!preNeutral && !resNeutral) {
139+
require(
140+
_usesBlockNumberFormat(validAfter1, validUntil1)
141+
== _usesBlockNumberFormat(validAfter2, validUntil2),
142+
ValidityFormatMismatch()
143+
);
144+
}
145+
}
146+
147+
resValidationData = uint256(validUntil1 > validUntil2 ? validUntil2 : validUntil1) << 160;
148+
resValidationData |= uint256(validAfter1 < validAfter2 ? validAfter2 : validAfter1) << 208;
126149
resValidationData |= finalAgg;
127150
}
128151
}

‎test/CheckValidation.t.sol‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// SPDX-License-Identifier: MIT
2+
pragma solidity ^0.8.0;
3+
4+
import "forge-std/Test.sol";
5+
6+
import "src/lib/Lib4337.sol";
7+
8+
/// @dev RP-01: `Lib4337.checkValidation` must match canonical EntryPoint v0.9 semantics —
9+
/// exact-zero success, block-number vs timestamp mode selection, and the exclusive
10+
/// interval `(validAfter, validUntil]`.
11+
contract CheckValidationTest is Test {
12+
uint48 constant MODE_BIT = 0x800000000000;
13+
14+
function _pack(uint48 validAfter, uint48 validUntil, address res) internal pure returns (uint256) {
15+
return uint256(validAfter) << 208 | uint256(validUntil) << 160 | uint160(res);
16+
}
17+
18+
// --- exact zero ---------------------------------------------------------
19+
20+
function test_ExactZero_IsUnconditionalSuccess() public {
21+
// Even at block.timestamp == 0, canonical EntryPoint treats packed-zero as success.
22+
vm.warp(0);
23+
assertTrue(Lib4337.checkValidation(0));
24+
}
25+
26+
// --- result field -------------------------------------------------------
27+
28+
function test_NonzeroResult_Failure_IsInvalid() public {
29+
vm.warp(1000);
30+
assertFalse(Lib4337.checkValidation(_pack(100, 2000, address(1))));
31+
}
32+
33+
function test_NonzeroResult_Aggregator_IsInvalid() public {
34+
vm.warp(1000);
35+
assertFalse(Lib4337.checkValidation(_pack(100, 2000, address(0x1234))));
36+
}
37+
38+
// --- timestamp mode boundaries: valid iff current in (validAfter, validUntil] ---
39+
40+
function test_Timestamp_CurrentEqualsValidAfter_IsInvalid() public {
41+
vm.warp(100);
42+
assertFalse(Lib4337.checkValidation(_pack(100, 200, address(0))));
43+
}
44+
45+
function test_Timestamp_CurrentOneAboveValidAfter_IsValid() public {
46+
vm.warp(101);
47+
assertTrue(Lib4337.checkValidation(_pack(100, 200, address(0))));
48+
}
49+
50+
function test_Timestamp_CurrentEqualsValidUntil_IsValid() public {
51+
vm.warp(200);
52+
assertTrue(Lib4337.checkValidation(_pack(100, 200, address(0))));
53+
}
54+
55+
function test_Timestamp_CurrentOneAboveValidUntil_IsInvalid() public {
56+
vm.warp(201);
57+
assertFalse(Lib4337.checkValidation(_pack(100, 200, address(0))));
58+
}
59+
60+
function test_Timestamp_ZeroValidUntil_IsUnbounded() public {
61+
// Raw validUntil == 0 normalizes to type(uint48).max (no expiry).
62+
vm.warp(uint256(type(uint48).max) - 1);
63+
assertTrue(Lib4337.checkValidation(_pack(100, 0, address(0))));
64+
}
65+
66+
// --- block-number mode boundaries: compared against block.number ---------
67+
68+
function test_Block_UsesBlockNumberNotTimestamp() public {
69+
// A deliberately incompatible timestamp proves block mode ignores block.timestamp.
70+
vm.warp(uint256(type(uint48).max) + 1);
71+
vm.roll(150);
72+
assertTrue(Lib4337.checkValidation(_pack(MODE_BIT | 100, MODE_BIT | 200, address(0))));
73+
}
74+
75+
function test_Block_CurrentEqualsValidAfter_IsInvalid() public {
76+
vm.roll(100);
77+
assertFalse(Lib4337.checkValidation(_pack(MODE_BIT | 100, MODE_BIT | 200, address(0))));
78+
}
79+
80+
function test_Block_CurrentOneAboveValidAfter_IsValid() public {
81+
vm.roll(101);
82+
assertTrue(Lib4337.checkValidation(_pack(MODE_BIT | 100, MODE_BIT | 200, address(0))));
83+
}
84+
85+
function test_Block_CurrentEqualsValidUntil_IsValid() public {
86+
vm.roll(200);
87+
assertTrue(Lib4337.checkValidation(_pack(MODE_BIT | 100, MODE_BIT | 200, address(0))));
88+
}
89+
90+
function test_Block_CurrentOneAboveValidUntil_IsInvalid() public {
91+
vm.roll(201);
92+
assertFalse(Lib4337.checkValidation(_pack(MODE_BIT | 100, MODE_BIT | 200, address(0))));
93+
}
94+
95+
function test_Block_ZeroValidUntil_IsUnbounded() public {
96+
// MODE_BIT validAfter with raw zero validUntil stays block mode, unbounded upper.
97+
vm.roll(uint256(uint48(MODE_BIT | 100) & (MODE_BIT - 1)) + 1);
98+
assertTrue(Lib4337.checkValidation(_pack(MODE_BIT | 100, 0, address(0))));
99+
}
100+
101+
// --- exact MODE_BIT classification (>= MODE_BIT, equality counts) --------
102+
103+
function test_ExactModeBitBound_ClassifiesAsBlockMode() public pure {
104+
// RP-01: a bound exactly equal to MODE_BIT counts as block-number format (>= MODE_BIT),
105+
// not just strictly greater. Both bounds must carry the flag.
106+
assertTrue(Lib4337._usesBlockNumberFormat(MODE_BIT, MODE_BIT));
107+
assertTrue(Lib4337._usesBlockNumberFormat(MODE_BIT, MODE_BIT | 10));
108+
// One bound below MODE_BIT → timestamp format.
109+
assertFalse(Lib4337._usesBlockNumberFormat(MODE_BIT - 1, MODE_BIT));
110+
assertFalse(Lib4337._usesBlockNumberFormat(MODE_BIT, MODE_BIT - 1));
111+
}
112+
}

‎test/IntersectValidationData.t.sol‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,5 +400,67 @@ contract IntersectValidationDataTest is Test {
400400
assertTrue(resultAfter & MODE_BIT != 0, "Result validAfter should have MODE_BIT");
401401
assertTrue(resultUntil & MODE_BIT != 0, "Result validUntil should have MODE_BIT");
402402
}
403+
404+
/**
405+
* TEST CATEGORY 9: Regression — validity-format ordering (audit M-03)
406+
*
407+
* The format check must run AFTER `validUntil == 0 -> max` normalization, the
408+
* aggregator failure/conflict must resolve BEFORE the format check, and a neutral
409+
* `[0, max]` range must be exempt from the format check.
410+
*/
411+
412+
// An unbounded block range encodes validUntil = 0. Before the fix this was classified
413+
// as timestamp format (raw validUntil = 0 lacks MODE_BIT), so pairing it with a future
414+
// timestamp range passed the format check and then dropped the future timestamp start
415+
// (MODE_BIT >> any real timestamp, so max() kept the block validAfter). After the fix the
416+
// range normalizes to [MODE_BIT|block, max] (block format) and the mismatched intersection
417+
// is rejected instead of silently producing an already-valid result.
418+
function test_Regression_UnboundedBlockRangeVsFutureTimestampReverts() public {
419+
uint256 unboundedBlock = createValidationData(100 | MODE_BIT, 0, address(0));
420+
uint256 futureTimestamp = createValidationData(2_000_000_000, 0, address(0));
421+
422+
try this.callIntersect(unboundedBlock, futureTimestamp) returns (uint256 result) {
423+
// The dangerous pre-fix outcome: no revert AND the future start is dropped.
424+
uint48 resultAfter = uint48(result >> 208);
425+
assertFalse(
426+
resultAfter == (100 | MODE_BIT),
427+
"M-03: future timestamp start dropped by misclassified unbounded block range"
428+
);
429+
fail("M-03: mismatched block/timestamp intersection must revert, not silently merge");
430+
} catch (bytes memory reason) {
431+
assertEq(bytes4(reason), bytes4(keccak256("ValidityFormatMismatch()")));
432+
}
433+
}
434+
435+
// A signature-failure operand (aggregator == 1) has all-zero raw time bounds. Before the
436+
// fix, pairing it with a block-format range hit the format `revert` before the aggregator
437+
// logic ran. After the fix the failure short-circuits and returns SIG_VALIDATION_FAILED.
438+
function test_Regression_FailureOperandDoesNotRevertOnFormatMismatch() public {
439+
uint256 blockValid = createValidationData(100 | MODE_BIT, 200 | MODE_BIT, address(0));
440+
uint256 failure = createValidationData(0, 0, address(1));
441+
442+
// Must not revert; must return failure.
443+
uint256 result = Lib4337._intersectValidationData(blockValid, failure);
444+
assertEq(uint160(result), 1, "M-03: signature failure must be returned, not reverted");
445+
446+
// Symmetric ordering.
447+
uint256 resultRev = Lib4337._intersectValidationData(failure, blockValid);
448+
assertEq(uint160(resultRev), 1, "M-03: signature failure must be returned, not reverted (reverse)");
449+
}
450+
451+
// A neutral [0, max] range carries no restriction and no format. It must intersect with a
452+
// block-format range without a spurious ValidityFormatMismatch (its normalized validUntil
453+
// has MODE_BIT set, which would otherwise misclassify it as block/timestamp inconsistently).
454+
function test_Regression_NeutralRangeWithBlockRangeDoesNotRevert() public {
455+
// Neutral range carrying only an aggregator (validAfter = validUntil = 0).
456+
uint256 neutral = createValidationData(0, 0, BLS_AGGREGATOR);
457+
uint256 blockRange = createValidationData(100 | MODE_BIT, 200 | MODE_BIT, address(0));
458+
459+
uint256 result = Lib4337._intersectValidationData(neutral, blockRange);
460+
461+
assertEq(uint160(result), uint160(BLS_AGGREGATOR), "M-03: aggregator must survive neutral intersection");
462+
assertEq(uint48(result >> 208), 100 | MODE_BIT, "M-03: block validAfter must be preserved");
463+
assertEq(uint48(result >> 160), 200 | MODE_BIT, "M-03: block validUntil must be preserved");
464+
}
403465
}
404466

‎test/KernelUserOpTest.sol‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,51 @@ abstract contract KernelUserOpTest is KernelTestBase {
349349
vm.stopPrank();
350350
}
351351

352+
// Regression (audit H-01): enable-mode install must NOT persist when the root signature
353+
// fails, even when validateUserOp is invoked outside the EntryPoint validation phase (during
354+
// execution EntryPoint calls the account with arbitrary calldata and ignores the returned
355+
// validationData). Before the fix, _processUserOp installed the package and advanced the
356+
// nonce before the failed validationData was ever checked, so a scoped key could install
357+
// arbitrary modules without root approval.
358+
function test_userop_enable_failed_root_sig_does_not_install() external entryPointTest {
359+
// newValidator is not installed yet.
360+
assertEq(kernel.validationInfo(validatorToIdentifier(newValidator)).hook, address(0));
361+
362+
PackedUserOperation memory op = PackedUserOperation({
363+
sender: address(kernel),
364+
nonce: encodeNonce(false, true, false, bytes1(0x01), bytes20(address(newValidator))),
365+
initCode: hex"",
366+
callData: abi.encodeWithSelector(
367+
Kernel.execute.selector,
368+
bytes32(0),
369+
abi.encodePacked(address(callee), uint256(0), MockCallee.foo.selector)
370+
),
371+
accountGasLimits: bytes32(abi.encodePacked(uint128(1000000), uint128(1000000))),
372+
preVerificationGas: 1000000,
373+
gasFees: bytes32(abi.encodePacked(uint128(1), uint128(1))),
374+
paymasterAndData: hex"",
375+
signature: hex""
376+
});
377+
// enableSuccess = false -> the root signature over the install digest is invalid.
378+
op.signature = encodeEnableValidatorSignature(
379+
Kernel.execute.selector, 0, false, false, _rootSignHash, _validatorSignUserOp(op, true, false)
380+
);
381+
382+
// Simulate the execution-phase re-entry: EntryPoint calls validateUserOp and discards
383+
// the return value.
384+
vm.prank(address(ep));
385+
uint256 validationData = kernel.validateUserOp(op, bytes32(0), 0);
386+
387+
// Failed root signature must surface as validation failure...
388+
assertEq(uint160(validationData), 1, "H-01: failed root sig must return SIG_VALIDATION_FAILED");
389+
// ...and the module must NOT have been installed.
390+
assertEq(
391+
kernel.validationInfo(validatorToIdentifier(newValidator)).hook,
392+
address(0),
393+
"H-01: module installed despite failed root signature"
394+
);
395+
}
396+
352397
function test_userop_validator_aa24_validation_failed() external entryPointTest {
353398
PackedUserOperation[] memory ops = new PackedUserOperation[](1);
354399
ops[0] = PackedUserOperation({

0 commit comments

Comments
 (0)