Skip to content
Smart contracts Write-up Advanced

[web3] Exploiting Signature Verification Vulnerabilities in Smart Contracts | by Heuss | Jan, 2024 | Medium

A cross-chain messaging protocol stored a commitment with a threshold of zero when a new domain was added, because the threshold was set after enrolling a validator. An attacker could front-run the threshold-setting transaction and submit a message with a zero threshold, bypassing signature verification entirely.

medium.com

Published on medium.com

Smart Contract Security

Heuss, on medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 5 min read.

Context

This write-up covers a finding in an Immunefi bug bounty program: a flaw in the signature verification process of a cross-chain messaging protocol. The protocol keeps a separate validator set and threshold for each supported chain (domain), and stores a commitment for each domain. The commitment is the hash of the validator set plus the threshold, and it is used to check the authenticity of the validator set before signature verification runs, because the metadata used during verification is supplied by the user.

Signature verification itself is a cryptographic process used to confirm the authenticity and integrity of a message. A submitted message carries a cryptographic signature generated by one or more authorised validators. The contract recovers the signers with the corresponding public keys and checks that the required number of valid signatures meets the threshold. If it does, the message is considered legitimate and can be processed or executed.

The function that performs this work in the affected contract is _verifyValidatorSignatures:

Text
function _verifyValidatorSignatures(        bytes calldata _metadata,        bytes calldata _message    ) internal view returns (bool) {        uint8 _threshold = _metadata.threshold();        bytes32 _digest;        {
            uint32 _origin = _message.origin();
            bytes32 _commitment = keccak256(
                abi.encodePacked(_threshold, _metadata.validators())
            );
                      require(_commitment == commitment[_origin], "!commitment");
            _digest = _getCheckpointDigest(_metadata, _origin);
        }
        uint256 _validatorCount = _metadata.validatorCount();
        uint256 _validatorIndex = 0;
              for (uint256 i = 0; i < _threshold; ++i) {
            address _signer = ECDSA.recover(_digest, _metadata.signatureAt(i));
                        for (
                ;
                _validatorIndex < _validatorCount &&
                    _signer != _metadata.validatorAt(_validatorIndex);
                ++_validatorIndex
            ) {}
                      require(_validatorIndex < _validatorCount, "!threshold");
            ++_validatorIndex;
        }
        return true;
    }

The function reads the threshold from the user-supplied metadata, recomputes the commitment from that threshold and the supplied validator list, and requires it to match the stored commitment for the message origin. It then loops _threshold times, recovering a signer from each signature and walking the validator list to find a match. If every iteration finds a match, it returns true.

Setup

The target is a cross-chain messaging protocol deployed as a smart contract, with a per-domain validator set and threshold. The relevant roles are the contract owner, who calls enrollValidator and setThreshold when adding a new domain, and an unprivileged attacker who can submit messages to the contract. The report does not give contract addresses, chain names, compiler versions or tooling.

The precondition for the bug is the normal onboarding sequence for a new domain: validators are enrolled first, and the threshold is set afterwards.

Finding it

The problem is in how the contract handles the initial setting of the threshold when a new domain or chain is added. When a new domain is added, setThreshold, which sets the threshold value, is called separately and after enrollValidator, which enrols a new validator. Both functions update the commitment when called.

setThreshold is guaranteed to run after enrollValidator because of this requirement:

Text
require(            _threshold > 0 && _threshold <= validatorCount(_domain),            "!range"        );

The threshold must be at least 1 and no greater than the number of validators already enrolled for the domain, so at least one validator must exist before a valid threshold can be set.

enrollValidator enrols the validator and then refreshes the commitment:

Text
function enrollValidator(uint32 _domain, address _validator)        external        onlyOwner    {        _enrollValidator(_domain, _validator);        _updateCommitment(_domain);    }

setThreshold checks the range, stores the threshold, emits an event and refreshes the commitment:

Text
function setThreshold(uint32 _domain, uint8 _threshold) public onlyOwner {        require(            _threshold > 0 && _threshold <= validatorCount(_domain),            "!range"        );        threshold[_domain] = _threshold;        emit ThresholdSet(_domain, _threshold);        _updateCommitment(_domain);    }

_updateCommitment hashes the current threshold and validator list for the domain and stores the result:

Text
function _updateCommitment(uint32 _domain) internal returns (bytes32) {        address[] memory _validators = validators(_domain);        uint8 _threshold = threshold[_domain];        bytes32 _commitment = keccak256(            abi.encodePacked(_threshold, _validators)        );
        commitment[_domain] = _commitment;
        emit CommitmentUpdated(_domain, _commitment);
        return _commitment;
    }

Because setThreshold has not been called before a validator is enrolled for the new domain, _threshold is still the default value of 0 at that point. The commitment computed with _threshold == 0 is written to the contract before setThreshold runs, and it becomes a permanent state. That incorrect commitment can then affect signature verification across the whole contract and lead to a bypass of the verification logic.

When _verifyValidatorSignatures runs with a threshold of 0, the loop for (uint256 i = 0; i < _threshold; ++i) is never entered, so the function returns true unconditionally. The signature verification process is effectively circumvented.

Exploitation

The attacker uses a frontrunning attack. The steps are:

  1. Wait for the team to add a new domain to support.
  2. Observe the enrollValidators transaction, which enrols the new validator without setting the threshold.
  3. Frontrun the setThreshold transaction by calling Process in the contract with a malicious message targeting protocols that use this cross-chain messaging system. Process calls _verifySignature before processing the message.
  4. In the malicious message metadata, set _metadata.threshold() to 0 and use the validator addresses previously sent by the team during the enrollValidators transaction.
  5. The require(_commitment == commitment[_origin], "!commitment") check passes because the commitment with _threshold == 0 is stored in the contract.
  6. Since the threshold is 0, the signature verification loop is not entered, and the message is processed without proper signature validation.

The report does not include the raw transaction, the message payload or the metadata bytes.

Root cause

The commitment is refreshed by both enrollValidator and setThreshold, but the ordering forced by the !range check means the first refresh happens while the threshold is still the default 0. That zero-threshold commitment is stored and never corrected until setThreshold runs, and during that window it matches any metadata that declares a threshold of 0 with the enrolled validator list. The verification loop is bounded by the user-supplied threshold, so a threshold of 0 skips the loop entirely and the function returns true. The commitment check, which is meant to authenticate the validator set, therefore authenticates a set whose declared threshold is 0.

Impact

An attacker can bypass signature verification and process malicious, unsigned messages in multiple protocols that use this contract. The report states this can lead to unauthorised actions, fund theft or other harmful consequences, affecting the integrity of affected systems.

Fix

The recommendation was to add a custom error to _verifyValidatorSignatures: if _threshold is equal to 0, the transaction should revert with an error message indicating that the threshold must be a non-zero value. The report does not say whether the project implemented this.

Variants to test

  1. Look for any per-domain or per-tenant configuration where a commitment, hash or cache is refreshed by more than one setter and one of them can run before the others. A positive result is a stored commitment that matches a configuration with a default or zero value.
  2. Check verification loops bounded by a value taken from user-supplied metadata. A positive result is a metadata value of 0 that skips the loop and returns success.
  3. Watch onboarding transactions for new domains, chains or validator sets and compare the state between the enrolment transaction and the configuration transaction. A positive result is a commitment that can be matched with a zero threshold during that window.
  4. Test whether Process or equivalent entry points can be called by anyone during onboarding, which is what makes the frontrun possible.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 14 min read.

What happened, in plain words

A security researcher found a bug in a smart contract that is used to send messages between different blockchains. The contract is supposed to check that a message really comes from the people who are allowed to approve messages (called validators). Because of a mistake in how the contract sets up a new blockchain it supports, an attacker could send a fake message that the contract would accept without any approval at all. The researcher reported it through a bug bounty programme on Immunefi, where companies pay people for finding security problems. The report does not say how much was paid or whether the fix was applied.

This article explains the whole thing from scratch. You do not need to know anything about blockchains or programming to follow it. Every technical word is explained the first time it appears, and there is a glossary at the end.

Background: what a smart contract and a blockchain are

A blockchain is a shared record book that many computers keep copies of. Once something is written into it, it is very hard to change. People use blockchains to move money and to run programs that everyone can see and check.

A smart contract is a program that lives on a blockchain. It runs automatically when someone sends it a request. Think of it like a vending machine: you put in a request, the machine checks the rules written into it, and then it either does the thing or refuses. Nobody can secretly change the rules afterwards, and anyone can read the code.

A cross-chain messaging protocol is a system that lets one blockchain talk to another. Blockchains normally cannot see each other, so a protocol like this acts as a courier: a message is created on chain A, and the protocol delivers it to chain B, where it triggers some action. Because the courier is trusted with important instructions, it must be very sure that a message is genuine before delivering it.

What signature verification is

Signature verification is a way of proving that a message really came from the person or group who claims to have sent it, and that nobody changed it on the way. It uses cryptography, which is mathematics used to keep information secret and to prove who sent what.

Here is an everyday comparison. Imagine a company that requires three managers to sign every payment order. The bank receives the order with three signatures and compares them against the signatures it has on file. If three valid signatures are there, the bank pays. If someone photocopies one signature or forges one, the bank refuses.

In the blockchain world, the signatures are long strings of characters produced by special mathematical keys. Each validator has a private key (a secret number only they know) and a public key (a number everyone can see, mathematically linked to the private key). A signature made with the private key can be checked with the public key, but you cannot work out the private key from the public one.

A validator is one of the trusted parties whose job is to approve messages. A threshold is the minimum number of validators who must approve a message before it counts. If the threshold is 3, you need 3 valid signatures.

When a message is submitted to the contract, it carries a signature generated by one or more authorised validators. The contract uses the corresponding public keys to check the signatures. If the required number of valid signatures meets the threshold, the message is considered legitimate and can be processed or executed.

The function that does the checking

In the affected contract, the work of checking signatures is done by a function called _verifyValidatorSignatures. A function is a named block of code inside a program; you can think of it as a recipe with a name, which takes some ingredients (inputs) and produces a result.

Text
function _verifyValidatorSignatures(        bytes calldata _metadata,        bytes calldata _message    ) internal view returns (bool) {        uint8 _threshold = _metadata.threshold();        bytes32 _digest;        {
            uint32 _origin = _message.origin();
            bytes32 _commitment = keccak256(
                abi.encodePacked(_threshold, _metadata.validators())
            );
                      require(_commitment == commitment[_origin], "!commitment");
            _digest = _getCheckpointDigest(_metadata, _origin);
        }
        uint256 _validatorCount = _metadata.validatorCount();
        uint256 _validatorIndex = 0;
              for (uint256 i = 0; i < _threshold; ++i) {
            address _signer = ECDSA.recover(_digest, _metadata.signatureAt(i));
                        for (
                ;
                _validatorIndex < _validatorCount &&
                    _signer != _metadata.validatorAt(_validatorIndex);
                ++_validatorIndex
            ) {}
                      require(_validatorIndex < _validatorCount, "!threshold");
            ++_validatorIndex;
        }
        return true;
    }

Line by line, in plain words:

  1. function _verifyValidatorSignatures(bytes calldata _metadata, bytes calldata _message) internal view returns (bool) declares the function. It takes two inputs: _metadata (extra information about the message, supplied by whoever submits it) and _message (the message itself). internal view means it can only be called from inside the contract and it does not change any stored data. returns (bool) means it gives back a yes or no answer.
  2. uint8 _threshold = _metadata.threshold(); reads the threshold number out of the metadata. The metadata is supplied by the user, so this number is not trusted yet.
  3. bytes32 _digest; creates an empty slot to hold a fingerprint of the message, which will be filled in shortly.
  4. uint32 _origin = _message.origin(); reads which chain the message claims to come from. The contract keeps separate validator lists for each chain, so it needs to know which list to use.
  5. bytes32 _commitment = keccak256(abi.encodePacked(_threshold, _metadata.validators())); builds a fingerprint (a hash, explained below) out of the threshold and the list of validators supplied in the metadata.
  6. require(_commitment == commitment[_origin], "!commitment"); compares that freshly built fingerprint with the one the contract has stored for that chain. If they differ, the whole transaction is cancelled with the error message !commitment. This is the check that is supposed to stop someone from inventing their own validator list.
  7. _digest = _getCheckpointDigest(_metadata, _origin); computes the fingerprint of the message that the signatures are supposed to cover.
  8. uint256 _validatorCount = _metadata.validatorCount(); and uint256 _validatorIndex = 0; set up a counter for how many validators there are and a position marker for walking through the list.
  9. for (uint256 i = 0; i < _threshold; ++i) { starts a loop that runs once for each required signature. If the threshold is 3, it runs three times. If the threshold is 0, it runs zero times, which is the heart of the bug.
  10. address _signer = ECDSA.recover(_digest, _metadata.signatureAt(i)); takes the i-th signature and works out which address produced it. ECDSA is the standard mathematical scheme used for these signatures, and recover means working backwards from a signature to the address that made it.
  11. The inner for loop walks through the validator list looking for that address. It stops when it finds a match or runs out of validators.
  12. require(_validatorIndex < _validatorCount, "!threshold"); fails the transaction if the signer was not found in the list, meaning the signature came from someone who is not a validator.
  13. ++_validatorIndex; moves the position marker forward so the same validator cannot be counted twice.
  14. return true; says the message is approved. If the loop never ran, this line is reached immediately.

A hash (here produced by keccak256) is a mathematical fingerprint. You feed it any amount of data and it produces a fixed-length string. Change even one character of the input and the fingerprint changes completely. You cannot work backwards from the fingerprint to the original data. It is used to compare large things quickly and safely.

The commitment, and why it exists

The commitment is the hash of the validator set plus the threshold. The contract stores one commitment for every chain (called a domain in this code). It is used to verify the authenticity of the validator set before signature verification runs, because the metadata used during verification is supplied by the user.

Think of the commitment as a wax seal on an envelope listing the approved signers and how many signatures are needed. If someone hands you a different list, the seal will not match the one you have on file, and you reject it.

The bug

The vulnerability arises from the way the contract handles the initial setting of the threshold value when a new domain or chain is added. The contract holds a different set of validators and a different threshold for each chain.

When a new domain is added, the setThreshold function, which sets the threshold value, is called separately and after the enrollValidator function, which enrols a new validator. Both functions update the commitment when called.

setThreshold is guaranteed to be called after enrollValidator because of this requirement:

Text
require(            _threshold > 0 && _threshold <= validatorCount(_domain),            "!range"        );

This says the threshold must be greater than 0 and no greater than the number of validators already enrolled for that domain. In plain words: you cannot ask for 3 signatures if only 2 validators exist. So at least one validator must be enrolled before a valid threshold can be set, which forces the order: validators first, threshold second.

Here is enrollValidator, which adds a validator and then refreshes the commitment:

Text
function enrollValidator(uint32 _domain, address _validator)        external        onlyOwner    {        _enrollValidator(_domain, _validator);        _updateCommitment(_domain);    }

Line by line:

  1. function enrollValidator(uint32 _domain, address _validator) external onlyOwner declares a function that takes a domain number and a validator address. external means it can be called from outside the contract. onlyOwner means only the contract owner is allowed to call it.
  2. _enrollValidator(_domain, _validator); does the actual adding of the validator to the list for that domain.
  3. _updateCommitment(_domain); recalculates and stores the commitment for that domain.

Here is setThreshold, which checks the range, stores the threshold, emits an event and refreshes the commitment:

Text
function setThreshold(uint32 _domain, uint8 _threshold) public onlyOwner {        require(            _threshold > 0 && _threshold <= validatorCount(_domain),            "!range"        );        threshold[_domain] = _threshold;        emit ThresholdSet(_domain, _threshold);        _updateCommitment(_domain);    }

Line by line:

  1. function setThreshold(uint32 _domain, uint8 _threshold) public onlyOwner declares a function that takes a domain and a threshold. public means it can be called from outside. onlyOwner restricts it to the contract owner.
  2. The require(...) block enforces the range rule explained above and cancels the transaction with !range if the rule is broken.
  3. threshold[_domain] = _threshold; saves the new threshold for that domain.
  4. emit ThresholdSet(_domain, _threshold); writes a note into the blockchain log so anyone watching can see the threshold changed. An event is such a log entry.
  5. _updateCommitment(_domain); recalculates and stores the commitment.

Here is _updateCommitment, which hashes the current threshold and validator list for the domain and stores the result:

Text
function _updateCommitment(uint32 _domain) internal returns (bytes32) {        address[] memory _validators = validators(_domain);        uint8 _threshold = threshold[_domain];        bytes32 _commitment = keccak256(            abi.encodePacked(_threshold, _validators)        );
        commitment[_domain] = _commitment;
        emit CommitmentUpdated(_domain, _commitment);
        return _commitment;
    }

Line by line:

  1. function _updateCommitment(uint32 _domain) internal returns (bytes32) declares an internal helper that takes a domain and returns a fingerprint.
  2. address[] memory _validators = validators(_domain); fetches the current list of validators for that domain into temporary memory.
  3. uint8 _threshold = threshold[_domain]; fetches the currently stored threshold for that domain.
  4. bytes32 _commitment = keccak256(abi.encodePacked(_threshold, _validators)); builds the fingerprint from the threshold and the validator list.
  5. commitment[_domain] = _commitment; saves it as the official commitment for that domain.
  6. emit CommitmentUpdated(_domain, _commitment); logs the change.
  7. return _commitment; hands the fingerprint back to the caller.

The problem is this: setThreshold has not been called before a validator is enrolled for the new domain, so _threshold is still the default value of 0 at that point. In most programming languages, a number that has never been set starts at zero. The commitment computed with _threshold == 0 is written to the contract before setThreshold runs, and it becomes a permanent state. That incorrect commitment can then affect signature verification across the whole contract and lead to a bypass of the verification logic.

When _verifyValidatorSignatures runs with a threshold of 0, the loop for (uint256 i = 0; i < _threshold; ++i) is never entered, so the function returns true unconditionally. The signature verification process is effectively circumvented.

How an attacker would exploit it

The attacker uses a frontrunning attack. Frontrunning means watching the queue of pending transactions and slipping your own transaction in just before someone else's, so yours is processed first. On a blockchain, pending transactions are held by nodes before they are confirmed, and they can often be seen before inclusion.

The steps are:

  1. Wait for the team to add a new domain to support.
  2. Observe the enrollValidators transaction, which enrols the new validator without setting the threshold.
  3. Frontrun the setThreshold transaction by calling Process in the contract with a malicious message targeting protocols that use this cross-chain messaging system. Process calls _verifySignature before processing the message.
  4. In the malicious message metadata, set _metadata.threshold() to 0 and use the validator addresses previously sent by the team during the enrollValidators transaction.
  5. The require(_commitment == commitment[_origin], "!commitment") check passes because the commitment with _threshold == 0 is stored in the contract.
  6. Since the threshold is 0, the signature verification loop is not entered, and the message is processed without proper signature validation.

Why each step matters: step 1 gives the attacker the window, because a new domain must be onboarded. Step 2 tells the attacker exactly which validator addresses to put in the fake metadata, since those are the ones the contract has just stored. Step 3 is the race: the attacker must get in before the team sets a real threshold. Step 4 makes the fake metadata match the broken commitment. Step 5 passes the fingerprint check because the stored fingerprint was built with a threshold of 0. Step 6 skips the signature loop entirely, so no real signature is ever needed.

The report does not include the raw transaction, the message payload or the metadata bytes.

Root cause

The commitment is refreshed by both enrollValidator and setThreshold, but the ordering forced by the !range check means the first refresh happens while the threshold is still the default 0. That zero-threshold commitment is stored and never corrected until setThreshold runs, and during that window it matches any metadata that declares a threshold of 0 with the enrolled validator list. The verification loop is bounded by the user-supplied threshold, so a threshold of 0 skips the loop entirely and the function returns true. The commitment check, which is meant to authenticate the validator set, therefore authenticates a set whose declared threshold is 0.

In everyday terms: the wax seal was stamped on an envelope that said "zero signatures required". Anyone who presents an envelope with the same wording gets a matching seal, and the guard, seeing zero signatures required, checks nothing and waves them through.

Impact

An attacker can bypass signature verification and process malicious, unsigned messages in multiple protocols that use this contract. The report states this can lead to unauthorised actions, fund theft or other harmful consequences, affecting the integrity of affected systems.

The fix

The recommendation was to add a custom error to _verifyValidatorSignatures: if _threshold is equal to 0, the transaction should revert with an error message indicating that the threshold must be a non-zero value. The report does not say whether the project implemented this.

Variants to test

If you are reviewing similar systems, these are the patterns worth checking:

  1. Look for any per-domain or per-tenant configuration where a commitment, hash or cache is refreshed by more than one setter and one of them can run before the others. A positive result is a stored commitment that matches a configuration with a default or zero value.
  2. Check verification loops bounded by a value taken from user-supplied metadata. A positive result is a metadata value of 0 that skips the loop and returns success.
  3. Watch onboarding transactions for new domains, chains or validator sets and compare the state between the enrolment transaction and the configuration transaction. A positive result is a commitment that can be matched with a zero threshold during that window.
  4. Test whether Process or equivalent entry points can be called by anyone during onboarding, which is what makes the frontrun possible.

Glossary

  • Blockchain: a shared record book kept by many computers, where entries are very hard to change once written.
  • Smart contract: a program that lives on a blockchain and runs automatically according to rules anyone can read.
  • Cross-chain messaging protocol: a system that lets one blockchain send instructions to another.
  • Signature verification: the process of checking that a message was really signed by the claimed sender and was not altered.
  • Cryptography: mathematics used to keep information secret and to prove who sent what.
  • Private key: a secret number that only its owner knows, used to create signatures.
  • Public key: a number everyone can see, mathematically linked to a private key, used to check signatures.
  • Validator: a trusted party whose approval counts towards accepting a message.
  • Threshold: the minimum number of valid signatures needed before a message is accepted.
  • Function: a named block of code that takes inputs and produces a result.
  • Hash: a fixed-length mathematical fingerprint of some data; changing the data changes the fingerprint completely, and you cannot reverse it.
  • Commitment: here, the stored hash of the validator list plus the threshold, used to check that a supplied validator list is the official one.
  • Domain: in this contract, one of the separate chains, each with its own validator list and threshold.
  • Event: a log entry written into the blockchain so that outside observers can see something happened.
  • Frontrunning: watching the public queue of pending transactions and inserting your own just before someone else's so it is processed first.
  • Mempool: the public waiting area where blockchain transactions sit before being confirmed.
  • ECDSA: the standard mathematical scheme used to create and check digital signatures.
  • Bug bounty programme: a scheme where organisations pay people for responsibly reporting security problems.
  • Immunefi: a bug bounty platform that focuses on blockchain and smart contract projects.
  • Revert: cancel a transaction and undo its effects, usually because a rule was broken.
  • Metadata: extra information attached to a message, here supplied by the user and therefore not trusted.

Similar reports

View all

Same bug class and techniques, clearest first.

Smart contract vulnerabilities

The lesson behind this report.

Flaws in on-chain code that let an attacker drain funds, freeze them or break the protocol's accounting.