Nonce can be manipulated by inserting a contract creation EthereumTx message first in an SDK TX with multiple EthereumTX messages
The nonce handling for Ethereum transactions in Nibiru allowed a user to include multiple EVM messages in one SDK transaction, where a contract creation message would reset the account nonce, enabling replay of subsequent messages. An attacker could reuse nonces to replay their own transactions.
The Ante handler for MsgEthereumTx transactions is responsible for ensuring messages are coming with correct nonces. After doing so, it’ll increment the account’s sequences for each message that the account has signed and broadcasted.
The problem is that when the EthereumTx() message server method calls ApplyEvmMsg() it’ll override the account nonce when the currently processed EVM transaction message is a contract creation and will set it to the nonce of the message. When a non-contract creation EVM transaction message is processed, however, the ApplyEvmMsg() method does not touch the account’s nonce.
This opens up an exploit window where a malicious user can replay a TX multiple times and reuse their nonces. Users can manipulate their Sequence (nonce) by submitting a contract creation EVM transaction message and multiple call/transfer EVM transaction messages in a single SDK transaction.
The code relies on evmObj.Call() and later stateDB.commitCtx() to persist a correct nonce in state but the Call() method on evmObj does not handle account nonces, it just executes the transaction. As we can see the method in geth that’s normally used to transition the state increments the sender’s nonce by 1 in either case:
func (evm *EVM) create(caller ContractRef, codeAndHash *codeAndHash, gas uint64, value *big.Int, address common.Address, typ OpCode) ([]byte, common.Address, uint64, error) {
// Depth check execution. Fail if we're trying to execute above the
// limit.
if evm.depth > int(params.CallCreateDepth) {
return nil, common.Address{}, gas, ErrDepth
}
if !evm.Context.CanTransfer(evm.StateDB, caller.Address(), value) {
return nil, common.Address{}, gas, ErrInsufficientBalance
}
nonce := evm.StateDB.GetNonce(caller.Address())
if nonce+1 < nonce {
return nil, common.Address{}, gas, ErrNonceUintOverflow
}
evm.StateDB.SetNonce(caller.Address(), nonce+1)
But ApplyEvmMsg() calls evmObj.Call() (st.evm.Call() in the above code snippet) directly and does not increment sender’s nonce:
if contractCreation {
// take over the nonce management from evm:
// - reset sender's nonce to msg.Nonce() before calling evm.
// - increase sender's nonce by one no matter the result.
stateDB.SetNonce(sender.Address(), msg.Nonce())
ret, _, leftoverGas, vmErr = evmObj.Create(
sender,
msg.Data(),
leftoverGas,
msgWei,
)
stateDB.SetNonce(sender.Address(), msg.Nonce()+1)
} else {
ret, leftoverGas, vmErr = evmObj.Call(
sender,
*msg.To(),
msg.Data(),
leftoverGas,
msgWei,
)
}
Proof of Concept
User constructs an SDK transaction with 4 MsgEthereumTx messages in it.
The first message is an EVM transaction that creates a new contract and has a nonce 1.
The next three messages are also EVM transactions that transfer ether (unibi as its the native unit of account in Nibiru’s EVM) or just call some contracts.
The three messages have nonces of 2, 3 and 4.
The user broadcasts the SDK transaction. It passes validation through the Ante handler and is included in the mempool.
The TX is picked up to be processed by the DeliverTx() method and the Ante handler is called again.
The Ante handler increments the MsgEthereumTx message sender’s sequence (nonce) for each EVM transaction message.
User’s sequence (nonce) in their SDK x/auth account is currently 5 (the next consecutive ready-for-use nonce).
ApplyEvmMsg() is called to process the first EVM transaction message and since it’s a contract creation transaction it sets the sender’s sequence (nonce) to msg.Nonce() + 1. After running the transaction through the geth interpreter, the account stateObject properties (like nonce, code hash and account state) are persisted to the x/evm module keeper’s storage by calling stateDB.Commit(). The user account’s Sequence is now reset to msg.Nonce() + 1 (equal to 2).
The remaining three messages with nonces (2, 3, and 4) are then executed but the user’s sequence (nonce) is still at 2.
User can now replay their last three messages.
SDK TX Message # | Contract creation | Message nonce | Account sequence set by ante handler | Account sequence after execution |
190: // GetMsgs returns a single MsgEthereumTx as sdk.Msg.
191: func (msg *MsgEthereumTx) GetMsgs() []sdk.Msg {
192: return []sdk.Msg{msg}
193: }
However, that’s not the correct GetMsgs(). In fact, multiple EVM messages within a single Cosmos tx are supported. As a result, the demonstrated issue is valid, allowing replaying a user’s EVM messages in this specific scenario. That’s a great catch!
I’d argue the side of sponsor-disputed here, similar to @onikonychev. When every transaction goes through execution via the DeliverTx ABCI (application blockchain interface) method. The implementation details of this function can be seen in BaseApp.runTx from the Cosmos-SDK baseapp/bapp.go code that, as it implements much of the non-consensus side of the ABCI.
In BaseApp.runTx, it first gets each message and calls ValidateBasic on them, then it enters the BaseApp.anteHandler before beginning any other logic with the tx msgs.
Note: to view the provided image, please see the original comment here.
The Nibiru ante handler, instantiated with NewAnteHandler in Nibiru/app/ante.go splits a tx down different paths of potential ante handlers.
You can see below that, if a tx (sdk.Tx) comes in and has the properties indicating it’s an sdk.Tx that is also a MsgEthereumTx, then it passes through an EVM ante handler (evmante.NewAnteHandlerEVM).
If however, the sdk.Tx is anything else, it goes through a non-EVM ante handler (NewAnteHandlerNonEVM), which you’ll see has the very first sdk.ChainAnteDecorator hook as a blocker that disallows the execution of the sdk.Tx if any of the contained messages are evm.MsgEthereumTx instances.
Note: Thus, it is not possible to insert a contract creation EthereumTx message in a non-EVM sdk.Tx with multiple EthereumTx messages because that type of tx would be rejected in the ante handler, even if there was only one MsgEthereumTx contained in the sdk.Tx
// NewAnteHandler returns and AnteHandler that checks and increments sequence
// numbers, checks signatures and account numbers, and deducts fees from the
// first signer.
func NewAnteHandler(
keepers AppKeepers,
options ante.AnteHandlerOptions,
) sdk.AnteHandler {
return func(
ctx sdk.Context, tx sdk.Tx, sim bool,
) (newCtx sdk.Context, err error) {
if err := options.ValidateAndClean(); err != nil {
return ctx, err
}
var anteHandler sdk.AnteHandler
txWithExtensions, ok := tx.(authante.HasExtensionOptionsTx)
if ok {
opts := txWithExtensions.GetExtensionOptions()
if len(opts) > 0 {
switch typeURL := opts[0].GetTypeUrl(); typeURL {
case "/eth.evm.v1.ExtensionOptionsEthereumTx":
// handle as *evmtypes.MsgEthereumTx
anteHandler = evmante.NewAnteHandlerEVM(options)
default:
return ctx, fmt.Errorf(
"rejecting tx with unsupported extension option: %s", typeURL)
}
return anteHandler(ctx, tx, sim)
}
}
switch tx.(type) {
case sdk.Tx:
anteHandler = NewAnteHandlerNonEVM(options)
default:
return ctx, fmt.Errorf("invalid tx type (%T) in AnteHandler", tx)
}
return anteHandler(ctx, tx, sim)
}
}
Why is this confusing at first glance?
The term transaction is overused in Web3 and means different things in the EVM context than in the ABCI/Cosmos-SDK context. An Ethereum tx can contain several Ethereum txs inside it. In other words, what’s called a tx msg or simply a “message” in the ABCI is what’s analogous to the idea of an Ethereum Tx, not the sdk.Tx.
MsgEthereumTx is meant to represent a true “Ethereum tx” like on the Eth L1. That means, a MsgEthereumTx may induce one or more inner Ethereum txs; however, they’ll only be still only occur within that single MsgEthereumTx.
@Unique-Divine - this issue is about multiple EVM messages within a single Cosmos TX. It’s not mixing EVM and regular msg’s; therefore, the EVM ante handler is used. It can, however, be argued on the severity.
The matter really is about putting multiple EVM transactions in a single SDK transaction. In this POC the two contract call transactions are replayable as the nonce got incremented only once because of how ApplyEvmMsg handles the nonce.
The original report as published on Code4rena, by Sentryx. 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.
Generating the AI write-up for this report.
This usually takes about 30 seconds. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
How it worked
Root cause
Likely, the ApplyEvmMsg function only updates the sender's nonce for contract creation transactions, not for regular calls, so when multiple EVM messages are in one SDK transaction, the nonce is not incremented correctly for non-creation messages.
Impact
A user could replay their own EVM messages, potentially causing unintended repeated actions, but the impact is limited to the user's own transactions and was rated Medium severity.
What the attacker needed
Ability to submit an SDK transaction with multiple EVM…
The fix
The sender's nonce should be set to msg.Nonce() + 1 when contractCreation is false, and the project mitigated the issue with a pull request for proper nonce management.
How it was found
Construct an SDK transaction with four MsgEthereumTx messages.
Set the first message as a contract creation with nonce 1.
Set the next three messages as transfers or calls with nonces 2, 3, and 4.
Broadcast the SDK transaction; it passes validation and is included in the mempool.
The transaction is processed, and the Ante handler increments the sender's sequence for each message.
ApplyEvmMsg processes the first message, resetting the account nonce to 2, and the remaining messages execute without updating the nonce, allowing replay.
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.
Generating the AI write-up for this report.
This usually takes about 30 seconds. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
In blockchain systems, a nonce is a number that ensures each transaction is processed only once. This report found that by bundling several Ethereum transactions into one larger transaction, a user could make the system lose track of the nonce, allowing some transactions to be replayed.
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.