draft-ERC7579Utils.t.sol 18 KB

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