Skip to content
Race condition Audit finding Advanced

Undermining the fairness of the protocol in swapSource() and possibilities for stealing a jackpot

The retry() function only updates maxFailedAttemptsReachedAt when failedAttempts equals maxFailedAttempts, so after that point a retry() can be front-run before swapSource() to trigger two random number requests. An attacker could then inspect the two random numbers and front-run the one that favours them, undermining fairness and potentially stealing a jackpot.

alexxander Follow

Originally disclosed on Code4rena

Submitted by alexxander

This issue will demonstrate how the current implementation of swapSource() and retry() goes directly against Chainlink’s Security Consideration of Not re-requesting randomness (https://docs.chain.link/vrf/v2/security#do-not-re-request-randomness).

Note

For clarity it is assumed that after swapSource() the new source would be Chainlink Subscription Method implementation and I would refer to it again as Chainlink VRF since this was the initial design decision, however it is of no consequence what the new VRF is.

The Exploit

The swapSource() method can be successfully called if 2 important boolean checks are true.

notEnoughRetryInvocations - makes sure that there were maxFailedAttempts failed requests for a RN.

notEnoughTimeReachingMaxFailedAttempts - makes sure that maxRequestDelay amount of time has passed since the timestamp for reaching maxFailedAttempts was recorded in maxFailedAttemptsReachedAt i.e sufficient time has passed since the last retry() invocation. The most important detail to note here is that the swapSource() function does not rely on lastRequestTimestamp to check whether maxRequestDelay has passed since the last RN request.

    function swapSource(IRNSource newSource) external override onlyOwner {
        if (address(newSource) == address(0)) {
            revert RNSourceZeroAddress();
        }
        bool notEnoughRetryInvocations = failedSequentialAttempts < maxFailedAttempts;
        bool notEnoughTimeReachingMaxFailedAttempts = block.timestamp < maxFailedAttemptsReachedAt + maxRequestDelay;
        if (notEnoughRetryInvocations || notEnoughTimeReachingMaxFailedAttempts) {
            revert NotEnoughFailedAttempts();
        }
        source = newSource;
        failedSequentialAttempts = 0;
        maxFailedAttemptsReachedAt = 0;

        emit SourceSet(newSource);
        requestRandomNumberFromSource();
    }

The critical bug resides in the retry() method. maxFailedAttemptsReachedAt is ONLY updated when failedAttempts == maxFailedAttempts - notice again the strict equality - meaning that maxFailedAttemptsReachedAt won’t be updated if there are more retry() invocations after failedAttempts == maxFailedAttempts. This means that after the point of time when the last failed retry() sets maxFailedAttemptsReachedAt and the maxRequestDelay time passes - retry() and swapSource() (in that exact order) can be called simultaneously.

        uint256 failedAttempts = ++failedSequentialAttempts;
        if (failedAttempts == maxFailedAttempts) {
            maxFailedAttemptsReachedAt = block.timestamp;
        }

The attacker would monitor the transaction mempool for the swapSource() invocation and front-run a retry() invocation before the swapSource transaction. Now we have two separate - seemingly at the same time - calls to requestRandomNumberFromSource() and again to note that the retry() call will update lastRequestTimestamp = block.timestamp but it will not update maxFailedAttemptsReachedAt since now failedAttempts > maxFailedAttempts and as presented swapSource() does not rely on lastRequestTimestamp which makes all of this possible.

Now we have two requests at the same time to VRFv2RNSource.sol and in turn Chainlink VRF. Chainlink VRF will in turn send 2 callback calls each containing a random number and the callbacks can be inspected by the attacker and in turn he will front-run the RN response that favours him greater thus undermining the fairness of the protocol.

Proof of Concept

  1. retry() is called enough times to reach maxFailedAttempts, attacker starts monitoring the mempool for the swapSource() call.
  2. Admin decides to swap Source. Admin waits for maxRequestDelay time to pass and calls swapSource().
  3. Attacker notices the swapSource() call and front-runs a retry() call before the swapSource() invocation.
  4. The introduced code bug displays that swapSource() is not invalidated by the front-ran retry() and both retry() and swapSource() request a random number from Chainlink VRF.
  5. Attacker now scans the mempool for the callbacks from the requests to VRF, inspects the random numbers and front-runs the transaction with the random number that favors him.

Impact

Re-requesting randomness is achieved when swapping sources of randomness. Fairness of protocol is undermined.

Note

Recently published finding by warden Trust discusses a very similar attack path that has to do with more than 1 VRF callbacks residing in the mempool.

Edge Case - stealing a jackpot when swapping randomness Source

The Wenwin protocol smart contracts are built such that various configurations of the system can be deployed. The provided documentation gives example with a weekly draw, however drawPeriod in LotterySetup.sol could be any value. A lottery that is deployed with drawPeriod of for example 1 hour rather than days can be much more susceptible to re-requesting randomness. Similarly to Issue #2 an attacker would anticipate a swapSource() call to front-run it with retry() call and generate 2 RN requests. Now the attacker would use another front-running technique - Supression, also called block-stuffing, an attack that delays a transaction from being executed (reference in link section).

The attacker would now let one of the generated RN callback requests return to the contract and reach the receiveRandomNumber() in Lottery.sol and let the protocol complete the current draw and return the system back in a state that can continue with the next draw - all of that while suppressing the second RN callback request. The attacker would register a ticket with the combination generated from the Random Number in the suppressed callback request and when executeDraw() is triggered he would then front-run the “floating” callback request to be picked first by miners therefore calling ‘fulfillRandomWords()’ with the known RN and winning the jackpot.

Relevant links

Consensys front-running attacks - (https://consensys.github.io/smart-contract-best-practices/attacks/frontrunning/#suppression) Medium article on Block Stuffing and Fomo3D - (https://medium.com/hackernoon/the-anatomy-of-a-block-stuffing-attack-a488698732ae)

Proof of Concept

  1. Assume Lottery configuration with a short drawPeriod e.g 1 hour.
  2. retry() is called enough times to reach maxFailedAttempts, attacker starts monitoring the mempool for the swapSource() call.
  3. Admin decides to swap Source. Admin waits for maxRequestDelay time to pass and calls swapSource().
  4. Attacker notices the swapSource() call and front-runs a retry() call before the swapSource() invocation thus achieving 2 callback RN requests as in Issue #2 PoC.
  5. Attacker uses front-running suppression after one of the callback requests is picked up by the protocol and therefore current draw is finalized.
  6. Attacker registers a ticket with the winning combination generated from the suppressed RN.
  7. After drawPeriod is past attacker or other user calls executeDraw().
  8. Attacker front-runs the “suppressed RN” to be picked by miners first.
  9. ‘fulfillRandomWords()’ is called with the RN known by the attacker thus winning a jackpot.

Impact

Fairness of the protocol is undermined when swapping Sources in Lottery configurations with short drawPeriod. Unfair win of a jackpot.

Tools Used

Recommended Mitigation Steps

Refactor the try{} catch{} in requestRandomNumberFromSource() in RNSourceController.sol. Replace failedAttempts == maxFailedAttempts with failedAttempts >= maxFailedAttempts in retry() in RNSourceController.sol. Evaluate centralization risks that spawn from the fact that only owners can decide on what a new source of randomness can be i.e swapSource().

Ensure that when swapping sources the new Source doesn’t introduce new potential attack vectors, I would suggest reading warden’s Trust report from Forgeries competition that displays potential attack vectors with retry-like functionality when using Chainlink VRF Subscription Method. Ensure all Security Considerations in Chainlink VRF documentation are met.

rand0c0des (Wenwin) confirmed, but disagreed with severity

cccz (judge) commented:

When block.timestamp >= maxFailedAttemptsReachedAt + maxRequestDelay, that is, when swapSource() can be called, retry() can be called first and does not prevent swapSource() from being called.

Summary: retry() can front-run swapSource() to get two random numbers.

cccz (judge) commented:

Returning two random numbers clearly breaks the intent of the protocol, and I would consider it to meet the Medium-risk criteria.

2 — Med: Assets not at direct risk, but the function of the protocol or its availability could be impacted, or leak value with a hypothetical attack path with stated assumptions, but external requirements.

For the severity criteria, see https://docs.code4rena.com/awarding/judging-criteria/severity-categorization


The original report as published on Code4rena, by alexxander. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the retry() function only sets maxFailedAttemptsReachedAt when failedAttempts exactly equals maxFailedAttempts, and swapSource() does not check lastRequestTimestamp, so a retry() after that point does not prevent swapSource() from being called.

Impact

The fairness of the protocol is undermined when swapping sources, and in configurations with a short drawPeriod an attacker could unfairly win a jackpot.

What the attacker needed

Attacker can monitor the mempool; attacker can front-run transactions; admin calls swapSource(); short drawPeriod for jackpot theft

The fix

The retry() function should use failedAttempts >= maxFailedAttempts instead of strict equality, and the try/catch in requestRandomNumberFromSource() should be refactored.

How it was found

  1. Call retry() enough times to reach maxFailedAttempts and start monitoring the mempool for swapSource().
  2. Admin waits for maxRequestDelay and calls swapSource().
  3. Attacker front-runs a retry() before swapSource().
  4. Both retry() and swapSource() request a random number from Chainlink VRF.
  5. Attacker scans the mempool for the callbacks, inspects the random numbers, and front-runs the transaction with the favourable number.

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 lottery uses a random number to pick a winner. The code has a bug that lets someone cause two random numbers to be requested at nearly the same time. The attacker can see both numbers and choose the one that makes them win.

What is Race condition?

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.

More by alexxander

View all

10 more disclosed reports, best first.

More from Wenwin contest

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.