Skip to content
Business logic Write-up Advanced

[web3] Polygon Consensus Bypass Bugfix Review. This is a postmortem of a vulnerability… | by Immunefi | Jul, 2022 | Medium

A flaw in Polygon's staking contract allowed a delegator to repeatedly decrease the total staking power by migrating and unstaking, potentially bypassing the two-thirds consensus threshold. An attacker could then submit malicious checkpoints to drain funds from the deposit manager.

medium.com

Published on medium.com

Polygon

Immunefi, 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. 7 min read.

## Context

Polygon PoS is a Layer-2 scalability solution that relies on a set of validators who stake MATIC tokens into the system to secure the network. Validators run Heimdall validator and Bor block producer nodes, produce blocks, validate and participate in consensus, and commit checkpoints on the Ethereum mainnet. Rewards are distributed to all stakers proportional to their stake at every checkpoint, and a staker can opt out at any time and withdraw tokens once the unbonding period ends. Validators are selected via an on-chain process that happens at regular intervals.

Those who do not run a validator node can participate as delegators: they stake MATIC with existing validators and receive a part of the rewards in exchange. Anyone can delegate any amount of tokens to any validator. When a validator unstakes, the counter of the total staking power updates together with the delegated amount in that validator.

As long as �
� of the weighted stake of the validators is honest, the chain progresses accurately and the funds on the chain are secure. The consensus requirement is therefore a �
� +1 threshold of the total staked amount, the PoS analogue of the 51% attack on PoW.

The target of the report is Polygon's staking manager contract, the main contract for validator-related activities such as checkpoint signature verification, reward distribution, slashing validators and stake management. Anyone can stake MATIC into the contract, and the contract mints an NFT with `validatorID` as a source of ownership. The contract has a fixed slot limit (`validatorThreshold`) for validators; at the time of the report the slot limit was set to 100. To stake into the system you have to wait until one of the validators unstakes and fill the slot via a selection process.

## Setup

On January 15, whitehat Niv Yehezkel submitted a report to Polygon together with a local mainnet fork proof of concept demonstrating a consensus bypass vulnerability. The bug was rated `high` because of the complexity of the exploit, and the bounty was $75,000.

Exploiting it required specific market conditions: a validator spot had to be open, and the capital requirements were high (less capital means the attack takes longer). The amount to pay miners directly to stay in the validator spot using flashbots was also high. Checkpoints on the Polygon network happen every 30 to 45 minutes, and the attacker would have needed to keep the validator spot for a long time, which increases the cost of the attack because of the time required.

## Finding it

For every validator participating via the `stakeFor()` function, the contract asks the validator whether it wants to allow delegators to stake tokens into it, through `acceptDelegation(bool)`. If the validator accepts delegators, the contract creates a `validatorShare` delegator contract for that validator.


{{media:1}}


The screenshot shows the `stakeFor()` function and the behaviour described above.

The `ValidatorShare` contract holds all the logic for delegators: buying and selling shares of validators, calculating rewards earned, and so on. Delegators provide MATIC to validators in the `stakeManger` contract and receive the corresponding amount of shares; they can later sell those shares and get back their staked MATIC along with the rewards. Delegators buy shares through the `buyVoucher()` function.


{{media:2}}


Every time staking tokens or stakers are added to or removed from the system, `updateTimeline(amount, stakerCount, epoch)` is called on the `stakingManager` contract, which accounts for the number of staked tokens and the number of stakers. The `StakingManager` contract keeps validator state in the `validatorState` struct. Two variables matter for the vulnerability:

- `validatorState.amount`: the total number of tokens staked by the validators, that is, the total staking power.
- `validatorState.stakerCount`: the total number of stakers in the contract.


{{media:3}}


When a validator unstakes, the total staking power counter is updated together with the delegated amount and the validator's own amount, through this line:

```text
updateTimeline(-(int256(amount) + delegationAmount), -1, targetEpoch);
```


{{media:4}}


That call decreases the total staking power by `amount + delegationAmount`, where `amount` is the validator's staked amount and `delegationAmount` is the total amount delegated to the validator.

`StakeManager` also has a `migrateDelegation` function, which lets delegators move their delegated amounts from one validator to another.


{{media:5}}


When a delegator migrates tokens through `migrateDelegation`, the system first calls `migrateOut` on `validators[fromValidatorId].contractAddress`, the contract that withdraws the tokens the delegator deposited along with the rewards from the `fromValidatorId` validator. It then burns the delegator's shares for that validator and updates the validator state with the removed amount on the `stakeManger` contract.


{{media:6}}


The system then calls `migrateIn` on `validators[toValidatorId].contractAddress`, which buys shares of the `toValidatorId` validator by depositing the staking tokens and updates the validator state with the added amount on the `stakeManger` contract. That completes the migration.

The problem appears when delegators migrate their delegations from one validator to another. The contract calls `updateTimeline(-amount)`, which subtracts from the total validator power in the `stakeManager` contract, and once that validator unstakes, the total staking power counter is updated again by decreasing the validator amount plus the delegated amount a second time.

Concretely: if the validator unstakes and a delegator migrates from one validator to another, the delegated amount moves to the other validator. When that validator unstakes, the total staking power counter updates again and decreases the delegated amount again.

The exact issue is in `updateValidatorState(validatorId, -int256(amount))` on the `stakeManager` contract, where it modifies the timeline with `updateTimeline(amount, 0, 0);`. This reduces the total staking power `validatorState.amount` by the amount the delegator is migrating, without first checking whether the current validator is still staking in the contract.


{{media:7}}


## Exploitation

### Step 1: create a validator

Create a new validator using the `stakeFor` function.

### Step 2: buy shares with a large delegation

Call the `buyVoucher` function with a big delegated amount to buy shares of the validator by staking tokens.

The attacker can then repeat the following steps until `validatorState.amount` (the total staking power) is low enough to bypass the �
� consensus majority check.

### Step 3: catch a validator slot

Catch an available validator slot via the on-chain auction process that happens at regular intervals.

### Step 4: migrate the delegation in

Migrate staking tokens into that validator by calling the `migrateDelegation` function.

### Step 5: unstake the validator

Unstake the validator. `validatorState.amount` is decreased again.

### Step 6: wait for a checkpoint

Wait for a checkpoint, so that the validator slot opens again.

Repeating these steps decreases the total staking power by the same delegated amount on every iteration. The attacker can keep going until the total staking power is low enough to start accepting new checkpoints, bypassing the required �
� consensus majority check, and can lower it to a point where a sole validator passes the majority check.


{{media:8}}


After the consensus bypass, the attacker can send malicious checkpoints that fake a withdrawal of tokens from Polygon, draining all tokens from the deposit manager and claiming all Heimdall fees stored there and more.

## Root cause

When `migrateOut()` is called in the `validatorShare` contract, it calls `stakeManager.updateValidatorState(validatorId, -int256(amount));` to subtract the amount from the `validatorId`. That path reduces the total staking power through `updateTimeline(amount, 0, 0);` without checking whether the validator is still staking in the contract. The unstaking path separately subtracts `amount + delegationAmount` from the same counter. A delegation that has already been migrated out is therefore subtracted twice: once at migration and once when the validator unstakes. The migration path subtracts the amount without checking whether the validator is still staking, and the unstake path subtracts it again.

## Impact

An attacker could decrease the total staking power until the �
� threshold could be bypassed, potentially allowing them to drain all funds from the deposit manager, perform unlimited withdrawals, cause a denial of service and more. The severity was rated `high` because of the complexity of the exploit. The attack depended on specific market conditions: an open validator spot, high capital requirements, high payments to miners via flashbots to hold the validator spot, and the need to keep the spot for a long time, with checkpoints every 30 to 45 minutes, making the attack expensive in time.

## Fix

The fix was deployed on the Matic GitHub repository by adding a check so that the total staking power is updated only if the validator did not unstake from the `StakeManager` contract.


{{media:9}}


## Variants to test

- Audit every accounting path that adjusts a global total (stake, voting power, supply, weight) for double subtraction when an entity leaves and a related balance is moved separately. A positive result is a sequence of two legitimate calls that reduces the global total by more than the entity's actual stake.
- Look at migration functions between validators, pools or vaults and check whether the source side updates global state without verifying the source entity is still active. A positive result is a migration that succeeds after the source has unstaked.
- Check whether re-entering a slot after unstaking resets the state used by the migration path. A positive result is a repeatable cycle that monotonically lowers the global total.
- Compare the unstake path and the migration path for the same counter and confirm they cannot both apply to the same delegated amount. A positive result is a counter that goes negative or below the sum of active stakes.
- Test the same pattern on delegation and reward contracts where shares are burned on one contract and totals are updated on another. A positive result is a mismatch between the sum of shares and the reported total staking power.

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

Polygon is a system for running a blockchain that sits alongside Ethereum. To keep it secure, people lock up digital tokens (MATIC) as a kind of deposit. If they behave honestly, they earn rewards. If they misbehave, they can lose their deposit. The people who lock tokens and run the machines that check transactions are called validators. Other people, called delegators, can hand their tokens to a validator and share in the rewards without running any machines themselves.

For the network to accept a new batch of records (a checkpoint), a large majority of the locked tokens has to agree: at least two thirds plus one. The system keeps a running total of all the tokens locked, called the total staking power, and compares votes against that total. If an attacker could make that running total much smaller than it really is, then a single validator could look like it holds a majority, and the attacker could push through checkpoints that nobody else agreed to.

That is exactly what the whitehat researcher Niv Yehezkel found. On January 15 he sent Polygon a report with a proof of concept (a working demonstration, run on a copy of the real network on his own machine) showing that a delegator moving tokens from one validator to another, combined with that validator then unstaking, causes the same amount to be subtracted from the total staking power twice. Repeat the cycle and the total keeps shrinking. The bug was rated high because the exploit is complex, and the bounty was $75,000.

Exploiting it in the real world was not cheap or quick. A validator spot had to be open, the capital requirements were high (less capital means the attack takes longer), and the amount to pay miners directly to stay in the validator spot using flashbots was also high. Checkpoints on Polygon happen every 30 to 45 minutes, and the attacker would have needed to hold the validator spot for a long time, which raises the cost because of the time required.

Some background: what a blockchain and consensus are

A consensus mechanism is the method a network uses to agree on a single version of the truth. In a centralised system one company decides what is true. In a distributed system, many independent participants have to cooperate, and the process is formalised: reaching consensus means enough of them agree on the next global state of the network.

In a proof of work (PoW) system, consensus means at least 51% of the nodes agree. A consensus mechanism also helps prevent certain kinds of economic attacks. In theory an attacker can compromise consensus by controlling 51% of the network, and the design is meant to make this "51% attack" unfeasible. A similar attack exists on proof of stake (PoS), but instead of 51% of nodes you need two thirds plus one of the total staked amount.

The two most common consensus mechanisms are:

  • proof-of-work (PoW)
  • proof-of-stake (PoS)

Ethereum's original Layer-1 uses PoW: transactions are broadcast to pools of pending transactions (mempools), and miners pick them up and process them. High demand makes this slow because of network congestion and gas prices that become unviable. The goal of a scalability solution is to increase transaction speed without sacrificing security or decentralisation.

Polygon PoS is a Layer-2 scalability solution that relies on a set of validators. Validators act like operators: they stake tokens into the system to secure the network. Anyone holding the native base cryptocurrency (MATIC for Polygon) can become a validator by locking up their staking token into the system and running Heimdall validator and Bor block producer nodes to help run the network. Validators run a full node, produce blocks, validate and take part in consensus, and commit checkpoints on the Ethereum mainnet. Rewards go to all stakers in proportion to their stake at every checkpoint. A staker can opt out at any time and withdraw tokens once the unbonding period ends. Validators are selected through an on-chain process that happens at regular intervals, and the selected validators act as block producers and verifiers. Once a checkpoint is validated by the participants, updates are made on the parent chain (Ethereum mainnet), which releases rewards for validators depending on their stake.

People who want to help secure the network but do not run a validator node can join as delegators. A delegator stakes MATIC with an existing validator without running nodes, and gets a part of the rewards in exchange. Anyone can delegate any amount of tokens to any validator they wish. When a validator unstakes, the counter of the total staking power updates together with the delegated amount in that validator.

As long as two thirds of the weighted stake of the validators is honest, the chain progresses accurately and the funds on the chain are secure. The validators put up MATIC as collateral to work for the security of the network and earn rewards for their service.

The contract under review

Polygon's staking manager contract is the main contract for validator-related activities: checkpoint signature verification, reward distribution, slashing validators and stake management. A contract here is a program that lives on the blockchain and runs by itself; think of it as a vending machine that anyone can press buttons on, but whose internal rules nobody can quietly change.

Anyone can take part in the PoS system by staking MATIC into the contract, and the contract mints an NFT with validatorID as a source of ownership for participants. An NFT here is simply a unique digital receipt that proves who owns what. The contract also has a fixed slot limit (validatorThreshold) for validators to take part. At the time of the report the slot limit was set to 100. To stake into the system you have to wait until one of the validators unstakes and then fill the slot through a selection process.

How staking and delegation work in the code

For every validator that joins through the stakeFor() function, the contract asks the validator whether it wants to allow delegators to stake tokens into it, through acceptDelegation(bool). If the validator wants to accept delegators, the contract creates a validatorShare delegator contract for that validator. The screenshot below shows the stakeFor() function and this behaviour.

From the original on medium.com

The ValidatorShare contract holds all the logic for delegators: buying and selling shares of validators, calculating the rewards earned, and so on. Delegators take part by providing staking tokens (MATIC) to validators in the stakeManger contract, and in return the contract mints the desired amount of shares to the delegator. Later, delegators can sell those shares and get back their staked MATIC along with the rewards earned. Delegators buy shares through the buyVoucher() function.

From the original on medium.com

Every time staking tokens or stakers are added to or removed from the system, the function updateTimeline(amount, stakerCount, epoch) is called on the stakingManager contract. It is responsible for accounting the number of staked tokens and the number of stakers in the contract.

The StakingManager contract keeps information about the validator state in the validatorState struct. A struct is just a bundle of related values kept together under one name. Two variables in it matter for the vulnerability:

  • validatorState.amount: the total number of tokens staked by the validators. In other words, the total staking power.
  • validatorState.stakerCount: the total number of stakers in the contract.
From the original on medium.com

When a validator unstakes, the total staking power counter is updated together with the delegated amount and the validator's own amount. This is the line that does it:

Text
updateTimeline(-(int256(amount) + delegationAmount), -1, targetEpoch);
From the original on medium.com

Line by line: updateTimeline is the accounting function described above. The first argument is the change to apply to the totals. -(int256(amount) + delegationAmount) means: take the validator's staked amount, add the delegationAmount (the total delegated to that validator by delegators), and make the result negative, so the total goes down by that sum. int256 is just the number type used so the value can be negative. The second argument, -1, means one staker is leaving. The third, targetEpoch, says at which point in time the change takes effect. So the call decreases the total staking power by amount + delegationAmount.

StakeManager also has a migrateDelegation function, which lets delegators move their delegated amounts from one validator to another validator.

From the original on medium.com

When a delegator migrates tokens through migrateDelegation, the system first calls migrateOut on validators[fromValidatorId].contractAddress, the contract that withdraws the staking tokens the delegator deposited, along with the rewards, from the fromValidatorId validator. Then it burns the shares the delegator held for that validator and updates the validator state with the removed amount on the stakeManger contract. Burning a share means destroying the receipt so it can no longer be redeemed.

From the original on medium.com

The system then calls migrateIn on validators[toValidatorId].contractAddress, which buys shares of the toValidatorId validator by depositing the staking tokens and updates the validator state with the added amount on the stakeManger contract. That completes the migration.

Where the bug is

The problem appears when delegators migrate their delegations from one validator to another. The contract calls updateTimeline(-amount), which subtracts from the total validator power in the stakeManager contract, and once that validator unstakes, the total staking power counter is updated again by decreasing the validator amount plus the delegated amount a second time.

Picture it as a shared bank account that tracks how much money the whole group has. When you move your money from one wallet to another, the bank subtracts it from the group total. Then, when the wallet you moved it out of is closed, the bank subtracts the same money again, so the group total is lower than the money that actually exists.

Concretely: if the validator unstakes and a delegator migrates from one validator to another, the delegated amount moves to the other validator. When that validator unstakes, the total staking power counter updates again and decreases the delegated amount again.

The exact issue is in updateValidatorState(validatorId, -int256(amount)) on the stakeManager contract, where it modifies the timeline with updateTimeline(amount, 0, 0);. This reduces the total staking power validatorState.amount by the amount the delegator is migrating, without first checking whether the current validator is still staking in the contract.

From the original on medium.com

Steps to reproduce

  1. Create a new validator using the stakeFor function.
  2. Call the buyVoucher function with a big delegated amount to buy shares of the validator by staking tokens.

The attacker can now repeat the following steps until validatorState.amount (the total staking power) is low enough to bypass the consensus majority check (two thirds) requirement.

  1. Catch an available validator slot through the on-chain auction process that happens at regular intervals.
  2. Migrate staking tokens into that validator by calling the migrateDelegation function.
  3. Unstake the validator. validatorState.amount is decreased again.
  4. Wait for a checkpoint, so that the validator slot opens again.

Why each step: the first two steps give the attacker a validator and a large delegation to work with. The loop then does the damage. Migrating moves the delegation and subtracts it from the total. Unstaking subtracts the validator's amount plus the delegated amount, which includes the same delegation a second time.

These steps repeatedly decrease the total staking power by the same delegated amount on every iteration. The attacker can keep going until the total staking power is low enough to start accepting new checkpoints, bypassing the required two thirds consensus majority check, and can lower it to a point where a sole validator passes the majority check.

From the original on medium.com

After this consensus bypass, the attacker can send malicious checkpoints that fake a withdrawal of tokens from Polygon. That basically drains all tokens from the deposit manager and claims all Heimdall fees stored there and more.

Root cause

When migrateOut() is called in the validatorShare contract, it calls stakeManager.updateValidatorState(validatorId, -int256(amount)); to subtract the amount from the validatorId. That path reduces the total staking power through updateTimeline(amount, 0, 0); without checking whether the validator is still staking in the contract. The unstaking path separately subtracts amount + delegationAmount from the same counter. A delegation that has already been migrated out is therefore subtracted twice: once at migration and once when the validator unstakes. The migration path subtracts the amount without checking whether the validator is still staking, and the unstake path subtracts it again.

Impact

An attacker could decrease the total staking power until the two thirds threshold could be bypassed. That could potentially let them drain all funds from the deposit manager, perform unlimited withdrawals, cause a denial of service and more. The severity was rated high because of the complexity of the exploit. The attack depended on specific market conditions: an open validator spot, high capital requirements, high payments to miners through flashbots to hold the validator spot, and the need to keep the spot for a long time, with checkpoints every 30 to 45 minutes, making the attack expensive in time.

The fix

The fix was deployed on the Matic GitHub repository by adding a check so that the total staking power is updated only if the validator did not unstake from the StakeManager contract.

From the original on medium.com

Variants to test

  • Audit every accounting path that adjusts a global total (stake, voting power, supply, weight) for double subtraction when an entity leaves and a related balance is moved separately. A positive result is a sequence of two legitimate calls that reduces the global total by more than the entity's actual stake.
  • Look at migration functions between validators, pools or vaults and check whether the source side updates global state without verifying the source entity is still active. A positive result is a migration that succeeds after the source has unstaked.
  • Check whether re-entering a slot after unstaking resets the state used by the migration path. A positive result is a repeatable cycle that monotonically lowers the global total.
  • Compare the unstake path and the migration path for the same counter and confirm they cannot both apply to the same delegated amount. A positive result is a counter that goes negative or below the sum of active stakes.
  • Test the same pattern on delegation and reward contracts where shares are burned on one contract and totals are updated on another. A positive result is a mismatch between the sum of shares and the reported total staking power.

Glossary

  • Blockchain: a shared record of transactions kept by many computers, where each new batch of records is linked to the previous one.
  • Consensus mechanism: the method a network uses to agree on a single version of the truth.
  • Proof of work (PoW): a consensus method where participants spend computing effort to earn the right to add records; consensus needs at least 51% of nodes.
  • Proof of stake (PoS): a consensus method where participants lock tokens as collateral; consensus needs two thirds plus one of the total staked amount.
  • 51% attack: an attack where someone controls 51% of a PoW network and can decide what is true.
  • Layer-1: the base blockchain itself, such as Ethereum mainnet.
  • Layer-2: a system built on top of a base blockchain to process transactions faster while relying on the base chain for security.
  • Polygon PoS: Polygon's proof-of-stake Layer-2 scalability solution, secured by validators who stake MATIC.
  • MATIC: the native token of the Polygon network, used for staking and rewards.
  • Validator: a participant who locks tokens and runs nodes to produce blocks, validate and take part in consensus.
  • Delegator: someone who hands tokens to a validator to share in the rewards without running nodes.
  • Staking: locking tokens as collateral in exchange for rewards and to help secure the network.
  • Unstaking: withdrawing staked tokens, subject to an unbonding period.
  • Unbonding period: the waiting time before withdrawn tokens become available.
  • Staking power: the total number of tokens staked, used as the weight in consensus.
  • Checkpoint: a batch of records committed from Polygon to Ethereum mainnet; on Polygon it happens every 30 to 45 minutes.
  • Heimdall validator node: a node that helps run the Polygon network.
  • Bor block producer node: a node that produces blocks on Polygon.
  • Mempool: a pool of pending transactions waiting to be processed.
  • Gas price: the fee paid to have a transaction processed.
  • Flashbots: a way to pay miners directly to include a transaction.
  • Smart contract: a program that lives on the blockchain and runs by itself under fixed rules.
  • Staking manager contract: Polygon's main contract for validator activities such as checkpoint signature verification, reward distribution, slashing and stake management.
  • stakeFor(): the function through which a validator joins the system.
  • acceptDelegation(bool): the function that asks a validator whether it accepts delegators.
  • validatorShare / ValidatorShare contract: the per-validator contract that holds delegator logic such as buying and selling shares and calculating rewards.
  • buyVoucher(): the function delegators use to buy shares of a validator.
  • migrateDelegation: the function that moves a delegation from one validator to another.
  • migrateOut: the step that withdraws a delegator's tokens and rewards from the source validator and burns their shares.
  • migrateIn: the step that buys shares of the destination validator with the migrated tokens.
  • updateTimeline(amount, stakerCount, epoch): the accounting function that adjusts the number of staked tokens and stakers.
  • updateValidatorState(validatorId, -int256(amount)): the function that subtracts an amount from a validator's state.
  • validatorState struct: the bundle of values holding a validator's state.
  • validatorState.amount: the total tokens staked by validators, i.e. the total staking power.
  • validatorThreshold: the fixed slot limit for validators, set to 100 at the time of the report.
  • validatorID: the identifier of a validator, used as the source of ownership in the minted NFT.
  • NFT: a unique digital receipt proving ownership.
  • Shares: units minted to a delegator representing their stake in a validator; they can be sold to get tokens and rewards back.
  • Burning: destroying shares so they can no longer be redeemed.
  • Slashing: penalising a validator by taking part of its stake.
  • Deposit manager: the contract holding deposited funds that the attacker could drain after a consensus bypass.
  • Heimdall fees: fees stored in the system that the attacker could claim.
  • Denial of service (DoS): making a system unusable for legitimate users.
  • Proof of concept (PoC): a working demonstration that a vulnerability can actually be exploited.
  • Mainnet fork: a copy of the real network run locally for testing.
  • Whitehat: a security researcher who finds and reports vulnerabilities responsibly.
  • Bug bounty: a reward paid for reporting a vulnerability.
  • Severity: the rating of how serious a vulnerability is; here high.
  • Root cause: the underlying reason a vulnerability exists.
  • Double subtraction: subtracting the same amount from a total twice, making the total too low.
  • On-chain auction: the selection process, run by the contract, that fills an open validator slot.
  • Epoch: a point in time used by the contract to schedule changes.
  • int256: a number type that can hold negative values.

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.