Post Mortem: KyberSwap Elastic Exploit November 2023

1. Incident Summary

  • Overview: On November 22, 2023, certain KyberSwap Elastic Liquidity Pools (“Affected Pools”) experienced a sophisticated exploit (“Exploit”) initiated by a primary exploiter (“Primary Exploiter”) and mimicked by front-run bots (“Front-Run Bots”), leading to unauthorized extraction of a significant amount of assets of KyberSwap Elastic users (“Affected Users”) from Affected Pools and rendering certain assets in certain Affected Pools inaccessible (such extracted and inaccessible Affected Users’ assets collectively “Affected Assets” and such inaccessible Affected Assets (“Locked Affected Assets”)).
  • Response and Mitigation: Suspension of liquidity additions to Affected Pools and all other KyberSwap Elastic Liquidity Pools prevent further attack, user alerts, and extensive recovery efforts, including negotiations and collaborations for recovery of Affected Assets and of Locked Affected Assets for return to Affected Users.
  • Treasury Grant Plan: Subsequent to the Exploit, KyberSwap has initiated a Treasury Grant Plan to support Affected Users through treasury grants to mitigate the economic impact of the Exploit on Affected Users, demonstrating KyberSwap’s commitment to support its community in the wake of the Exploit.
  • Technical Vulnerability: The Exploiter(s) exploited a vulnerability in the swap mechanism code that is attributed to a discrepancy in the tick-based swap mechanism exacerbated by a rounding error – which vulnerability was not identified despite prior code audit efforts.

Key Incident Metrics

  • Affected Users: 2,367 unique liquidity providers impacted.
  • Total Value of Affected Assets: Approximately $56,197,284.26 being the value of Affected Assets. Of this amount, approximately $55,234,535.17 was taken from Affected Pools by the Exploit, of which approximately $48,671,786.84 was taken by Primary Exploiter and approximately $6,562,748.33 was taken by Mimicking Bots.
    (estimated in USD value of digital assets at the time of the Exploit)
  • Total Value of Affected Assets recovered by KyberSwap Team from Front-Run Bots: Approximately $5.7 million
  • Total Value of Locked Affected Assets: Approximately $24,306.18
  • Total Value of Locked Affected Assets recovered by KyberSwap Team: Approximately $706k

2. Technical Analysis

Having outlined the overall impact of the incident, we now delve into a detailed technical analysis to understand the dynamics of the attack and the vulnerability that was exploited in the Exploit.

2.1. Attack Dynamics

Specifics of KyberSwap Elastic Vulnerability

KyberSwap Elastic’s design featured concentrated liquidity, allowing for variable liquidity levels at different prices, and a tick-based system where liquidity changes at specific price points. The root cause of the vulnerability was a discrepancy between the cross-tick estimation and final price calculation, lacking sufficient checks for consistency. A rounding error exacerbated this inconsistency, leading to unrecalculated liquidity upon crossing a tick.

Execution of the Exploit

  1. Initial Preparations: The Primary Exploiter began by manipulating the pool price outside of the liquidity zone, establishing a clean state.
  2. Precise Liquidity Adjustments: The Primary Exploiter added and then partially removed liquidity to achieve a specific liquidity state.
  3. Triggering the Vulnerability: A carefully calculated swap amount was used to exploit the rounding error, corrupting the pool state.
  4. Profitable Swap Execution: Finally, the Primary Exploiter executed a swap in the opposite direction, benefiting from the erroneous liquidity calculation.

2.2. Vulnerability Analysis

Vulnerability Context

The critical vulnerability in the swap mechanism of KyberSwap Elastic, a tick-based Concentrated Liquidity Automated Market Maker (AMM), was triggered during a swap flow. This occurred when the swap amount was insufficient to cross a tick boundary, specifically when swapAmount = amountSwapToCrossTick – 1.

Specifics of the Issue

  • Rounding Error: A rounding error in the swap logic resulted in an incorrect pool price after the swap.
  • Assertion Breach: The assumption that nextPrice ≤ targetPrice was invalidated in scenarios where swapping occurred.
  • Unexpected Liquidity Doubling: This led to a scenario where a swap crossing a tick in the opposite direction unexpectedly doubled the pool’s base liquidity.

Detailed Breakdown of the Flaw

Contract-Level Analysis

  • Pool Contract:
    • The Pool contract’s function named Swap processes the calculation of total exchanged amount in many repeated steps.
    • The Pool contract’s function SwapMath#computeSwapStep() was responsible for calculating swap amounts and the next pool price after each step.
    • In the function SwapMath#computeSwapStep() , the smart contract calculates the amount to reach the target price (targetSqrtP) first.
      • Condition #1: If there is sufficient amount to reach targetSqrtP, the smart contract considers that the result price is equal to targetSqrtP and go to next step.
      • Condition #2: If there is not sufficient amount to reach targetSqrtP, the smart contract calculates the result price using two functions estimateIncrementalLiquidity() and calcFinalPrice() . The calculation of each functions involves a rounding process.
    • SwapMath Logic: The bug was located in the sol file, where computeSwapStep() suffers from a double rounding error that is high enough to make the result price pass the targetSqrtP (In the case of swap from token 1 to token 0, nextSqrtP > targetSqrtP).
    • State Mismatch:
      • The system considers that the targetSqrtP is not reached (condition #2) so that there is no cross tick process and consequently no update of liquidity ( baseL)
      • The current tick is calculated from the final price. In the attack, this final price goes over the target price (represented by targetSqrtP) so that the current tick is updated.
      • The updated current tick is mismatched with the outdated liquidity amount (baseL)

Exploitation

  • The exploiter swapped with a pre-calculated amount to trigger the double rounding error and caused the state mismatch where liquidity amount (baseL) is much higher than the correct state.
  • The exploiter performed a swap in the opposite direction, exploiting the mismatched pool liquidity states and resulting in a higher output amount than expected.

2.3. Transaction-Level Explanation

An example of an exploit transaction is provided for detailed understanding: Etherscan Transaction Link.

Initial Setup and Execution

  1. Borrowing Assets: The Primary Exploiter initiated the exploit by borrowing a massive amount of ETHx, specifically 500,000,000,000,000,000,000 units, from UniswapV3. This large sum was crucial for the initial phase of the Exploit.
  2. First Swap (ETHx to USDC): Using the borrowed ETHx, the Primary Exploiter executed a swap from ETHx to USDC in the target pool (0xcbec1e9407f1910c86f261eaeac27d85c0479e8c). The swap was conducted with a specific limit for the square root price (limitSqrtP), set at 332,306,998,946,228,968,225,951,765,070,086,144. This action strategically shifted the pool’s current tick to 305000, laying the groundwork for subsequent steps in the exploit.
  3. Precise Liquidity Adjustment: Prior to executing the main phase of the Exploit, the Primary Exploiter had already calculated and set aside a very specific glitch liquidity amount – 54,880,483,538,064. This exact figure was a critical component of the exploit.
  4. Position Minting and Liquidity Removal: With the glitch liquidity in hand, the Primary Exploiter then took two key actions:
    1. Minting a Position: A position was minted with 3,321,338,298,606,975 liquidity, between tickLower 305000 and tickUpper 305408.
    2. Partial Liquidity Removal: Subsequently, a portion of the added liquidity, precisely 553,556,212,810,899, was removed. This step was vital to ensure that the pool’s liquidity matched the exact glitch liquidity number of 54,880,483,538,064.
  5. Triggering the Exploit: The next move involved the Primary Exploiter inputting a very specific swap amount (amountIn), calculated to be 244,080,034,447,359,999,999. This amount was chosen to exploit the rounding error at the heart of the vulnerability. The precision of these inputs – both the liquidity and the swap amount – was exceptionally high, making replication nearly impossible under normal circumstances.

Exploit Execution and Profit Realization

  1. Swap Execution and Glitch Triggering: During the swap of ETHx to USDC using the calculated amountIn, the computeSwapStep function in the contract calculated a nextSqrtP value of 339155191902819413739723733068166101. This value was anomalously higher than the sqrtP for tick 305408, which stood at 339155191902819412225936896397443374. This discrepancy was the glitch – an unexpected condition where nextSqrtP < targetSqrtP, which should not occur under normal operational parameters.
  2. Pool State Corruption: Due to this glitch, the pool’s logic incorrectly assumed that tick 305408 had not been crossed. As a result, the pool’s states, including baseL and reinvestL, remained unchanged when they should have been reset to zero due to the absence of liquidity at this point.
  3. Second Swap and Profit Extraction: Capitalizing on the corrupted pool state, the Primary Exploiter then conducted another swap, this time reversing the direction from USDC to ETHx. The incorrect pool states allowed the Primary Exploiter to extract an abnormally large amount, specifically 493,638,353,608,983,793,765 in ETHx.
  4. Loan Repayment and Net Gain: After completing the exploit, the Primary Exploiter repaid the initial flash loan of 500,250,000,000,000,000,000 ETHx to UniswapV3. The net profit realized from this sophisticated Exploit amounted to 32,359,711,420 USDC and 2,548,804,968,791,375,657 ETHx, highlighting the substantial financial impact of the exploit.

3. Exploiters

Through these exploitative swaps, the exploiters (being the Primary Exploiter and the Front-Run Bots) (“Exploiter(s)”) in the Exploit who effected the exploitative swaps succeeded in transferring Affected Assets from Affected Pools to several wallet addresses on multiple different blockchain networks in a matter of minutes and obtained the Misappropriated Digital Assets at a value significantly below their respective prevailing market value.

Exploiter

Amount Taken

(estimated in USD value of digital assets at the time of the Exploit)

Description

Exploiter 1

$48,671,786.84

Primary Exploiter

Exploiter 2

$5,822,114,95

Front-Run Bots, whose operator contacted KyberSwap to return Affected Assets

Exploiter 3

$565,229.83

Front-Run Bots whose operator contacted KyberSwap to return Affected Assets

Exploiter 4

$17,435.56

Copycat exploit

Exploiter 5

$157,967.99

Copycat exploit

The following table summarizes the list of addresses related to the Exploiter(s):

Status

Address

Exploiter

Confirmed

0x50275E0B7261559cE1644014d4b78D4AA63BE836

Exploiter 1

Confirmed

0xC9B826BAD20872EB29f9b1D8af4BefE8460b50c6

Exploiter 1

Confirmed

0x98d69d3ea5f7e03098400a5bedfbe49f2b0b88d3

Exploiter 1

Suspected

0x84e66f86c28502c0fc8613e1d9cbbed806f7adb4

Exploiter 1

Confirmed

0x5E42DD64266C3852cad3d294f71b171459Cf0a48

Exploiter 1

Confirmed

0x4ea83653ecea38b51730c14776698e19f5ca6e65

Exploiter 1

Confirmed

0xa423c7be031e988b25fb7ec39b7906582f6858c6

Exploiter 1

Suspected

0xd3a7e3c5602f8a66b58dc17ce33f739efac33da2

Exploiter 1

Suspected

0xc0f9c4b3d29a522140f3002972a7d07d7566e296

Exploiter 1

Suspected

0xDa73a2c62Ecaa80Dcb002956fa777d4c5CaB8D0d

Exploiter 1

Confirmed

0xae7e16cAa7a4d572FfF09924Bf077a89485850Cb

Exploiter 2

Confirmed

0xa4c92d7482066878bb1e2c0510f42b20d79a7ea9

Exploiter 2

Suspected

0x13603dfd43f98060ca7ce2099fce7046c191dc2b

Exploiter 2

Confirmed

0xd01896e3D4F130Ffd6f6a5A9d6780bbd7008d71d

Exploiter 3

Confirmed

0x9296fa3246f478e32b05d4dde35176d927be703f

Exploiter 3

Confirmed

0x33a7255be909fdc00801ba0db6422c9e6d8f543c

Exploiter 4

Confirmed

0x17680Ad85a366312B96406B8d940c8DFfd813444

Exploiter 4

Confirmed

0x0000000000000f25a072efa232d8efc0b5ce2436

Exploiter 5

Confirmed

0x000000000000b91b6956fead1dda24c66aa6b972

Exploiter 5

Confirmed

0x000000000000c35e4364deffa9059dbadaefd4f8

Exploiter 5

4. Response and Mitigation Steps

Following the significant impact of the incident, we have initiated a robust set of response and mitigation measures to address immediate issues and prevent similar events in the future.

  • Suspension of Liquidity Additions:
    • Arbitrum: 0x4336e5ae5763caf6a911aad3f347d39ba110ee52f7787240aa2fbe3f782a36b4
    • Optimism: 0x2d592f68243b12cbc21b249f0987f5a06d7932ec629fb281df38fe3255ea07c7
    • BSC: 0xa683703e547132eb872778b3df92ef549b118a96691f86879cdaba3c7647503f
    • Avalanche: 0x49d19da21723f480c162e971ac128e204e3f9b8301051503f8b2ead005a85d67
    • Ethereum: 0xa7075593e21c4c0fd6a8de10974877910db873d3bcdcb6b45c753c12d62d20f4
    • Polygon: 0x4346345e543bda830902aca109ca6fb67c4bdfc528de8320a03dff8b91c4aa5d
    • Fantom: 0xdf4019bfac14ec00aedc6f9bc8cc57fd0271d5164403586371f745b81cb8a219
    • Base: 0x14cdc1ccd2030caa00d23f3650f2adf13b8483130780a1b89ddd3737c5842426
    • Scroll: 0x54d8653cdddca1ed4eae316734ed95325bc0721a73aca2d08f6491f5ea8ffb27
    • Linea: 0x658e0e3c96d96535a547431fefd5c4c71f80c4ffc98840bbeefd72698782085f
    • Polygon zkEVM: 0x4c920d84bcd487aa2c86c86b0b7ea9b705ce40bec7993e5f4b73cfe008f4d482
    • BitTorrent: 0xec9d037fdfffc41597673c6ea6f3c0aa7512fc519c1a4a21887b8b68a16bfb1c
    • Cronos: 0x6ab8bd73df5307c45c7a4e4d7ac240ff1664579e6e59274f6b2b8bb4eaa5c00c
  • User Alerts: We disseminated alerts via x, Telegram, Discord, and on the Kyberswap website, as well as through these tweets:
  • On-Chain Communications: We sent several messages to the Primary Exploiter and other Exploiters (being the operators of the Front-Run Bots), offering a 10% bug bounty. See an example of these messages here: Etherscan On-Chain Message. Only Exploiter 2 and Exploiter 3 responded.
  • Negotiations and Affected Asset Recovery: We negotiated with Exploiter 2 and Exploiter 3 who extracted about $5.7M* from KyberSwap pools on Polygon and Avalanche. An agreement for a 90% return of Affected Assets in exchange for a 10% bounty was made, as detailed in this on-chain message: Polygon Transaction. Approximately $4.67M** has been returned to the KyberSwap Deployer address on Polygon through these transactions:
  • We also worked with security researchers to recover most of the Locked Affected Assets in Affected Pools, which made up a USD value of $706k at the time of the Exploit, based on a snapshot taken at the last block before the Exploit. The Locked Affected Assets include $KNC and $cbETH, and the recovery is reflected in the following transactions:
  • Partnership with Arkham Intelligence: We have launched a bounty in collaboration with Arkham Intelligence to reward information leading to the Exploiter’s identification or successful Affected Asset recovery. More details can be found here: Arkham Intelligence Tweet.
  • Continuous Support for Law Enforcement and Cybersecurity: We remain dedicated to assisting law enforcement and cybersecurity professionals in tracing and recovering Affected Users’ Affected Assets from the Exploit’s perpetrators.

5. Impact Assessment

With the technical intricacies of the Exploit examined, and effort on negotiating with Exploiter(s), we next assess the comprehensive impact of this incident. This assessment focuses on quantifying the impact in terms of Affected Users’ Affected Assets and the extent of Affected Users involvement.

5.1. List of Affected Assets

Approximately $56,197,284.26 in value of Affected Assets was initially taken from the Affected Pools or rendered in accessible by the Exploit. The following table summarizes the list of Affected Assets (price of Affected Assets based on snapshot at the blocks prior to the relevant Exploit transactions in respect of the Affected Pools):

SymbolUSD Value
WETH$13,729,924.34
wstETH$10,477,697.92
USDC$10,443,132.96
ARB$4,117,336.14
cbETH$3,196,267.03
axl-wstETH$2,866,515.57
USDT$2,746,891.95
KNC$1,527,890.79
DAI$1,110,742.25
OP$1,022,466.13
dBSGG$948,189.13
WBTC$919,330.30
WMATIC$799,194.53
axlUSDC$761,492.87
rMATIC$671,060.51
GMX$218,315.83
stMATIC$144,154.70
swETH$105,509.19
VCHF$65,392.64
SWTH$55,733.40
ELK$36,837.98
VEUR$34,965.17
FRAX$29,400.49
frxETH$28,842.04
LINK$25,886.05
USDT.e$25,722.69
LYRA$18,018.73
fUSDC$14,432.49
WAVAX$11,724.09
HAY$8,509.14
SNX$7,729.05
MONA$7,037.13
MEME$6,746.55
ETHx$5,883.49
LDO$4,324.11
WCRO$1,920.04
Volta$1,785.61
BSGG$174.64
STG$106.58

5.2. Number of Affected Users and Impact Assessment

The total number of Affected Users who have been impacted by the Exploit is 2,367 (on the assumption that each wallet address that contributed liquidity directly to Affected Pools is operated by a unique Affected User as liquidity provider (LP), though the actual number of Affected Users could be more as certain Affected Users had contributed liquidity to Affected Pools via third-party protocols/smart contracts such as Pendle).

Here’s the breakdown of the number of Affected Users within the specified impact ranges:

  • Impact from $0 to $10: 423 LPs
  • Impact from $10 to $100: 391 LPs
  • Impact from $100 to $1,000: 624 LPs
  • Impact from $1,000 to $10,000: 555 LPs
  • Impact from $10,000 to $100,000: 265 LPs
  • Impact from $100,000 to $1,000,000: 88 LPs
  • Impact greater than $1,000,000: 8 LPs

5.3. Impact on Affected Users by category

5.3.1. Exploiter 1 (Category 1):

  • Nature: Affected Assets drained from pools during the initial Exploit on November 22, 2023.
  • Value Impact to Affected Users: Approximately US$48,889,474.12, which includes liquidity positions and LP fees.
  • Current Status: Efforts are ongoing to recover these assets.

5.3.2. Exploiter 2 (Category 2):

  • Nature: Affected Assets taken from Affected Pools by Exploiter 2 – being two Front-Run Bots mimicking the Primary Exploiter.
  • Value Impact to Affected Users: Estimated at US$172,106.72, encompassing liquidity positions and LP fees.
  • Current Status: Recovery operations are in progress.

5.3.3. Exploiter 3 (Category 3):

  • Nature: Affected Assets taken from Affected Pools by Exploiter 3 – being another set of Front-Run Bots imitating the Primary Exploiter.
  • Value Impact to Affected Users: Valued at US$6,405,061.64, which includes assets that have been partially recovered and those swapped.
  • Current Status: Partial recovery has been achieved, and efforts continue for the remainder.

5.3.4. Locked Affected Assets (Category 4):

  • Nature: Subsequent to the Exploit, certain Locked Affected Assets remain locked in Affected Pools due to the incorrect pool states caused by the Exploit.
  • Value Impact to Affected Users: Total of US$24,306.18, detailed as follows: a. From Primary Exploit: US$9,217.76; b. From Category 2 Mimicking Activity: US$15,036.04; c. From Category 3 Mimicking Activity: US$52.38
  • Current Status: We are actively working to resolve the locked state and restore access to these Locked Affected Assets.

5.3.5. Locked Affected Assets that have been recovered (Category 5):

  • Nature: Subsequent to the Exploit, certain Locked Affected Assets initially locked in certain Affected Pools due to incorrect pool states caused by the Exploit have been recovered.
  • Value of Locked Affected Assets recovered: US$706,335.60.
  • Current status: Recovered

6. Treasury Grant Plans

In addition to the immediate technical responses, we are also committed to supporting our affected users financially. The following section outlines our Treasury Grant Plans designed to provide relief to those impacted.

For Categories 1, 2, and 4 affected assets: KyberSwap, a critical component of its ecosystem supported by users, developers, auditors, and cybersecurity experts, has historically funded ecosystem development through the KyberSwap Treasury. In response to the recent Elastic Exploit which significantly impacted users, KyberSwap has introduced a targeted support initiative for those affected. This initiative, named the KyberSwap Elastic Exploit Treasury Grant Program (“Program”), aims to assist Affected Users whose Affected Assets remain unrecovered, subject to fulfilment of grant eligibility criteria. Affected Users who fulfil eligibility criteria and complies with the terms of the Program can select from two treasury grant options and be offered treasury grants based on their selection.

The Program offers two choices for treasury grants:

  • Option A: 60% of the value of unrecovered Affected Assets in USD stablecoins, vested over 3 months.
  • Option B: 100% of the value of unrecovered Affected Assets in USD stablecoins, vested over 12 months.

For Category 3 Affected Assets, valued at approximately $6.4 million, the majority has been returned by Exploiter 2 and Exploiter 3 (each being operators of Front-Run Bots). KyberSwap has initiated the distribution of these recovered Affected Assets to Affected Users.

Lastly, for Category 5, the recovery will involve returning Locked Affected Assets in the same token form and amount as recovered, proportionally distributed to each Affected Address based on their LP share in the Affected Pools. This includes significant holdings by KyberSwap itself in these pools.

7. Lessons Learned

While we endeavor to support our community through these treasury grants, we also reflect on the vital lessons learned from this incident, which are crucial for our continuous improvement.

  • Improved Validation Mechanisms: The incident highlighted the need for more robust validation checks within smart contracts, particularly for complex functionalities like tick-based liquidity management.
  • Enhanced Security Audits: Strengthening security audit processes, including engaging multiple audit firms and incorporating more rigorous stress testing scenarios, is essential.
  • Community Collaboration: The importance of community collaboration in identifying vulnerabilities and responding to incidents has been reaffirmed. Encouraging a culture of responsible disclosure and rewarding white hat contributions can significantly enhance platform security.
  • Continuous Monitoring and Rapid Response: Developing stronger monitoring tools to detect anomalies and implementing rapid response protocols for potential breaches can greatly reduce the impact of such incidents. In more detail, we can implement the following system:
    • Advanced Anomaly Detection Tools: Developing and integrating advanced monitoring tools capable of real-time analysis and detection of unusual patterns or potential vulnerabilities in the system is crucial. These tools should leverage AI and machine learning algorithms to predict and identify deviations from normal operational behaviors, signaling potential exploits or system malfunctions.
    • Decentralized Monitoring System: Implementing a decentralized approach to monitoring, where not only the internal team but also trusted external entities (guardians) have access to monitoring tools. This diversifies the oversight and brings in varied expertise and perspectives, enhancing the detection capabilities.
    • Rapid Response Protocols with Guardian Integration: Establishing protocols that allow for swift action, such as pausing liquidity additions, in the event of a detected anomaly. The decision to trigger these protocols could be made collectively, involving both KyberSwap’s internal team and external guardians. This collaborative approach ensures that decisions are made promptly and with a broader consensus, mitigating risks of delayed responses.
    • Guardian Alert System: Implementing an alert system that notifies all guardians simultaneously when potential threats are detected. This system should be capable of providing detailed information about the anomaly, enabling guardians to make informed decisions quickly.

. . .

About Kyber Network

Kyber Network is building a world where any token is usable anywhere. KyberSwap.com, our flagship Decentralized Exchange (DEX) aggregator and liquidity platform, provides superior rates for traders in DeFi and maximizes returns for liquidity providers.

KyberSwap powers 200+ integrated projects and has facilitated over US$20 billion worth of transactions for thousands of users across 15 chains since its inception. Full list of supported exchanges and networks available here.

Join our community:

KyberSwap | Twitter | Telegram | Discord | Facebook | Forum | GitHub | Docs | Kyber Network

Home > Kyber Content Hub > Post Mortem: KyberSwap Elastic Exploit November 2023

Scroll to Top