draft-ERC7579Utils.t.sol 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. // SPDX-License-Identifier: UNLICENSED
  2. pragma solidity ^0.8.24;
  3. // Parts of this test file are adapted from Adam Egyed (@adamegyed) proof of concept available at:
  4. // https://github.com/adamegyed/erc7579-execute-vulnerability/tree/4589a30ff139e143d6c57183ac62b5c029217a90
  5. //
  6. // solhint-disable no-console
  7. import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
  8. import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
  9. import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
  10. import {PackedUserOperation, IAccount, IEntryPoint} from "@openzeppelin/contracts/interfaces/draft-IERC4337.sol";
  11. import {ERC4337Utils} from "@openzeppelin/contracts/account/utils/draft-ERC4337Utils.sol";
  12. import {ERC7579Utils, Mode, CallType, ExecType, ModeSelector, ModePayload, Execution} from "@openzeppelin/contracts/account/utils/draft-ERC7579Utils.sol";
  13. import {Test, Vm, console} from "forge-std/Test.sol";
  14. contract SampleAccount is IAccount, Ownable {
  15. using ECDSA for *;
  16. using MessageHashUtils for *;
  17. using ERC4337Utils for *;
  18. using ERC7579Utils for *;
  19. IEntryPoint internal constant ENTRY_POINT = IEntryPoint(payable(0x0000000071727De22E5E9d8BAf0edAc6f37da032));
  20. event Log(bool duringValidation, Execution[] calls);
  21. error UnsupportedCallType(CallType callType);
  22. constructor(address initialOwner) Ownable(initialOwner) {}
  23. function validateUserOp(
  24. PackedUserOperation calldata userOp,
  25. bytes32 userOpHash,
  26. uint256 missingAccountFunds
  27. ) external override returns (uint256 validationData) {
  28. require(msg.sender == address(ENTRY_POINT), "only from EP");
  29. // Check signature
  30. if (userOpHash.toEthSignedMessageHash().recover(userOp.signature) != owner()) {
  31. revert OwnableUnauthorizedAccount(_msgSender());
  32. }
  33. // If this is an execute call with a batch operation, log the call details from the calldata
  34. if (bytes4(userOp.callData[0x00:0x04]) == this.execute.selector) {
  35. (CallType callType, , , ) = Mode.wrap(bytes32(userOp.callData[0x04:0x24])).decodeMode();
  36. if (callType == ERC7579Utils.CALLTYPE_BATCH) {
  37. // Remove the selector
  38. bytes calldata params = userOp.callData[0x04:];
  39. // Use the same vulnerable assignment technique here, but assert afterwards that the checks aren't
  40. // broken here by comparing to the result of `abi.decode(...)`.
  41. bytes calldata executionCalldata;
  42. assembly ("memory-safe") {
  43. let dataptr := add(params.offset, calldataload(add(params.offset, 0x20)))
  44. executionCalldata.offset := add(dataptr, 32)
  45. executionCalldata.length := calldataload(dataptr)
  46. }
  47. // Check that this decoding step is done correctly.
  48. (, bytes memory executionCalldataMemory) = abi.decode(params, (bytes32, bytes));
  49. require(
  50. keccak256(executionCalldata) == keccak256(executionCalldataMemory),
  51. "decoding during validation failed"
  52. );
  53. // Now, we know that we have `bytes calldata executionCalldata` as would be decoded by the solidity
  54. // builtin decoder for the `execute` function.
  55. // This is where the vulnerability from ExecutionLib results in a different result between validation
  56. // andexecution.
  57. emit Log(true, executionCalldata.decodeBatch());
  58. }
  59. }
  60. if (missingAccountFunds > 0) {
  61. (bool success, ) = payable(msg.sender).call{value: missingAccountFunds}("");
  62. success; // Silence warning. The entrypoint should validate the result.
  63. }
  64. return ERC4337Utils.SIG_VALIDATION_SUCCESS;
  65. }
  66. function execute(Mode mode, bytes calldata executionCalldata) external payable {
  67. require(msg.sender == address(this) || msg.sender == address(ENTRY_POINT), "not auth");
  68. (CallType callType, ExecType execType, , ) = mode.decodeMode();
  69. // check if calltype is batch or single
  70. if (callType == ERC7579Utils.CALLTYPE_SINGLE) {
  71. executionCalldata.execSingle(execType);
  72. } else if (callType == ERC7579Utils.CALLTYPE_BATCH) {
  73. executionCalldata.execBatch(execType);
  74. emit Log(false, executionCalldata.decodeBatch());
  75. } else if (callType == ERC7579Utils.CALLTYPE_DELEGATECALL) {
  76. executionCalldata.execDelegateCall(execType);
  77. } else {
  78. revert UnsupportedCallType(callType);
  79. }
  80. }
  81. }
  82. contract ERC7579UtilsTest is Test {
  83. using MessageHashUtils for *;
  84. using ERC4337Utils for *;
  85. using ERC7579Utils for *;
  86. IEntryPoint private constant ENTRYPOINT = IEntryPoint(payable(0x0000000071727De22E5E9d8BAf0edAc6f37da032));
  87. address private _owner;
  88. uint256 private _ownerKey;
  89. address private _account;
  90. address private _beneficiary;
  91. address private _recipient1;
  92. address private _recipient2;
  93. constructor() {
  94. vm.etch(0x0000000071727De22E5E9d8BAf0edAc6f37da032, vm.readFileBinary("test/bin/EntryPoint070.bytecode"));
  95. vm.etch(0xEFC2c1444eBCC4Db75e7613d20C6a62fF67A167C, vm.readFileBinary("test/bin/SenderCreator070.bytecode"));
  96. // signing key
  97. (_owner, _ownerKey) = makeAddrAndKey("owner");
  98. // ERC-4337 account
  99. _account = address(new SampleAccount(_owner));
  100. vm.deal(_account, 1 ether);
  101. // other
  102. _beneficiary = makeAddr("beneficiary");
  103. _recipient1 = makeAddr("recipient1");
  104. _recipient2 = makeAddr("recipient2");
  105. }
  106. function testExecuteBatchDecodeCorrectly() public {
  107. Execution[] memory calls = new Execution[](2);
  108. calls[0] = Execution({target: _recipient1, value: 1 wei, callData: ""});
  109. calls[1] = Execution({target: _recipient2, value: 1 wei, callData: ""});
  110. PackedUserOperation[] memory userOps = new PackedUserOperation[](1);
  111. userOps[0] = PackedUserOperation({
  112. sender: _account,
  113. nonce: 0,
  114. initCode: "",
  115. callData: abi.encodeCall(
  116. SampleAccount.execute,
  117. (
  118. ERC7579Utils.encodeMode(
  119. ERC7579Utils.CALLTYPE_BATCH,
  120. ERC7579Utils.EXECTYPE_DEFAULT,
  121. ModeSelector.wrap(0x00),
  122. ModePayload.wrap(0x00)
  123. ),
  124. ERC7579Utils.encodeBatch(calls)
  125. )
  126. ),
  127. accountGasLimits: _packGas(500_000, 500_000),
  128. preVerificationGas: 0,
  129. gasFees: _packGas(1, 1),
  130. paymasterAndData: "",
  131. signature: ""
  132. });
  133. (uint8 v, bytes32 r, bytes32 s) = vm.sign(
  134. _ownerKey,
  135. this.hashUserOperation(userOps[0]).toEthSignedMessageHash()
  136. );
  137. userOps[0].signature = abi.encodePacked(r, s, v);
  138. vm.recordLogs();
  139. ENTRYPOINT.handleOps(userOps, payable(_beneficiary));
  140. assertEq(_recipient1.balance, 1 wei);
  141. assertEq(_recipient2.balance, 1 wei);
  142. _collectAndPrintLogs(false);
  143. }
  144. function testExecuteBatchDecodeEmpty() public {
  145. bytes memory fakeCalls = abi.encodePacked(
  146. uint256(1), // Length of execution[]
  147. uint256(0x20), // offset
  148. uint256(uint160(_recipient1)), // target
  149. uint256(1), // value: 1 wei
  150. uint256(0x60), // offset of data
  151. uint256(0) // length of
  152. );
  153. PackedUserOperation[] memory userOps = new PackedUserOperation[](1);
  154. userOps[0] = PackedUserOperation({
  155. sender: _account,
  156. nonce: 0,
  157. initCode: "",
  158. callData: abi.encodeCall(
  159. SampleAccount.execute,
  160. (
  161. ERC7579Utils.encodeMode(
  162. ERC7579Utils.CALLTYPE_BATCH,
  163. ERC7579Utils.EXECTYPE_DEFAULT,
  164. ModeSelector.wrap(0x00),
  165. ModePayload.wrap(0x00)
  166. ),
  167. abi.encodePacked(
  168. uint256(0x70) // fake offset pointing to paymasterAndData
  169. )
  170. )
  171. ),
  172. accountGasLimits: _packGas(500_000, 500_000),
  173. preVerificationGas: 0,
  174. gasFees: _packGas(1, 1),
  175. paymasterAndData: abi.encodePacked(address(0), fakeCalls),
  176. signature: ""
  177. });
  178. (uint8 v, bytes32 r, bytes32 s) = vm.sign(
  179. _ownerKey,
  180. this.hashUserOperation(userOps[0]).toEthSignedMessageHash()
  181. );
  182. userOps[0].signature = abi.encodePacked(r, s, v);
  183. vm.expectRevert(
  184. abi.encodeWithSelector(
  185. IEntryPoint.FailedOpWithRevert.selector,
  186. 0,
  187. "AA23 reverted",
  188. abi.encodeWithSelector(ERC7579Utils.ERC7579DecodingError.selector)
  189. )
  190. );
  191. ENTRYPOINT.handleOps(userOps, payable(_beneficiary));
  192. _collectAndPrintLogs(false);
  193. }
  194. function testExecuteBatchDecodeDifferent() public {
  195. bytes memory execCallData = abi.encodePacked(
  196. uint256(0x20), // offset pointing to the next segment
  197. uint256(5), // Length of execution[]
  198. uint256(0), // offset of calls[0], and target (!!)
  199. uint256(0x20), // offset of calls[1], and value (!!)
  200. uint256(0), // offset of calls[2], and rel offset of data (!!)
  201. uint256(0) // offset of calls[3].
  202. // There is one more to read by the array length, but it's not present here. This will be
  203. // paymasterAndData.length during validation, pointing to an all-zero call.
  204. // During execution, the offset will be 0, pointing to a call with value.
  205. );
  206. PackedUserOperation[] memory userOps = new PackedUserOperation[](1);
  207. userOps[0] = PackedUserOperation({
  208. sender: _account,
  209. nonce: 0,
  210. initCode: "",
  211. callData: abi.encodePacked(
  212. SampleAccount.execute.selector,
  213. ERC7579Utils.encodeMode(
  214. ERC7579Utils.CALLTYPE_BATCH,
  215. ERC7579Utils.EXECTYPE_DEFAULT,
  216. ModeSelector.wrap(0x00),
  217. ModePayload.wrap(0x00)
  218. ),
  219. uint256(0x5c), // offset pointing to the next segment
  220. uint224(type(uint224).max), // Padding to align the `bytes` types
  221. // type(uint256).max, // unknown padding
  222. uint256(execCallData.length), // Length of the data
  223. execCallData
  224. ),
  225. accountGasLimits: _packGas(500_000, 500_000),
  226. preVerificationGas: 0,
  227. gasFees: _packGas(1, 1),
  228. paymasterAndData: abi.encodePacked(uint256(0), uint256(0)), // padding length to create an offset
  229. signature: ""
  230. });
  231. (uint8 v, bytes32 r, bytes32 s) = vm.sign(
  232. _ownerKey,
  233. this.hashUserOperation(userOps[0]).toEthSignedMessageHash()
  234. );
  235. userOps[0].signature = abi.encodePacked(r, s, v);
  236. vm.expectRevert(
  237. abi.encodeWithSelector(
  238. IEntryPoint.FailedOpWithRevert.selector,
  239. 0,
  240. "AA23 reverted",
  241. abi.encodeWithSelector(ERC7579Utils.ERC7579DecodingError.selector)
  242. )
  243. );
  244. ENTRYPOINT.handleOps(userOps, payable(_beneficiary));
  245. _collectAndPrintLogs(true);
  246. }
  247. function testDecodeBatch() public {
  248. // BAD: buffer empty
  249. vm.expectRevert(ERC7579Utils.ERC7579DecodingError.selector);
  250. this.callDecodeBatch("");
  251. // BAD: buffer too short
  252. vm.expectRevert(ERC7579Utils.ERC7579DecodingError.selector);
  253. this.callDecodeBatch(abi.encodePacked(uint128(0)));
  254. // GOOD
  255. this.callDecodeBatch(abi.encode(0));
  256. // Note: Solidity also supports this even though it's odd. Offset 0 means array is at the same location, which
  257. // is interpreted as an array of length 0, which doesn't require any more data
  258. // solhint-disable-next-line var-name-mixedcase
  259. uint256[] memory _1 = abi.decode(abi.encode(0), (uint256[]));
  260. _1;
  261. // BAD: offset is out of bounds
  262. vm.expectRevert(ERC7579Utils.ERC7579DecodingError.selector);
  263. this.callDecodeBatch(abi.encode(1));
  264. // GOOD
  265. this.callDecodeBatch(abi.encode(32, 0));
  266. // BAD: reported array length extends beyond bounds
  267. vm.expectRevert(ERC7579Utils.ERC7579DecodingError.selector);
  268. this.callDecodeBatch(abi.encode(32, 1));
  269. // GOOD
  270. this.callDecodeBatch(abi.encode(32, 1, 0));
  271. // GOOD
  272. //
  273. // 0000000000000000000000000000000000000000000000000000000000000020 (32) offset
  274. // 0000000000000000000000000000000000000000000000000000000000000001 ( 1) array length
  275. // 0000000000000000000000000000000000000000000000000000000000000020 (32) element 0 offset
  276. // 000000000000000000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (recipient) target for element #0
  277. // 000000000000000000000000000000000000000000000000000000000000002a (42) value for element #0
  278. // 0000000000000000000000000000000000000000000000000000000000000060 (96) offset to calldata for element #0
  279. // 000000000000000000000000000000000000000000000000000000000000000c (12) length of the calldata for element #0
  280. // 48656c6c6f20576f726c64210000000000000000000000000000000000000000 (..) buffer for the calldata for element #0
  281. assertEq(
  282. bytes("Hello World!"),
  283. this.callDecodeBatchAndGetFirstBytes(
  284. abi.encode(32, 1, 32, _recipient1, 42, 96, 12, bytes12("Hello World!"))
  285. )
  286. );
  287. // This is invalid, the first element of the array points is out of bounds
  288. // but we allow it past initial validation, because solidity will validate later when the bytes field is accessed
  289. //
  290. // 0000000000000000000000000000000000000000000000000000000000000020 (32) offset
  291. // 0000000000000000000000000000000000000000000000000000000000000001 ( 1) array length
  292. // 0000000000000000000000000000000000000000000000000000000000000020 (32) element 0 offset
  293. // <missing element>
  294. bytes memory invalid = abi.encode(32, 1, 32);
  295. this.callDecodeBatch(invalid);
  296. vm.expectRevert();
  297. this.callDecodeBatchAndGetFirst(invalid);
  298. // this is invalid: the bytes field of the first element of the array is out of bounds
  299. // but we allow it past initial validation, because solidity will validate later when the bytes field is accessed
  300. //
  301. // 0000000000000000000000000000000000000000000000000000000000000020 (32) offset
  302. // 0000000000000000000000000000000000000000000000000000000000000001 ( 1) array length
  303. // 0000000000000000000000000000000000000000000000000000000000000020 (32) element 0 offset
  304. // 000000000000000000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (recipient) target for element #0
  305. // 000000000000000000000000000000000000000000000000000000000000002a (42) value for element #0
  306. // 0000000000000000000000000000000000000000000000000000000000000060 (96) offset to calldata for element #0
  307. // <missing data>
  308. bytes memory invalidDeeply = abi.encode(32, 1, 32, _recipient1, 42, 96);
  309. this.callDecodeBatch(invalidDeeply);
  310. // Note that this is ok because we don't return the value. Returning it would introduce a check that would fails.
  311. this.callDecodeBatchAndGetFirst(invalidDeeply);
  312. vm.expectRevert();
  313. this.callDecodeBatchAndGetFirstBytes(invalidDeeply);
  314. }
  315. function callDecodeBatch(bytes calldata executionCalldata) public pure {
  316. ERC7579Utils.decodeBatch(executionCalldata);
  317. }
  318. function callDecodeBatchAndGetFirst(bytes calldata executionCalldata) public pure {
  319. ERC7579Utils.decodeBatch(executionCalldata)[0];
  320. }
  321. function callDecodeBatchAndGetFirstBytes(bytes calldata executionCalldata) public pure returns (bytes calldata) {
  322. return ERC7579Utils.decodeBatch(executionCalldata)[0].callData;
  323. }
  324. function hashUserOperation(PackedUserOperation calldata useroperation) public view returns (bytes32) {
  325. return useroperation.hash(address(ENTRYPOINT), block.chainid);
  326. }
  327. function _collectAndPrintLogs(bool includeTotalValue) internal {
  328. Vm.Log[] memory logs = vm.getRecordedLogs();
  329. for (uint256 i = 0; i < logs.length; i++) {
  330. if (logs[i].emitter == _account) {
  331. _printDecodedCalls(logs[i].data, includeTotalValue);
  332. }
  333. }
  334. }
  335. function _printDecodedCalls(bytes memory logData, bool includeTotalValue) internal pure {
  336. (bool duringValidation, Execution[] memory calls) = abi.decode(logData, (bool, Execution[]));
  337. console.log(
  338. string.concat(
  339. "Batch execute contents, as read during ",
  340. duringValidation ? "validation" : "execution",
  341. ": "
  342. )
  343. );
  344. console.log(" Execution[] length: %s", calls.length);
  345. uint256 totalValue = 0;
  346. for (uint256 i = 0; i < calls.length; ++i) {
  347. console.log(string.concat(" calls[", vm.toString(i), "].target = ", vm.toString(calls[i].target)));
  348. console.log(string.concat(" calls[", vm.toString(i), "].value = ", vm.toString(calls[i].value)));
  349. console.log(string.concat(" calls[", vm.toString(i), "].data = ", vm.toString(calls[i].callData)));
  350. totalValue += calls[i].value;
  351. }
  352. if (includeTotalValue) {
  353. console.log(" Total value: %s", totalValue);
  354. }
  355. }
  356. function _packGas(uint256 upper, uint256 lower) internal pure returns (bytes32) {
  357. return bytes32(uint256((upper << 128) | uint128(lower)));
  358. }
  359. }