draft-ERC7579Utils.t.sol 18 KB

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