Skip to content

Commit 9ce0340

Browse files
committed
Make Multicall context-aware
1 parent 4eb67a4 commit 9ce0340

File tree

7 files changed

+111
-13
lines changed

7 files changed

+111
-13
lines changed

.changeset/rude-weeks-beg.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': patch
3+
---
4+
5+
`ERC2771Context` and `Context`: Introduce a `_contextPrefixLength()` getter, used to trim extra information appended to `msg.data`.

.changeset/strong-points-invent.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': patch
3+
---
4+
5+
`Multicall`: Make aware of non-canonical context (i.e. `msg.sender` is not `_msgSender()`), allowing compatibility with `ERC2771Context`.

contracts/metatx/ERC2771Context.sol

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ import {Context} from "../utils/Context.sol";
1313
* specification adding the address size in bytes (20) to the calldata size. An example of an unexpected
1414
* behavior could be an unintended fallback (or another function) invocation while trying to invoke the `receive`
1515
* function only accessible if `msg.data.length == 0`.
16+
*
17+
* WARNING: The usage of `delegatecall` in this contract is dangerous and may result in context corruption.
18+
* Any forwarded request to this contract triggering a `delegatecall` to itself will result in an invalid {_msgSender}
19+
* recovery.
1620
*/
1721
abstract contract ERC2771Context is Context {
1822
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
@@ -48,13 +52,11 @@ abstract contract ERC2771Context is Context {
4852
* a call is not performed by the trusted forwarder or the calldata length is less than
4953
* 20 bytes (an address length).
5054
*/
51-
function _msgSender() internal view virtual override returns (address sender) {
52-
if (isTrustedForwarder(msg.sender) && msg.data.length >= 20) {
53-
// The assembly code is more direct than the Solidity version using `abi.decode`.
54-
/// @solidity memory-safe-assembly
55-
assembly {
56-
sender := shr(96, calldataload(sub(calldatasize(), 20)))
57-
}
55+
function _msgSender() internal view virtual override returns (address) {
56+
uint256 calldataLength = msg.data.length;
57+
uint256 contextSuffixLength = _contextSuffixLength();
58+
if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) {
59+
return address(bytes20(msg.data[calldataLength - contextSuffixLength:]));
5860
} else {
5961
return super._msgSender();
6062
}
@@ -66,10 +68,19 @@ abstract contract ERC2771Context is Context {
6668
* 20 bytes (an address length).
6769
*/
6870
function _msgData() internal view virtual override returns (bytes calldata) {
69-
if (isTrustedForwarder(msg.sender) && msg.data.length >= 20) {
70-
return msg.data[:msg.data.length - 20];
71+
uint256 calldataLength = msg.data.length;
72+
uint256 contextSuffixLength = _contextSuffixLength();
73+
if (isTrustedForwarder(msg.sender) && calldataLength >= contextSuffixLength) {
74+
return msg.data[:calldataLength - contextSuffixLength];
7175
} else {
7276
return super._msgData();
7377
}
7478
}
79+
80+
/**
81+
* @dev ERC-2771 specifies the context as being a single address (20 bytes).
82+
*/
83+
function _contextSuffixLength() internal view virtual override returns (uint256) {
84+
return 20;
85+
}
7586
}

contracts/mocks/ERC2771ContextMock.sol

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@ pragma solidity ^0.8.20;
44

55
import {ContextMock} from "./ContextMock.sol";
66
import {Context} from "../utils/Context.sol";
7+
import {Multicall} from "../utils/Multicall.sol";
78
import {ERC2771Context} from "../metatx/ERC2771Context.sol";
89

910
// By inheriting from ERC2771Context, Context's internal functions are overridden automatically
10-
contract ERC2771ContextMock is ContextMock, ERC2771Context {
11+
contract ERC2771ContextMock is ContextMock, ERC2771Context, Multicall {
1112
/// @custom:oz-upgrades-unsafe-allow constructor
1213
constructor(address trustedForwarder) ERC2771Context(trustedForwarder) {
1314
emit Sender(_msgSender()); // _msgSender() should be accessible during construction
@@ -20,4 +21,8 @@ contract ERC2771ContextMock is ContextMock, ERC2771Context {
2021
function _msgData() internal view override(Context, ERC2771Context) returns (bytes calldata) {
2122
return ERC2771Context._msgData();
2223
}
24+
25+
function _contextSuffixLength() internal view override(Context, ERC2771Context) returns (uint256) {
26+
return ERC2771Context._contextSuffixLength();
27+
}
2328
}

contracts/utils/Context.sol

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,8 @@ abstract contract Context {
2121
function _msgData() internal view virtual returns (bytes calldata) {
2222
return msg.data;
2323
}
24+
25+
function _contextSuffixLength() internal view virtual returns (uint256) {
26+
return 0;
27+
}
2428
}

contracts/utils/Multicall.sol

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,33 @@
44
pragma solidity ^0.8.20;
55

66
import {Address} from "./Address.sol";
7+
import {Context} from "./Context.sol";
78

89
/**
910
* @dev Provides a function to batch together multiple calls in a single external call.
11+
*
12+
* Consider any assumption about calldata validation performed by the sender may be violated if it's not especially
13+
* careful about sending transactions invoking {multicall}. For example, a relay address that filters function
14+
* selectors won't filter calls nested within a {multicall} operation.
15+
*
16+
* NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).
17+
* If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`
18+
* to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of
19+
* {_msgSender} are not propagated to subcalls.
1020
*/
11-
abstract contract Multicall {
21+
abstract contract Multicall is Context {
1222
/**
1323
* @dev Receives and executes a batch of function calls on this contract.
1424
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
1525
*/
1626
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
27+
bytes memory context = msg.sender == _msgSender()
28+
? new bytes(0)
29+
: msg.data[msg.data.length - _contextSuffixLength():];
30+
1731
results = new bytes[](data.length);
1832
for (uint256 i = 0; i < data.length; i++) {
19-
results[i] = Address.functionDelegateCall(address(this), data[i]);
33+
results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));
2034
}
2135
return results;
2236
}

test/metatx/ERC2771Context.test.js

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const ContextMockCaller = artifacts.require('ContextMockCaller');
1313
const { shouldBehaveLikeRegularContext } = require('../utils/Context.behavior');
1414

1515
contract('ERC2771Context', function (accounts) {
16-
const [, trustedForwarder] = accounts;
16+
const [, trustedForwarder, other] = accounts;
1717

1818
beforeEach(async function () {
1919
this.forwarder = await ERC2771Forwarder.new('ERC2771Forwarder');
@@ -131,4 +131,58 @@ contract('ERC2771Context', function (accounts) {
131131
await expectEvent(receipt, 'DataShort', { data });
132132
});
133133
});
134+
135+
it('multicall poison attack', async function () {
136+
const attacker = Wallet.generate();
137+
const attackerAddress = attacker.getChecksumAddressString();
138+
const nonce = await this.forwarder.nonces(attackerAddress);
139+
140+
const msgSenderCall = web3.eth.abi.encodeFunctionCall(
141+
{
142+
name: 'msgSender',
143+
type: 'function',
144+
inputs: [],
145+
},
146+
[],
147+
);
148+
149+
const data = web3.eth.abi.encodeFunctionCall(
150+
{
151+
name: 'multicall',
152+
type: 'function',
153+
inputs: [
154+
{
155+
internalType: 'bytes[]',
156+
name: 'data',
157+
type: 'bytes[]',
158+
},
159+
],
160+
},
161+
[[web3.utils.encodePacked({ value: msgSenderCall, type: 'bytes' }, { value: other, type: 'address' })]],
162+
);
163+
164+
const req = {
165+
from: attackerAddress,
166+
to: this.recipient.address,
167+
value: '0',
168+
gas: '100000',
169+
data,
170+
nonce: Number(nonce),
171+
deadline: MAX_UINT48,
172+
};
173+
174+
req.signature = await ethSigUtil.signTypedMessage(attacker.getPrivateKey(), {
175+
data: {
176+
types: this.types,
177+
domain: this.domain,
178+
primaryType: 'ForwardRequest',
179+
message: req,
180+
},
181+
});
182+
183+
expect(await this.forwarder.verify(req)).to.equal(true);
184+
185+
const receipt = await this.forwarder.execute(req);
186+
await expectEvent.inTransaction(receipt.tx, ERC2771ContextMock, 'Sender', { sender: attackerAddress });
187+
});
134188
});

0 commit comments

Comments
 (0)