GithubHelp home page GithubHelp logo

manifoldfinance / defi-threat Goto Github PK

View Code? Open in Web Editor NEW
484.0 22.0 53.0 13.75 MB

a globally-accessible knowledge base of adversary tactics and techniques based on real-world observations on decentralized finance

License: Mozilla Public License 2.0

JavaScript 100.00%
defi threat cve solidity infosec ethereum erc20 erc721 defi-threat threat-matrix

defi-threat's Introduction

Decentralized Finance Threat Matrix

Advisories

We are now publishing Security Advisories https://github.com/manifoldfinance/defi-threat/security/advisories

Link to the latest published ones here

Changes

v3.0.3 New attack: Secret Size Attack New Category: Interchain, id: 006

v3.0.2 New attacks such as:
Ex Post/Ex Ante Reorg (On-Chain),
Compiler not Optimizing errors (Solidity),
BGP Routing Hijacking (Off-chain) and more.

Abstract

This work is inspired by attack.mitre.org. Please use attack for "normal" InfoSec/Dev/Sys security check-listing, this is meant to be specialized towards the unique issues brought about in blockchain/cryptocurrency applications (i.e. protocols).

Repository Structure

  • libtx: transaction library with example transactions from hacks in a UML format

  • src: Source of the latest DeFi Threat Mapping and Matrix. Provided in .mediawiki and .tsv formats.

v4 Draft of Threat Matrix

Market Attacks Economic Attacks Off-Chain Attacks On-Chain Attacks Solidity-Specific Attacks
Front-Running In Arrears Liability Price Feed Timestamp Dependence Integer Overflow and Underflow
Coordinated Attack Insufficient Gas Griefing Quote Stuffing Admin Key Exploits DoS with (Unexpected) Revert
Liquidity Pocket Token Inflation Spoofing Timelock Exploits DoS with Block Gas Limit
Quote Stuffing Circulating Supply Attack Credential Access Lateral Movements Arithmetic Over/Under Flows
Wash Trading Gas Griefing (DoS) Reentrancy Multi-Sig Key Exploits Forcibly Sending Ether to a Contract
Ramping The Market Network Congestion (uDoS) Privilege Escalation Miner Cartel Attacks Delegatecall
Cornering The Market Liquidity Squeeze Credential Access Finality Exploits Entropy Illusion
Churning Governance Cartels Encryption Protections Honeypot Attacks Short Address/Parameter Attack
Flash Loans Interlocking Directorate Phishing Red Queen Attacks Uninitialized Storage Pointers
Aggregated Transactions Governance Attack Unicode Exploits Sole Block Synchronization Floating Points and Numerical Precision
Bulge Bracket Transactions Slippage Exploit API Transaction Pool Right-To-Left-Override Control Character (U+202E)
Layering Safety Check Exploits DNS Attacks Performance Fee Minting Delegatecall to Untrusted Callee
Spoofing Circulating Supply Dump Transaction Pool Front-Running Requirement Violation
Order Book Flash "Straddle" Checksum Address Sandwich Attacks Shadowing State Variables
Market Index Calculation Attack Structuring Siphon Funds Second System Effector Transaction Order Dependence
Flash Crash Stalking Horse Influencer Attacks Backrunning Assert Violation
Repo Like Asset Price Divergence Synthetic Mint Spread Block Producer Cartel Uninitialized Storage Pointer
Excessive Leverage Reserve Asset Liquidity Manipulation Syscall Exploit Unlimited Permissions on Token Approval Unprotected Ether Withdrawal
Breaking the "Buck" Stable Reserve Asset Manipulation Container Privilege Escalation Naked Call Floating Pragma
Fake News Price Induced Oracle Volatility Keyctl Misuse (syscall) Block Constructor Cartel Outdated Compiler Version
Nested Bot Fake Token Trading Pair Supply Chain Dependency Malicious Airdrop Function Default Visibility
Audience of Bots Volume Manipulation by Re-circulating Flashloan Compiled Output Destructuring Const Values Oracle HALT by MultiSig msg.sender
Arbitrage Exploit Persistent De-Peg Instability Browser in the Browser Attack Ex Ante Reorg Wallet Balance
Cascading Loan Failure Unexpected Fee on Transfer Man in the Blotter Ex Post Reorg Compiler Optimizer Not Optimizing
BGP Routing Nonstandard Proxy Implementation Math Operations Differ in Certain Pragmas
IP4/IP6 Misconfiguration Tyranny of the Majority Uninitialized Contract

v3 Threat Matrix

version v3.0.3/2022.08

001 002 003 004 005
Market Attacks Economic Attack Off-Chain On-Chain Solidity
Front-Running In Arrears liability Price Feed Timestamp Dependence Integer Overflow and Underflow
Coordinated Attack Insufficient gas griefing Quote Stuffing Admin Key DoS with (Unexpected) revert
Liquidity Pocket Token Inflation Spoofing Timelock DoS with Block Gas Limit
Quote Stuffing Circulating Supply Attack Credential Access Lateral Movements Arithmetic Over/Under Flows
Wash Trading Gas Griefing (DoS) Reentrancy Multi-Sig Keys Forcibly Sending Ether to a Contract
Ramping The Market Network Congestion (uDoS) Privilage Esclation Miner Cartel Delegatecall
Cornering The Market Liquidity Squeeze Credential Access Finality Entropy Illusion
Churning Governance Cartels Encryption Protections Honeypot Short Address/Parameter Attack
Flash Loans Interlocking Directorate Phishing Red Queen Uninitialised Storage Pointers
Aggregated Transactions Governance Attack Unicode Exploits Sole block synchronization Floating Points and Numerical Precision
Bulge Bracket Transactions Slippage Exploit API Transaction Pool Right-To-Left-Override control character (U+202E)
Layering Safety Check Exploits DNS Attacks Performance Fee Minting Delegatecall to Untrusted Callee
Spoofing Circulating Supply Dump Transaction Pool Front-Running Requirement Violation
Order Book Flash "Straddle" Checksum Address Sandwhiching Shadowing State Variables
Market Index Calculation Attack Structuring Siphon Funds Second System Effector Transaction Order Dependence
Flash Crash Stalking Horse Influencers' Backrunning Assert Violation
Repo Like Asset Price Divergance Synthetic Mint Spread Block Producer Cartel Uninitialized Storage Pointer
Excessive Leverage Reserve Asset Liquidity Manipulation Syscall Exploit Unlimited Permissions on Token Approval Unprotected Ether Withdrawal
Breaking the "Buck" Stable Reserve Asset Manipulation Container Priv. Esclation Naked Call Floating Pragma
"Fake" News Price Induced Oracle Volatility Keyctl missuse (syscall) Block Constructor Cartel Outdated Compiler Version
Nested Bot Fake Token Trading Pair Supply Chain Dependency MaliciousAirdrop Function Default Visibility
Audience of Bots Volume Manipulation by re-circulating flashloan Compiled output destructuring const values Oracle HALT by MultiSig msg.sender
Arb. Exploit Persistant de-peg instability Browser in the Browser attack Ex Ante Reorg Wallet Balance
Cascading Loan Failure Unexpected Fee on Transfer Man in the Blotter Ex Post Reorg Compiler Optimizer not Optimizing
BGP Routing Nonstandard Proxy Implementation Math operations differ in certain pragmas
IP4/IP6 misconfiguration Tyranny of the Majority Uninitialized Contract
Secret Size Attack

v2 Matrix

For Reference use only!

Protocol / Interaction Based Blockchain Transaction Based Non-Blockchain Sources Blockchain Sources SWC Registry (Solidity Exploits)
Market Attacks Economic Attack Off-Chain On-Chain Solidity
Front-Running Front-Running Price Feed Timestamp Dependence Integer Overflow and Underflow
Coordinated Attack Insufficient gas griefing Quote Stuffing Admin Key DoS with (Unexpected) revert
Liquidity Pocket Token Inflation Spoofing Timelock DoS with Block Gas Limit
Quote Stuffing Circulating Supply Attack Credential Access Lateral Movements Arithmetic Over/Under Flows
Wash Trading Gas Griefing (DoS) Reentrancy Multi-Sig Keys Forcibly Sending Ether to a Contract
Ramping The Market Network Congestion (uDoS) Privilege Escalation Miner Cartel Delegatecall
Cornering The Market Liquidity Squeeze Credential Access Finality Entropy Illusion
Churning Smurfing Encryption Protections Short Address/Parameter Attack
Flash Loans Phishing Uninitialised Storage Pointers
Aggregated Transactions Unicode Exploits Floating Points and Numerical Precision
Bulge Bracket Transactions API Right-To-Left-Override control character (U+202E)
Layering Blockchain Transaction Based DNS Attacks Delegatecall to Untrusted Callee
Spoofing Governance Attack Transaction Pool Transaction Pool Requirement Violation
Order Book Interlocking Directorate Checksum Address Shadowing State Variables
Market Index Calculation Attack Governance Cartels Siphon Funds Transaction Order Dependence
Flash Crash Assert Violation
Repo Stalking Horse Synthetic Mint Spread Sole block synchronization Uninitialized Storage Pointer
Excessive Leverage Syscall Exploit Unprotected Ether Withdrawal
Breaking the "Buck" Container Priv. Esclation Floating Pragma
"Fake" News Keyctl missuse (syscall) Outdated Compiler Version
Nested Bot Function Default Visibility
Audience of Bots Influencers'
Arb. Exploit
Slippage Exploit
Safety Check Exploits
Circulating Supply Dump
Governance Cartel
Flash "Straddle"
Structuring
Back-Running

UML Diagrams of Real World Attacks

Example: Fake Trading Volume on UniswapV2

Contributions and Acknowledgements

Ali Atiia
John Mardlin
Raul Jack
samczsun
Sam Bacha
James Zaki

v1 Sheet

DeFi Sec Matrix Sheet

v2 Sheet

DeFi Sec Page

  • Updates to the Sheet can be found in in the 'legend' section

License

Software Components under Mozilla Public License 2.0

CVE/SWC are licensed under their respective author's licenses.

Everything else is under CC-2.5-NC-ND. If you would like an exemption to this license pleasae contact: [email protected]

defi-threat's People

Contributors

marcoworms avatar sambacha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

defi-threat's Issues

Commit-Reveal schema: bias via abort

Bias via Abort

In the commit-then-reveal protocol each user chooses a secret and shares their commitment to the secret with other users. Later, users reveal their secrets and a random value is calculated by combining the secrets. This approach is susceptible to attacks where a user can choose not to reveal their secret to bias the randomness generation to their advantage "bias-via-abort"

Citation: E. Syta, P. Jovanovic, E. Kokoris-Kogias, N. Gailly, L. Gasser, I. Khoffi,
M. J. Fischer, and B. Ford. Scalable Bias-Resistant Distributed Randomness. In 38th IEEE Symposium on Security and Privacy, May 2017.

Execution environment aware contracts

Describe the bug
Execution environment aware contracts

Minimal Reproduction Repo / Steps to Reproduce

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

You can also provide output through the command like such as running printenv

Additional context
Add any other context about the problem here.

Lending: Depositors unfairly harmed by sandwich when debt is distributed

Attackers can profit by sandwiching calls that result in bad debt being distributed
among depositors, such as liquidate and handleBadDebt. As a consequence,
protocols floating assets depositors decrease their assets in a higher than fair
proportion.

By redeeming their deposits before, and depositing again right after spreadBadDebt
takes place, attackers avoid being distributed bad debt, and also profit by obtaining
cheaper market shares. The amount of profit depends on how much debt is being
distributed. Also, if the network transaction fees are low enough the malicious holder
can trigger this sandwich attack to every single liquidate call and take profits in the
event of debt being distributed. The ratio between the shares used by the malicious
holder to perform this attack and the current pool liquidity determines how much do
bystanders lose.

The malicious holder (Alice) simply needs to redeem the shares just before a
liquidate call and deposit again in order to repurchase them at a discounted price. It
can be seen how the value of the shares held by Annie (bystander) changes depending
on the case (usual liquidation and sandwich liquidation).

1.Before Liquidation (NO SANDWICH)
Assets that Alice gets if withdraws = 30000000000000000000000
Alice Shares = 30000000000000000000000
Alice DAI Balance = 20000000000000000000000
Assets that ANNIE (Bystander) gets if withdraws = 100000000000000000000
Floating Assets = 64100000000000000000000
After Liquidation (NO SANDWICH)
Assets that Alice gets if withdraws = 29610480782867678343497
Alice Shares = 30000000000000000000000
Alice DAI Balance = 20000000000000000000000
Assets that ANNIE (Bystander) gets if withdraws = 98701602609558927811
Floating Assets = 63267727272727272727273
2.Before Liquidate (WITH SANDWICH)
Assets that Alice gets if withdraws = 30000000000000000000000
Alice Shares = 30000000000000000000000
Alice DAI Balance = 20000000000000000000000
Assets that ANNIE (Bystander) gets if withdraws = 100000000000000000000
Floating Assets = 64100000000000000000000
After Liquidation (WITH SANDWICH)
Assets that Alice gets if withdraws = 29999999999999999999999
Alice Shares = 30750522619519326674773
Alice DAI Balance = 20000000000000000000000
Assets that ANNIE (Bystander) gets if withdraws = 97559317515329245534
Floating Assets = 63267727272727272727273

Recommendation

Fixed by clearing the bad debt by subtracting from the earningsAccumulator instead
of distributing the bad debt over the users. The clearBadDebt function allows partial
debt clearing. When the earningsAccumulator does not suffice to clear all the debt,
the call will not revert and the bad debt can be cleared when more earnings are
available. This effectively addresses the sandwich attack reported in this issue.

Prices: offchain oracle response liveliness not checked

Offchain oracle response liveliness not checked.

No liveness checks are performed while retrieving oracle data. As a result, prices could
be outdated yet used anyways affecting deposits, borrows, repayments, and any other
source that relies on Chainlink’s prices.

The data retrieval from the rate conversion wrapper does not check the retrieved price
and the success condition. As a result, the PriceFeedWrapper.latestAnswer() could
return negative or invalid data yet used anyways across the market.
The mentioned function has the following implementation:

function latestAnswer() external view returns (int256) {
int256 mainPrice = mainPriceFeed.latestAnswer();
(, bytes memory data) =
address(wrapper).staticcall(abi.encodeWithSelector(conversionSelector, baseUnit));
uint256 rate = abi.decode(data, (uint256));
return int256(rate.mulDivDown(uint256(mainPrice), baseUnit));
}

On the other hand, Auditor.assetPrice() is implemented as follows:

function assetPrice(IPriceFeed priceFeed) public view returns (uint256) {
if (address(priceFeed) == BASE_FEED) return basePrice;
int256 price = priceFeed.latestAnswer();
if (price <= 0) revert InvalidPrice();
return uint256(price) * baseFactor;
}

The low level staticcall function has two returns, a boolean success and bytes
data. Currently, the decoded rate has no rules as the price has in assetPrice(). Also,
there are no checks that ensure that the boolean return is true.

Recommendation

Check both the boolean return and the retrieved rate if possible.

Validator and MEV related issues

Describe the bug
we dont document any of this actually

Minimal Reproduction Repo / Steps to Reproduce

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Environment:

You can also provide output through the command like such as running printenv

Additional context
Add any other context about the problem here.

Poor SSH Configuration Missing From Off-Chain Attacks

Is your feature request related to a problem? Please describe.
Backend servers are often used for things like compounders, apis, oracles, etc.. This requires remote access, usually through SSH. Default SSH configurations are dogshit, often permitting root access with password enable ssh.

Describe the solution you'd like

  • Add SSH as an off-chain attack

Describe alternatives you've considered
Telnet? /s

PID controlled interest rate curve attacks

When do dynamic DeFi rate curves reduce capital efficiency?

From the unpublished paper:
https://gauntlet.network/reports/pid

The two major designs proposed for PID controlled interest rate curves are Euler Finance's reactive rates [2, 3] and Mars Protocol. Currently, only Mars Protocol has implemented $[13,14]$ and deployed a proportional interest rate controller to production. Euler Finance has signalled that they would introduce reactive rates pending further research. However, it appears that neither of these teams has formally analyzed their PID interest protocols.

We note that most PID designs in DeFi are either proportional (P) or proportional integral (PI) controllers. The PI controllers correspond to the utilization of time-weighted average quantities (akin to the Uniswap V3 TWAP oracle [9]). There are two reasons derivatives of rate changes are less useful in practice. First, the rate of change of an interest rate is more easily manipulable given the constraints of blockchains, such as large confirmation times. Moreover, the only reason to adjust a rate based on its gradient is to provide fixed-interest rate protocols. However, most fixed-interest rate protocols such as Yield and Notional, use more transaction cost efficient mechanisms than a PID controller [11]. As such, whenever DeFi enthusiasts talk about PID controlled interest rates, they usually only mean a P or PI controller.

profitability in the worst case for lenders: when there is no supply or demand elasticity. The supply and/or demand elasticity of a protocol refers to the expected rate of change of supply or demand in the protocol as a function of a rate change. We usually have the supply elasticity be positive when rates increase whereas the demand elasticity is negative. However, in many DeFi protocols there are a large swath of users who are completely inelastic to rate changes [5]. This means that the worst case condition of the attack is often true.

We also analyze how this attack is related to capital efficiency in the protocol. We demonstrate that the attack has low profitability if there is excess capital within the pool (e.g. the utilization rate and the target utilization rate are low and the supplied assets dwarf the demand). Similarly, if the protocol can time-lock assets (e.g. force a user who to supply or borrow for a minimum time period), the protocol can make such an attack significantly more expensive However, both of these options are very capital inefficient states for a lending protocol.
Our solution for mitigating this attack involves three components:

  1. Using a PI controller which is more expensive to attack (see Appendix A)
  2. Separating supply and demand curves (akin to what Compound V3 does [7])
  3. Having the controller depend not only on utilization but also supply and demand elasticities

We also note that any off-chain optimization of interest rate curves should take attack profitability into account (which is what Gauntlet has focused on making sure we have battle tested before we roll out interest rate optimization recommendations).

Lack Of Security Guides / Recommendations For Off-Chain Attacks

Problem

The off-chain attacks section is pretty cool, and not something a lot of people consider. However the google sheets does not really mention any resources, guides, etc.. to combat against this. So I've provided some below:

Container Security

Docker has a number of features which can be used to help mitigate, and contain the damage from container escapes. This includes things like apparmor, seccomp, etc.. For example a really good thing to add to all your docker compose files is the following:

    read_only: true
    restart: always
    security_opt:
      - apparmor:docker-default
      - seccomp=/home/foobar/seccomp_default.json
      - no-new-privileges
    tmpfs:
       - /tmp

There more you can do, so i've listed some resources below:

SSH Security

Somewhat a followup to #11, so some simple recommendations:

  • disable root ssh access
  • disable password ssh access
  • enable public key ssh access
  • enable 2fa based ssh

I use the following script to bootstrap 2FA ssh on all new servers, etc..

#!/bin/bash

# references
# https://www.digitalocean.com/community/tutorials/how-to-configure-multi-factor-authentication-on-ubuntu-18-04
# https://www.digitalocean.com/community/tutorials/how-to-set-up-multi-factor-authentication-for-ssh-on-ubuntu-16-04

# we use nullok so that we dont brick ourselves if we havent configured 2fa before running this


sudo apt install libpam-google-authenticator

# enables 2fa for ssh
echo "auth required pam_google_authenticator.so nullok" | sudo tee --append /etc/pam.d/sshd
# enables 2fa for login and sudo requests
echo "auth required pam_google_authenticator.so nullok" | sudo tee --append /etc/pam.d/common-auth
echo "[WARN] if you want to enable 2fa for desktop environments make sure to edit '/etc/pam.d/gdm' or similar"
# this makes ssh aware of ssh
echo "AuthenticationMethods publickey,password publickey,keyboard-interactive" | sudo tee --append /etc/ssh/sshd_config
# enable challenge response
sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/g' /etc/ssh/sshd_config
sudo systemctl restart sshd

echo "please comment out '@include common-auth' in /etc/pam.d/sshd to disable password prompts"
echo "[INFO] please run the google-authenticator command"

Beyond the above here are some resources

Developer Workstation Security

Developer workstation security is super important, if your workstation is compromised the ability to pivot to other attacks will be greatly increased.

Windows

💀

Mac OSX

🤷

Linux

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.