Skip to main content

7 posts tagged with "Sharing"

View All Tags

· 7 min read
Sebastian Lim

Introduction

In this monthly series, HashDit is sharing the monthly security incidents in the crypto space and what we can learn from them. For this July 2024 edition, the total losses amounted to $282.5 million, showing a 25% decrease compared to July 2023 ($377.2 million).

In this sharing, we focus on the DApps incidents. Below are the top 5 DApps incidents that DApp Developers should pay attention to.

Top 5 DApps incidents

Li.Fi protocol - $10m - Lack of Validation

Chain: Ethereum

Li.Fi protocol is a bridge aggregation protocol with DEX connectivity and cross-chain data messaging capabilities. On July 16 2024, in this incident, the GasZipFacet contract was upgraded, introducing a vulnerable code which resulted in a compromise of approximately $10 million.

Interestingly, a similar exploit 2 years ago, when Li.Fi was also compromised for the same vulnerability.

Root cause: The primary cause of the incident was no validation of swapCallData in the LibSwap.sol library. This calldata can be externally controlled in the outer function depositToGasZipERC20 method. This allows arbitrary calls whereby funds approved to this victim contract can be abused and stolen.

Onchain information:

Hack tx

Code snippet:

IMG-1 IMG-2

Rho Markets - $7.6m - Oracle Manipulation

Chain: Scroll

Rho Markets is a liquidity platform built on Scroll, based on an overcollateralized lending model (which is a fork of Compound Finance). On July 19, 2024, in this incident, a misconfigured oracle provided the wrong price of $ETH for the rETH market ($BTC price was fed instead). Thankfully, an MEV bot front ran the original hacker and was able to safeguard the $7.6 million and return them back to the project party.

Root cause: On July 16, 2024, after updating the smart contract for a new market, Rho Markets found that ETH and BTC price oracles were giving contradictory feeds due to a deployment script misconfiguration. This reversed BTC and ETH prices, creating arbitrage opportunities for MEV bots. Incorrect oracle pricing led to assets(USDC, USDT, wstETH, STONE, and wrsETH) being borrowed up to their caps.

Onchain information:

Oracle misconfiguration tx

Hack tx

Transaction snippet:

IMG-3

DoughFina - $1.8m - Lack of Validation

Chain: Ethereum

On July 12, 2024, DoughFina, a DeFi project, had its ConnectorDeleverageParaswap contract compromised, resulting in a loss of ~$1.8 million. In this attack, there was a lack of validation issue which allowed anyone to withdraw funds from the vulnerable contract.

Root cause: The primary cause of the incident was that there is lack of validation in the flash loan call back data which leads to a WETH transfer.

After invoking the flashloan method of the ConnectorDeleverageParaswap contract, the flash loan call data allowed multiple operations to be executed afterwards.

This allowed the hacker to burn AaveWETH from one of Dough’s pools. WETH is then approved to the Victim contract which can then be transferred from out to the hacker.

Onchain information:

Hack tx 1

Hack tx 2

Code snippet:

IMG-4 IMG-5

Minterest - $1.4m - Exchange rate manipulation

Chain: Mantle

Minterest is a blockchain cross-chain DeFi lending protocol that redistributes 100% of the value captured back to users. On July 15, 2024, its MUSDYToken_Mantle contract was compromised, leading to an estimate loss of ~$1.4m on Mantle (ETH and Taiko not affected).

Root cause: The exchange rate of the Minterest is dependent on the token cash balance (updated immediately during token transfers, instead of at the end of the state).

Reentrancy vulnerability in which an attacker could loan out tokens that they had previously just borrowed from the protocol.

Onchain information:

Hack tx

Code snippet:

IMG-6

Monoswap - $1.3m - Social Engineering

Chain: Blast

Monoswap is a community-driven and yield-focused v3 Decentralized Exchange built to facilitate the Blast ecosystem.. On the 24th of July, 2024, due to a social engineering exploit of one of its developers, the deployer wallet was compromised, resulting in financial losses approximating $1.3 million in ETH.

Root cause: One of Monoswap developers installed phishing software from https[:]//kakaocall[.]kr. The scammer pretended to be a VC institution to deceive the developer's trust and carried out phishing attacks.

Onchain information:

Hack tx 1

Hack tx 2

Hack tx 3

Transaction snippet:

IMG-7

Key lessons for developers

  1. Given the risk of social engineering attacks, it is essential for employees to install only trusted software and exercise heightened caution when working with third parties. Specifically, be vigilant for potential red flags, including:

    • Educate and Train Team Members:

      • Awareness Programs: Regularly conduct training sessions to educate team members about the various types of social engineering attacks, such as phishing, vishing (voice phishing), and smishing (SMS phishing).

      • Simulated Attacks: Perform simulated social engineering attacks to test and improve the team's response to real threats.

      • Trusted Software: Always verify the source before installing any software. Ensure that you download applications only from official websites or trusted platforms, and avoid using pirated or cracked versions. Additionally, check for reviews and ratings, and consult with your IT department if you are unsure about the legitimacy of the software.

    • Secure Communication Channels:

      • Encrypted Communication: Use encrypted communication channels for sensitive information and authentication processes.

      • Verification Protocols: Establish protocols for verifying the identity of individuals before sharing sensitive information or performing critical actions.

    • Limit Access and Permissions:

      • Role-Based Access Control (RBAC): Implement RBAC to ensure that team members only have access to the information and systems necessary for their role.

      • Regular Audits: Conduct regular audits of access permissions to ensure they are up-to-date and appropriate.

  2. Input validation is a crucial process - it's essential to verify all potential user inputs, especially when these inputs affect changes to the state of the system. This holds particularly true in the below scenarios:

    • Calldata Parameters: Given that attackers have the ability to craft any data, extra validation steps must be in place for calldata parameters.

    • User Approvals: During the process where the protocol contract manages users' approvals, meticulous input checks are paramount to prevent potential malicious activities.

  3. To guard against price manipulation, it's essential to ensure that updated prices cannot be influenced to reflect unexpected values. Oracles, both on-chain and off-chain types, can be employed by developers. Here's how:

    • Set Boundaries: Implementing limits can block prices from being abruptly manipulated to an impossible value, regardless of the oracle type in use.

    • Fallback Oracle: Integrate a secondary oracle as a fallback measure. This ensures that if the initial oracle fails, there is a backup in place to verify the consistency of prices. By doing so, it ensures continuous, reliable price feeds, and safeguards against single point of failure.

    • Test scripts: Test scripts can be designed to check the integrity of the data being fed into the Oracle system. By running these scripts, you can ensure that the data is accurate, complete, and consistent with the expected format and values. This helps in identifying and correcting any discrepancies early in the process.

  4. Tips to Prevent Exchange Rate Manipulation:

    • Educate and Train Team Members: Use multiple, independent oracle sources to fetch exchange rates. Aggregating data from various sources can help ensure accuracy and reduce the risk of manipulation from a single compromised source.

    • Use Strong 2FA Mechanisms: Implement validation checks to ensure the consistency and accuracy of exchange rate data. Cross-verify rates with other reliable sources to detect anomalies.

    • Monitor and Respond to Suspicious Activity: Ensure that exchange rate data is transmitted securely using encryption protocols. This helps prevent interception and tampering of data during transmission.

    • Secure Communication Channels: In the context of exchange rate systems, a reentrancy attack could be particularly damaging. For example, if an exchange rate contract is vulnerable to reentrancy, an attacker could exploit this to manipulate the exchange rates.

      • Checks-Effects-Interactions Pattern: Ensure that state changes are made before any external calls. This reduces the risk of reentrancy attacks.

      • Reentrancy Guards: Implement reentrancy guards, such as mutexes, to prevent multiple calls to a function before the first call is resolved.

Feel free to contact us at support@hashdit.io for any support needed! Stay safe!

· 8 min read
Sebastian Lim

Introduction

In this monthly series, HashDit is sharing the monthly security incidents in the crypto space and what we can learn from them. For this June 2024 edition, the total losses amounted to $56.4 million, showing a 276% increase compared to June 2023 ($15 million).

In this sharing, we focus on the DApps incidents. Below are the top 5 DApps incidents that DApp Developers should pay attention to.

Top 5 DApps incidents

Uwulend - $23.7m - Price Manipulation

Chain: Ethereum

Uwulend is a DeFi protocol where users can participate as depositors, borrowers or LP stakers. Depositors provide liquidity to the market to earn a passive income, while borrowers are able to borrow in an overcollateralized (perpetually) fashion. On June 10 2024, in this incident, the Market contracts used an unreliable averaged-out oracle which resulted in an initial compromise of $20 million.

After the project paused and unpaused the protocol, they were once again exploited for another $3.7 million just 3 days later.

Root cause: The price oracle used took 11 different prices, and used the median price as the price oracle. However, 5 of these prices were spot prices and directly under the control of the attacker. This meant that only one EMA price needed to be manipulated.

The second issue is that the input prices are in USDE, but the oracle output is in sUSDE, which currently trades around 1.08. The oracle converts between them with an owner controlled conversion factor. This conversion was set to 1.03 three months ago, and has been steadily more wrong over time as the price of sUSDE goes up with yield.

Onchain information:

Hack tx

Code snippet:

IMG-1 IMG-2

Velocore - $6.8m - Lack of validation

Chain: Linea & Zksync

On the 2nd of June, 2024, Velocore is a Layer-2 protocol that leverages ZK technology to enhance Ethereum scalability. Due to a Lack of validation vulnerability in the smart contract, Velocore experienced a security breach on June 2nd, 2024, resulting in financial losses approximating $6.8 million in ETH.

Root cause: The root cause of this compromise was due to vulnerabilities within the Balancer-style CPMM pool contract, specifically the ‘velocore__execute’ function. The vulnerability here is that effectiveFee1e9 was allowed to exceed 100% - that is 1e18 (take note of the ‘unchecked’ block). This resulted in an underflow, changing a withdrawal into a large deposit.

Onchain information:

Hack tx

Malicious upgrade tx

Code snippet:

IMG-3 IMG-4

Loopring - $5m - Social Engineering

Chain: Ethereum

Loopring is a zkRollup Layer 2. It allows for high-throughput, low-cost trading and payment on Ethereum. On June 9, 2024, in this attack, some Loopring Smart Wallets were targeted in a security breach. Subsequently, the attacker transferred assets out of the affected wallets. This resulted in a loss of approximately $5 million across the wallets.

Root cause: The attack succeeded by compromising Loopring's 2FA service, allowing the hacker to impersonate the wallet owner (by obtaining the right signature) and gain approval for the Recovery from the Official Guardian.

Onchain information:

Hack tx

Code snippet:

IMG-5

Bazaar - $1.4m - Lack of Validation

Chain: Blast

On June 10, 2024, Bazaar, a DeFi project, had its BazaarVaultBlast contract compromised, resulting in a loss of ~$1.4 million. In this attack, there was a lack of validation issue which allowed anyone to withdraw funds from the vulnerable contract.

Root cause: The vulnerable function exitPool() did not validate its caller, which means that a malicious actor could invoke this method and parse another user’s balance to withdraw their funds to himself.

Onchain information:

Hack tx

Code snippet:

IMG-6

Holograph - $1.3m - Insider Attack

Chain: Ethereum

Holograph is an omnichain tokenization protocol, enabling asset issuers to mint natively composable omnichain tokens. On June 13, 2024, the incident involved a misused HLG created on Mantle that was activated through Layerzero bridge. There was a Falsified packet that was executed on Mantle which resulted in a large mint of 1 billion HLG tokens on Ethereum, valued around $1.3 million at the time.

Root cause: It was a private key compromise that was later on confirmed by Holograph, this was an insider attack. A former contractor exploited Holograph Protocol to mint additional HLG. The malicious actor deployed an unverified contract on Mantle, which was used to mint additional HLG.

Onchain information:

Large mint tx

Mantle packet tx

Transaction snippet:

IMG-7

Key lessons for developers

  1. In light of potential insider compromises, it's crucial to apply thorough background checks for new employees. Specifically, keep an eye out for potential red flags including:

    • Preference for certain platforms: Malicious developers seem to favor using Github, often impersonating user profiles such as SuperTalentedDev726 or CryptoKnight415.

    • Use of numbers: Both email addresses and Github usernames often contain numerical sequences. It's suspected they use this as a method for tracking the identities they impersonate.

    • Asian identities: There's a tendency toward choosing Japanese (and possibly Korean) identities, often claiming prior education in Japan.

    • Prominent educational background: The falsified credentials often include elite universities in Japan, Hong Kong, and Singapore. Such institutions may include Singapore State University, Nanyang Technological University, University of Hong Kong or Hong Kong University of Science and Technology.

    • Codebase theft: While not always the case, these imposters often steal existing projects from GitHub and recondition the commit messages to reflect their assumed usernames.

    • Multiple applications: They tend to apply repeatedly for the same job, resorting to multiple email addresses for their submissions.

    • Premature expertise: They often claim experience in Solidity/EVM too early (such as in 2015), which is an unlikely scenario giving the nascent state of blockchain technology at the time.

  2. To guard against price manipulation, it's essential to ensure that updated prices cannot be influenced to reflect unexpected values. Oracles, both on-chain and off-chain types, can be employed by developers. Here's how:

    • Set Boundaries: Implementing limits can block prices from being abruptly manipulated to an impossible value, regardless of the oracle type in use.

    • Fallback Oracle: Integrate a secondary oracle as a fallback measure. This ensures that if the initial oracle fails, there is a backup in place to verify the consistency of prices. By doing so, it ensures continuous, reliable price feeds, and safeguards against single point of failure.

  3. Input validation is a crucial process - it's essential to verify all potential user inputs, especially when these inputs affect changes to the state of the system. This holds particularly true in the below scenarios:

    • Calldata Parameters: Given that attackers have the ability to craft any data, extra validation steps must be in place for calldata parameters.

    • User Approvals: During the process where the protocol contract manages users' approvals, meticulous input checks are paramount to prevent potential malicious activities.

  4. Here are five key tips to protect against social engineering attacks that compromise 2FA for Web3 protocol teams:

    • Educate and Train Team Members

      • Awareness Programs: Regularly conduct training sessions to educate team members about the various types of social engineering attacks, such as phishing, vishing (voice phishing), and smishing (SMS phishing).

      • Simulated Attacks: Perform simulated social engineering attacks to test and improve the team's response to real threats.

    • Use Strong 2FA Mechanisms

      • Hardware Tokens: Encourage the use of hardware-based 2FA tokens (e.g., YubiKey) instead of SMS-based 2FA, which is more susceptible to SIM swapping attacks.

      • App-Based 2FA: If hardware tokens are not feasible, use app-based 2FA solutions like Google Authenticator or Authy, which are more secure than SMS.

    • Monitor and Respond to Suspicious Activity

      • Anomaly Detection: Implement systems to detect and alert on unusual login attempts or behavior that could indicate a compromised account.

      • Immediate Response: Have a clear incident response plan in place to quickly address and mitigate any suspected social engineering attacks.

    • Secure Communication Channels

      • Encrypted Communication: Use encrypted communication channels for sensitive information and authentication processes.

      • Verification Protocols: Establish protocols for verifying the identity of individuals before sharing sensitive information or performing critical actions.

    • Limit Access and Permissions

      • Role-Based Access Control (RBAC): Implement RBAC to ensure that team members only have access to the information and systems necessary for their role.

      • Regular Audits: Conduct regular audits of access permissions to ensure they are up-to-date and appropriate.

Feel free to contact us at support@hashdit.io for any support needed! Stay safe!

· 7 min read
Sebastian Lim

Introduction

In this monthly series, HashDit is sharing the monthly security incidents in the crypto space and what we can learn from them. For this May 2024 edition, the total losses mounted up to $92.3 million, showing a 16% increase compared to May 2023.

In this sharing, we focus on the DApps incidents. Below are the top 5 DApps incidents that DApp Developers should pay attention to.

Top 5 DApps incidents

GoGalaGames - $21.7m - Private Key Compromise

GoGalaGames is a GameFi protocol that allows players to earn cryptocurrencies and non-fungible tokens (NFTs) through gameplay. In this incident, its minting role’s private key was compromised, leading to a mint of 5,000,000,001 GALA tokens, an estimated loss of ~$222m on ETH. Interestingly, only a portion of GALA tokens were swapped for ETH, amounting to an estimate of 5913 ETH or $22m USD.

Thankfully, funds have since been returned and sent to an address termed as Gala Fund Recovery. Also, the excess GALA tokens have been burned.

Root cause: The hacker was able to compromise the private key of the original Minter account. It is unclear if it was an internal or external attack.

Onchain information:

Mint tx

Code snippet:

IMG-1

SonneFinance - $20m - Empty Market Attack

Sonne Finance is a decentralized lending protocol for individuals, institutions and protocols to access financial services. It is a permissionless, open source and Optimistic protocol serving users on Optimism. Users can deposit their assets, use them as collateral and borrow against them. In this attack, the hacker made use of a mislapse in the protocol’s market configuration to execute an empty market attack.

Root cause: Sonne was aware of the empty market bug, and planned to:

  • timelock add a market
  • user add funds
  • timelock open up the market for use.

It would work, as long as the order was followed. However, they scheduled the supportMarket operation independently, instead of using scheduleBatch. Additionally, they opened the EXECUTOR_ROLE to everyone. This essentially allowed anyone to execute the operations in any order.

The exploited solVELO market was deployed 4 days ago without any liquidity, and added to the Unitroller 2 days later after timelock. As such, this empty market was abused with direct donation to borrow funds from other markets with liquidity.

Onchain information:

Hack tx 1

Hack tx 2

Code snippet:

IMG-2 IMG-3

ALEXLabBTC - $4.3m - Private Key Compromise

On May 15, 2024, ALEXLabBTC, a DeFi project, had an unverified contract compromised, after a malicious upgrade. The potential loss was ~$12m, however the attacker was thankfully inexperienced. The attacker was successfully able to transfer around 13.8 million STX (~$2 million) on the Stack BTC layer-2 chain.

However, on BSC where the potential damage was $4.3m, a white hat was able to secure funds, and eventually returned all 100% to the project team. On ETH, the exploiter tried to steal assets notionally worth around $5 million, but failed to do so. ALEX Lab later announced they were able to recover or secure around $4.5 million of those assets (through CEX).

Root cause: Using compromised private keys obtained via a phishing attack. The exploiter was able to upgrade the code to a malicious logic contract and drain some assets from the ALEX protocol.

Onchain information:

Hack tx

Malicious upgrade tx

Code snippet:

IMG-4

Pump.fun - $1.9m - Insider Attack

Pump.fun is a Solana Based Memecoin Launchpad that allows users to deploy their own Solana tokens. The incident involved a former employee gaining pump.fun's admin privileges, resulting in the misappropriation of approximately 12,300 SOL, valued around $1.9 million at the time.

Root cause: A former employee, illegitimately taken access of the withdraw authority using their privileged position at the company, used flash loans on a Solana lending protocol.

The loans were used to borrow SOL to buy out as many memecoins until they hit 100% on their bonding curves, which allowed the exploiter to gain liquidity to repay the flash loans. This affected roughly $1.9 million out of a total of $45 million in liquidity within the bonding curve contracts during a specific timeframe.

Onchain information:

Hack tx

Code snippet:

IMG-5

NORMIE - $800k - Price Manipulation

On the 26th of May, 2024, the Base network suffered a damaging exploit targeted at the memecoin, NORMIE. Due to a vulnerability in the smart contract, there was an unfortunate loss of approximately 224.98 ETH.

Root cause: The fundamental catalyst for the exploit was a flaw in the smart contract logic. This flaw granted the attacker the capability to trick the contract into acknowledging their address as a privileged one. This deceptive maneuver allowed them to mint tokens without authorization, circumventing crucial security measures, and consequently leading to a significant financial loss.

Onchain information:

Hack tx

Code snippet:

IMG-6 IMG-7

Key lessons for developers

  1. In light of potential insider compromises, it's crucial to apply thorough background checks for new employees. Specifically, keep an eye out for potential red flags including:

    • Preference for certain platforms: Malicious developers seem to favor using Github, often impersonating user profiles such as SuperTalentedDev726 or CryptoKnight415.

    • Use of numbers: Both email addresses and Github usernames often contain numerical sequences. It's suspected they use this as a method for tracking the identities they impersonate.

    • Asian identities: There's a tendency toward choosing Japanese (and possibly Korean) identities, often claiming prior education in Japan.

    • Prominent educational background: The falsified credentials often include elite universities in Japan, Hong Kong, and Singapore. Such institutions may include Singapore State University, Nanyang Technological University, University of Hong Kong or Hong Kong University of Science and Technology.

    • Codebase theft: While not always the case, these imposters often steal existing projects from GitHub and recondition the commit messages to reflect their assumed usernames.

    • Multiple applications: They tend to apply repeatedly for the same job, resorting to multiple email addresses for their submissions.

    • Premature expertise: They often claim experience in Solidity/EVM too early (such as in 2015), which is an unlikely scenario giving the nascent state of blockchain technology at the time.

  2. To guard against price manipulation, it's essential to ensure that updated prices cannot be influenced to reflect unexpected values. Oracles, both on-chain and off-chain types, can be employed by developers. Here's how:

    • Set Boundaries: Implementing limits can block prices from being abruptly manipulated to an impossible value, regardless of the oracle type in use.

    • Fallback Oracle: Integrate a secondary oracle as a fallback measure. This ensures that if the initial oracle fails, there is a backup in place to verify the consistency of prices. By doing so, it ensures continuous, reliable price feeds, and safeguards against single point of failure.

  3. Keys should be properly secured, are rotated regularly and have some level of decentralization. Adopt a zero-trust model.

  4. For projects utilizing lending protocols:

    • When deploying a new market (especially for Compound / Aave v2 forks), ensure that it is first initialized with 0 Collateral Factor and deploy with small deposit to lock dead shares.
    • Disallow deposits when the pool price is out of the base range of liquidity.
    • Increase precision on price change thresholds and deposit ratios.
    • For those allowing single-sided pool deposits, add a conditional statement to prevent deposits of any ratio of assets so long as vault is single-sided.

Feel free to contact us at support@hashdit.io for any support needed! Stay safe!

· 7 min read
Sebastian Lim

Introduction

In this monthly series, HashDit is sharing the monthly security incidents in the crypto space and what we can learn from them. For this Apr 2024 edition, the total losses mounted up to $2.7 million, showing a 54% decrease compared to April 2023.

In this sharing, we focus on the DApps incidents. Below are the top 5 DApps incidents that DApp Developers should pay attention to.

Top 5 DApps incidents

XBridge - $1.03m - Wrong Proxy Upgrade

XBridge is a Bridge / Cross-Chain protocol that allows users to bridge funds from one chain to another. In this attack, a vulnerable logic contract was introduced in a proxy contract upgrade, allowing the attacker to drain 466,490,205 STC tokens, 511,424,527 SRLTY tokens and 11,165,018 Mazi tokens, amounting to ~$1.03m. Interestingly, the attacker did not liquidate all tokens, and only swapped ~$192k to BNB and deposited it into Tornado Cash, leaving some tokens in his wallet.

Root cause: The listToken function in the target contract does not verify msg.sender and _tokenOwner. Essentially, as long as _baseToken==_correspondingToken, the attacker can set the key variable _tokenOwner to msg.sender which is himself, and subsequently call withdrawTokens to extract the baseToken funds directly.

The upgrade introduced a wrong mapping _tokenOwner instead of using TokenOwner (which was correctly set up in the old logic contract), anyone can thus assume _tokenOwner and withdraw tokens.

Onchain information:

Bug introduced in Upgrade tx

Hack tx

Code snippet:

IMG-1

FinanceChainge - $710k - Lack of Validation

FinanceChainge is a DeFi protocol, which is known as a liquid cross-chain aggregator. In this attack, the hackers exploited the swap function with a malicious payload. The hack amount is ~ $710k. Interestingly, the sole victim is 0x8a4aa176007196d48d39c89402d3753c39ae64c1, which is linked to the project team and hence likely funds belonging to the project.

Root cause: The swap() function had a bug which allowed hackers to exploit users’ allowance given to this victim contract.

Onchain information:

Hack tx 1

Hack tx 2

Code snippet:

IMG-2

OpenLeverage - $226k - Internal accounting

OpenLeverage is a DeFi protocol which operates as a DEX, allowing users to swap tokens. In this rather complicated attack, the attacker was able to compromise the OpenLev contract on BSC. The exploit consisted of a sequence of arbitrary external calls, taking advantage of inconsistency in the accounting for borrowers.

Root cause: The attack occurred due to a discrepancy in the accounting process, which comprised two separate transactions.

Firstly, the attacker set up a "margin position" in the OpenLevV1 contract using the marginTrade function. This function call permitted an additional position creation with minimal collateral through an untrusted external call to the OpBorrowing contract. This position was ultimately liquidated.

However, both OpenLevV1 and OpBorrowing contracts use the LToken contract for their transactions. Consequently, the debt of the margin position was unintentionally cleared in the liquidation process.

In the second transaction, the attacker exploited this situation. They used the payoffTrade function, bypassing the health check, and drained all the collateral from the margin positions.

Onchain information:

Hack tx 1

Hack tx 2

Code snippet:

IMG-3 IMG-4

NGFS - $190k - Lack of Validation

NGFS is a DeFi token on BSC. In this attack, the attacker was able to manipulate his own token balance due to a lack of validation for a privileged function. As such, he could simply increase his balance and dump the tokens on the open market.

Root cause: The function delegateCallReserves() can be called only once, and is supposed to be set up during the initialization phase, however it was left untouched. As such, anyone could assume _uniswapV2Proxy position and then call the setProxySync() method to set an arbitrary _uniswapV2Library. Lastly, within the reserveMultiSync() function, the attacker could set a large balance for himself since he has _uniswapV2Library privilege.

Onchain information:

Hack tx

Code snippet:

IMG-5

ATM - $180k - Price Manipulation

ATM is a DeFi token on BSC. In this attack, the attacker was able to make use of the funds in the ATM contract to add liquidity to the pool. At the same time, he could invoke the skim function to drain excess funds from the pair.

Root cause: The _transfer routine can be exploited by directly transferring funds to the pair contract. This triggers the distributeCurrency function, adding liquidity from the perspective of the ATM contract. The attacker could then profit by simply calling skim on the pair.

Onchain information:

Hack tx 1

Hack tx 2

Code snippet:

IMG-6

Key lessons for developers

  1. Input validation is a crucial process - it's essential to verify all potential user inputs, especially when these inputs affect changes to the state of the system. This holds particularly true in the below scenarios:

    • Calldata Parameters: Given that attackers have the ability to craft any data, extra validation steps must be in place for calldata parameters.

    • User Approvals: During the process where the protocol contract manages users' approvals, meticulous input checks are paramount to prevent potential malicious activities.

  2. To guard against price manipulation, it's essential to ensure that updated prices cannot be influenced to reflect unexpected values. Oracles, both on-chain and off-chain types, can be employed by developers. Here's how:

    • Set Boundaries: Implementing limits can block prices from being abruptly manipulated to an impossible value, regardless of the oracle type in use.

    • Fallback Oracle: Integrate a secondary oracle as a fallback measure. This ensures that if the initial oracle fails, there is a backup in place to verify the consistency of prices. By doing so, it ensures continuous, reliable price feeds, and safeguards against single point of failure.

  3. Upgrading proxy code should be taken very seriously and should require several checks such as:

    • Thorough Testing: Conduct rigorous testing before deploying any updates to ensure that the changes will not disrupt existing functionalities or introduce new vulnerabilities.

    • Code Audits: Always get your code audited by a third party. It's crucial to have another set of eyes inspect your code, as they may spot issues that you've overlooked.

    • Pause Functionality: Make sure that your contract has a 'pause' functionality. In case something goes wrong, this function allows halting the operations until the issue is fixed.

  4. Addressing internal accounting errors and effectively handling external arbitrary calls are critical for crypto developers, especially for lending projects which involve complex financial transactions. Here are some recommendations:

    • Sequencing Transactions: Consider sequencing transactions appropriately. Generally, it's safer to make state changes before conducting external calls.

    • External Calls: Be extremely careful while interacting with third-party contracts. They should be treated as potentially malicious. Avoid state changes after making a call to an external contract.

    • Precise Accounting: Keep accurate and precise accounting to make sure all balances tally at the end of each operation. This is primarily to ensure that no tokens are lost or mistakenly created during transactions.

    • Debt and Collateral Management: Carefully track and manage computational handling of debt and collateral. Errors in management or calculation can lead to vulnerabilities such as unforeseen liquidations or insolvency.

    • Limit Permissions: Limit the permissions of the contract that makes external calls to only what's necessary to reduce your contract's attack surface.

Feel free to contact us at support@hashdit.io for any support needed! Stay safe!

· 7 min read
Sebastian Lim

Introduction

In this monthly series, HashDit is sharing the monthly security incidents in the crypto space and what we can learn from them. For this Mar 2024 edition, the total losses mounted up to $146 million, showing a 50% decrease compared to March 2023.

Of which, they are split across 2 sections: DApps ($114m) and Phishing ($32m).

In this sharing, we focus on the DApps incidents. Below are the top 5 DApps incidents that DApp Developers should pay attention to.

Top 5 DApps incidents

Munchables - $62.5m - Insider Attack

Munchables is a GameFi and NFT protocol. In this attack, it was confirmed to be an Insider Attack where a rogue employee was malicious, gaining access to a privileged account. After malicious logic was introduced in a proxy contract upgrade, 62M funds were transferred out by the attacker. Thankfully, after some negotiation and investigation, the funds were eventually returned.

Root cause: Malicious developer was hired and suspected to be linked to DPRK, and had bad intentions right from the start. It was found that the malicious logic was already introduced during deployment and the bad actor used manual manipulation of the getLocked storage slot to assign himself an enormous Ether balance in the contract, so that his locked amount would bypass the withdrawal checks.

Onchain information:

Hack tx

Malicious contract upgrade

Code snippet:

Unverified contract

IMG-1 IMG-2

PrismaFi - $12m - Lack of Validation

PrismaFi is a DeFi protocol, which is known as a non-custodial and decentralized Ethereum LST & LRT backed stablecoins. In this attack, the hackers bypassed the migrate function and called the flash loan directly with carefully crafted input data.

The flash loan's callback function, onFlashloan(), was called. The lack of proper checks allowed the hackers to close a trove owner's Trove and immediately reopen it within the same TroveManager. The transaction caused the owner's position to be closed and reopened, resulting in the trove owner having a new position with the same debt but less collateral and the difference in collateral sitting in the zap contract.

The hackers then opened a new Trove and used the MigrateTroveZap contract to migrate it, effectively using the remaining collateral for their own Trove. Finally, the hackers closed their Trove and took the profits.

Root cause: The root cause of the vulnerability was twofold:

  1. By directly calling the onFlashloan() function, the user could manipulate other trove managers positions.
  2. The contract allowed for a mismatch between the collateral in the initial position and the collateral in the new position, with the difference being susceptible to being taken.

Onchain information:

Hack tx 1

Hack tx 2

Hack tx 3

Code snippet:

IMG-3

WooFi - $8.7m - Price Manipulation

WooFi is a DeFi protocol which operates as a DEX, allowing users to swap tokens. In this attack, the attacker was able to compromise the WooPPV2 contract on Arbitrum. The exploit consisted of a sequence of flash loans that took advantage of low liquidity to manipulate the price of WOO in order to repay the flash loans at a cheaper price.

Root cause: There were 2 configuration issues.

  1. A previously unidentified error resulted in the price being adjusted far outside of the expected range ($0.00000009)
  2. The fallback check, normally executed against Chain Link, didn’t cover the WOO token price.

Onchain information:

Hack tx 1

Hack tx 2

Code snippet:

IMG-4 IMG-5

SSS_HQ - $4.8m - Function wrongly implemented

SSS_HQ or Super Sushi Samurai is a GameFi platform on Blast chain. In this attack, thankfully a White Hat was able to spot the bug before any malicious actor, where he increased his own balance by repeatedly transferring to himself. He subsequently swapped these tokens in the liquidity pool and protected the liquidity of ~$4.8m.

Root cause: The tax transfer logic is wrongly implemented in the _update method of the SSS.sol code. The _balances[to] value is incremented before the _balances[from] value is updated (done within the _postCheck method), seen in the first picture. As such, the balance of the to address uses the stale value i.e original balance, seen in the second picture. This is summed with the amount variable, stored in the toBalance variable and subsequently overwriting the _balances[from] in the last statement, almost doubling the sender’s balance.

Onchain information:

White-hat Hack tx

Code snippet:

IMG-6 IMG-7

Unizen - $2.1m - Lack of Validation

Unizen is a DeFi protocol which operates as a DEX across multiple chains. In this instance, the attack happened on Ethereum, just 5 hours after the victim proxy was upgraded to a vulnerable logic contract. The vulnerable contract introduced a function 0x1ef29a02 which allowed arbitrary calldata to be sent.

Root cause: Lack of validation in a Swap related function (which allowed arbitrary transferFrom calls, specifying the From, To and Amount parameters). As such, victims that have approved their funds to this contract will be affected.

Onchain information:

Hack tx

Code snippet: Unverified contract

IMG-8 IMG-9 IMG-10

Key lessons for developers

  1. In light of potential insider compromises, it's crucial to apply thorough background checks for new employees. Specifically, keep an eye out for potential red flags including:

    • Preference for certain platforms: Malicious developers seem to favor using Github, often impersonating user profiles such as SuperTalentedDev726 or CryptoKnight415.

    • Use of numbers: Both email addresses and Github usernames often contain numerical sequences. It's suspected they use this as a method for tracking the identities they impersonate.

    • Asian identities: There's a tendency toward choosing Japanese (and possibly Korean) identities, often claiming prior education in Japan.

    • Prominent educational background: The falsified credentials often include elite universities in Japan, Hong Kong, and Singapore. Such institutions may include Singapore State University, Nanyang Technological University, University of Hong Kong or Hong Kong University of Science and Technology.

    • Codebase theft: While not always the case, these imposters often steal existing projects from GitHub and recondition the commit messages to reflect their assumed usernames.

    • Multiple applications: They tend to apply repeatedly for the same job, resorting to multiple email addresses for their submissions.

    • Premature expertise: They often claim experience in Solidity/EVM too early (such as in 2015), which is an unlikely scenario giving the nascent state of blockchain technology at the time.

  2. Input validation is a crucial process - it's essential to verify all potential user inputs, especially when these inputs affect changes to the state of the system. This holds particularly true in the below scenarios:

    • Calldata Parameters: Given that attackers have the ability to craft any data, extra validation steps must be in place for calldata parameters.

    • User Approvals: During the process where the protocol contract manages users' approvals, meticulous input checks are paramount to prevent potential malicious activities.

  3. To guard against price manipulation, it's essential to ensure that updated prices cannot be influenced to reflect unexpected values. Oracles, both on-chain and off-chain types, can be employed by developers. Here's how:

    • Set Boundaries: Implementing limits can block prices from being abruptly manipulated to an impossible value, regardless of the oracle type in use.

    • Fallback Oracle: Integrate a secondary oracle as a fallback measure. This ensures that if the initial oracle fails, there is a backup in place to verify the consistency of prices. By doing so, it ensures continuous, reliable price feeds, and safeguards against single point of failure.

  4. Ensuring that the deployed function aligns with the intended objective is a critical requirement, especially for high-stakes operations such as accounting. This assurance can be achieved through:

    • Thorough Testing: Execute comprehensive fuzz testing and edge case analysis. This doesn't solely ensure correct function logic, it also helps to identify potential flaws and security vulnerabilities that might otherwise be overlooked.

    • Use Trusted Templates: Consider using trusted codebases, such as Openzeppelin, as a foundation for your code. These established libraries have been vetted extensively by the developer community, reducing the likelihood of introduction of unexpected bugs or issues.

Feel free to contact us at support@hashdit.io for any support needed! Stay safe!

*Unverified contracts screenshots courtesy of Dedaub’s decompiler!

· 5 min read
Sebastian Lim

Monthly Incident Sharing (Feb 2024)

Introduction

In this monthly series, HashDit is sharing the monthly security incidents in the crypto space and what we can learn from them. For this Feb 2024 edition, the total losses mounted up to $132 million, showing a 141% increase compared to February 2023.

Of which, they are split across 3 sections: DApps ($65m), CEXs ($62m) and Phishing ($5m).

In this sharing, we focus on the DApps incidents. Below are the top 5 DApps incidents that DApp Developers should pay attention to.

Top 5 DApps incidents

PlayDapp - $30m - Private Key Compromise

PlayDapp is a GameFi and Web3 Service protocol. In this attack, the hacker was able to compromise the original Minter account. As such, a malicious minter account was added and he minted 200m $PLA tokens, before dumping them on the open market.

Since then, the token transfer method has been paused and the token is planning to be migrated to a new address $PDA.

Root cause: The hacker was able to compromise the private key of the original Minter account. It is unclear if it was an internal or external attack.

Onchain information:

Add Malicious Minter tx

Malicious Mint tx

Vulnerable code snippet:

IMG-1 IMG-2

Ronin Network’s Jihoz - $10m - Private Key Compromise

Ronin Network is a bridge protocol allowing cross chain of funds. In this attack, Ronin Network’s cofounder Jihoz had his wallet compromised. However, the attack is limited to only personal accounts, and does not affect operations of Sky Mavis and the Ronin chain.

Root cause: The hacker was able to compromise the private key of Jihoz’s wallet. As such, his assets were stolen from there.

Onchain information:

Vulnerable code snippet:

IMG-3 IMG-4 IMG-5

Shido - $3.3m - Private Key Compromise

Shido is a L1 blockchain protocol which combines the interoperability of Cosmos, and the development power of EVM and WASM. In this attack, the attacker was able to compromise the StakingV4Proxy owner's wallet on Ethereum, upgrading to a malicious logic, withdrawing $SHIDO tokens and dumping them on the open market.

Root cause: The hacker was able to compromise the private key of StakingV4Proxy’s owner wallet. It is unclear if it was an internal or external attack.

After transferring ownership to a malicious owner, he immediately upgrades the StakingV4Proxy contract with a malicious withdrawToken() function that withdraws all $SHIDO tokens from the contract.

Onchain information:

StakingV4Proxy owner transfer tx

StakingV4Proxy upgrade tx

Withdraw all $SHIDO tokens tx

Vulnerable code snippet:

IMG-6 IMG-7

Seneca - $3.1m - Lack of Validation

Seneca Protocol is a DeFi lending platform and stablecoin issuer. In this attack, the attacker was able to compromise approximately 1,385 PT-Kelp rsETH from a Seneca collateral pool. He subsequently swapped these tokens for approximately $3 million worth of ETH.

Root cause: There is a lack of validation check for the user input data in the performOperations() function. This bug allows any account to call the function while specifying OPERATION_CALL as the action to be performed, allowing an exploiter to arbitrarily invoke external calls to steal funds from approving users.

Onchain information:

Hack tx on Ethereum

Hack tx on Arbitrum

Vulnerable code snippet:

IMG-8 IMG-9 IMG-10

BlueberryFDN - $1.6m - Oracle Misconfiguration

BlueberryFDN is a DeFi protocol which allows lending and borrowing of funds across chains. In this instance, the attack was front-runned by a whitehat, c0ffeebabe.eth. The vulnerability was due to the lending contract's incorrect handling of price decimals. As such, the attacker was able to borrow all the liquidity of three lending pools (OHM, USDC, WBTC) with extremely low collateral, since the assets borrowed are under-estimated, due to the non-normalized price.

Root cause: There was an incorrect usage of the oracle because the oracle always returns prices scaled to 18 decimals, thus causing assets that have less than 18 decimals to be undervalued significantly when being borrowed.

On Ethereum, WETH has a decimal of 18, OHM has a decimal of 9, USDC has a decimal of 6, and WBTC has a decimal of 8. Since BlueberryProtocol’s price oracle scales all token prices based on a decimal of 18, this caused the value of OHM to shrink by 1e9, USDC by 1e12, and WBTC by 1e10. As a result, the attacker managed to borrow assets worth 460 ETH by only collateralizing 1 ETH.

Onchain information:

Hack tx

Code snippet:

IMG-11

Key lessons for developers

  1. Keys should be properly secured, rotated regularly and have some level of decentralization. Adopt a zero-trust model. Conduct proper background checks for new employees in view of insider compromises.
  1. Validation is important - ensure all possible user inputs are checked for state changing methods. This is especially true for calldata parameters where attackers can craft any data and when the protocol contract handles users’ approvals.
  1. Proper handling of decimals in different tokens used in the protocol is fundamental, particularly when calculating token price values. Furthermore, guaranteeing that the price oracles used in the protocol are normalized to the expected decimals is critical. Price oracles provide current and accurate token prices, thus any discrepancies might lead to significant errors in token pricing and overall system operations.

Feel free to contact us at support@hashdit.io for any support needed! Stay safe!

· 4 min read
Sebastian Lim

Monthly Incident Sharing (Jan 2024)

Introduction

In this monthly series, HashDit is sharing the monthly security incidents in the crypto space and what we can learn from them.

For this Jan 2024 edition, the total losses mounted up to $153 million, showing a staggering 453% increase compared to January 2023.

Top 5 DApps incidents

Orbit Chain - $81.5m

Orbit Chain is a Bridge protocol, which uses the model of locking collateral on the source chain to mint wrapped tokens on the destination chain. In this attack, the hacker was able to compromise 1 of the bridge’s vault and steal its funds. Hack tx

Root cause: Backend compromise. The hacker was able to produce 15 correct Signer keys (v, r, s values), although the threshold needed was just 7.

Vulnerable code snippet:

IMG-1

Magic Internet Money (MIM) - $6.5m

Magic Internet Money is a DeFi protocol which allows lending and borrowing of funds. In this attack, the attacker was able to compromise 1 of the protocol’s markets and steal funds. Hack tx

Root cause: The borrow function in CauldronV4 contracts was vulnerable to manipulation of the part parameter (the user’s share of total debt) via repeatedly borrowing and repaying an asset, taking advantage of the rounding error.

Vulnerable code snippet:

IMG-2 IMG-3 IMG-4 IMG-5

Gamma Strategies - $4.6m

Gamma Strategies is a DeFi protocol which allows active liquidity management and market making strategies. In this attack, the attacker was able to compromise 1 of the protocol’s vaults and steal funds. Hack tx

Root cause: The liquidity ratio checker function erroneously allowed for deposits in any ratio so long as the contents within the vault were single-sided. This allowed for a disproportionate amount of token 0 being deposited, gaining more shares than expected. A second issue was there was no check for the current tick to be within the base position’s lower and upper tick (only a check for the tick change)

Vulnerable code snippet:

IMG-6 IMG-7 IMG-8 IMG-9

Radiant - $4.4m

Radiant is a DeFi protocol which allows lending and borrowing of funds across chains. In this attack, the attacker was able to compromise 1 of the protocol’s markets and steal funds. Hack tx

Root cause: "New/empty market" exploit. It is a known vulnerability to the combination of a rounding error and a totalSupply value of 0. Bug introduced in recent upgrade.

Vulnerable code snippet:

IMG-10

Socket Dot Tech - $3.3m

Socket Dot Tech is an Interoperability protocol bringing seamless connectivity across blockchains. In this attack, the attacker was able to compromise 1 of the protocol’s vaults and steal funds. Hack Tx

Root cause: Unsafe call in the performAction() function. The attacker constructed calldata in the swapExtraData parameter to call transferFrom() of arbitrary tokens, transferring tokens approved to the contract by other users to the attacker's address. Bug was introduced in the recent proxy upgrade.

Code snippet:

IMG-11

Key lessons for developers

  1. Keys should be properly secured, rotated regularly and have some level of decentralization. Adopt a zero-trust model. Conduct proper background checks for new employees in view of insider compromises.
  1. Validation is important - ensure all possible user inputs are checked for state changing methods. This is especially true for calldata parameters where attackers can craft any data and when the protocol contract handles users’ approvals.
  1. Rounding in Solidity always rounds down. As such, it is important to perform multiplication before division and to round down for the user during withdrawals, and round up during deposits. Consider increasing precision during calculations to avoid unexpected manipulation attacks.

    However, in the latest donation attacks for lending protocols, we see that the usual rule to favor protocol for calculations is no longer sufficient. There must be better health checks for bad debt as well, at the end state of a transaction.

  1. For projects utilizing lending protocols:

    • When deploying a new market (especially for Compound / Aave v2 forks), ensure that it is first initialized with 0 Collateral Factor and deploy with small deposit to lock dead shares.
    • Disallow deposits when the pool price is out of the base range of liquidity.
    • Increase precision on price change thresholds and deposit ratios.
    • For those allowing single-sided pool deposits, add a conditional statement to prevent deposits of any ratio of assets so long as vault is single-sided.
  2. Always engage a security auditor to review all code upgrades before they are deployed on chain. This prevents new bugs from being introduced.

Feel free to contact us at support@hashdit.io for any support needed! Stay safe!