SlideShare a Scribd company logo
© Black Hills Information Security
@BHInfoSecurity
Getting Started
in Blockchain
Security and
Smart Contract
Auditing
© Black Hills Information Security
@BHInfoSecurity
Beau Bullock
@dafthack
• Pentester / Red Team at Black Hills Information Security
• Author / Instructor of Breaching the Cloud Training
• Host / CoinSec Podcast
• Certs: OSCP
, OSWP
, GXPN, GPEN, GWAPT, GCIH, GCIA,
GCFA, GSEC
• Speaker: WWHF, DerbyCon, Black Hat Arsenal, BSides,
Hack Miami, RVASec
• Tool Developer: MailSniper, PowerMeta,
DomainPasswordSpray, MSOLSpray, HostRecon, Check-
LocalAdminHash, MFASweep
• Cyberpunk Synthwave Metal Producer (NOBANDWIDTH)
2
© Black Hills Information Security
@BHInfoSecurity
© Black Hills Information Security
@BHInfoSecurity
Roadmap
• Why is blockchain security important?
• Introduction to smart contracts
• Blockchain hack case studies
• Smart contract exploit demo
• Additional resources to get started
3
© Black Hills Information Security
@BHInfoSecurity
© Black Hills Information Security
@BHInfoSecurity
Why Blockchain Security?
4
© Black Hills Information Security
@BHInfoSecurity
Top DeFi Hacks Since September 2020
• Poly Network - $611,000,000 | 10 Aug 2021
• EasyFi - $59,000,000 | 19 Apr 2021
• Uranium Finance - $57,200,000 | 28 Apr 2021
• PancakeBunny - $45,000,000 | 19 May 2021
• Kucoin - $45,000,000 | 29 Sep 2020
• Alpha Finance - $37,500,000 | 13 Feb 2021
• Meerkat Finance - BSC - $32,000,000 | 04 Mar 2021
• Spartan Protocol - $30,500,000 | 02 May 2021
• StableMagnet - $27,000,000 | 23 Jun 2021
• Paid Network - $27,000,000 | 05 Mar 2021
• Harvest Finance - $25,000,000 | 26 Oct 2020
• XToken - $24,000,000 | 12 May 2021
• Popsicle Finance - $20,000,000 | 03 Aug 2021
• Pickle Finance - $19,700,000 | 22 Nov 2020
• bEarn - $18,000,000 | 17 May 2021
• Furucombo - $14,000,000 | 27 Feb 2021
• Compounder Finance - $12,000,000 | 02 Dec 2020
• Value DeFi 3 - $11,000,000 | 7 May 2021
• Yearn - $11,000,000 | 05 Feb 2021
• Rari Capital - $10,000,000 | 8 May 2021
• Value DeFi 2 - $10,000,000 | 5 May 2021
• Cover - $9,400,000 | 29 Dec 2020
• Punk Protocol - $8,950,000 | 10 Aug 2021
• THORChain 2 - $8,000,000 | 22 Jul 2021
• Hack Epidemic (Origin Protocol ) - $8,000,000 | 17
Nov 2020
• Anyswap - $7,900,000 | 10 Jul 2021
• Warp Finance - $7,800,000 | 18 Dec 2020
• BurgerSwap - Arcadia Group - $7,200,000 | 28 May
2021
• Value DeFi - $7,000,000 | 14 Nov 2020
• Alchemix - $6,500,000 | 16 Jun 2021
• Belt - $6,300,000 | 29 May 2021
• Bondly - $5,900,000 | 15 Jul 2021
• Roll - $5,700,000 | 14 Mar 2021
• THORChain - $5,000,000 | 15 Jul 2021
• Eleven Finance - $4,500,000 | 22 Jun 2021
• ChainSwap - $4,400,000 | 11 Jul 2021
• PancakeBunny 2 - $2,400,000 | 16 May 2021
• DODO - $2,000,000 | 09 Mar 2021
• Akropolis - $2,000,000 | 12 Nov 2020
• Levyathan - $1,500,000 | 30 Jul 2021
• The Big Combo (Growth DeFi ) - $1,300,000 | 09 Feb
2021
• Autoshark - $745,000 | 24 May 2021
• Merlin Labs - $680,000 | 26 May 2021
• Merlin Labs 2 - $550,000 | 26 May 2021
• Merlin Labs - $330,000 | 29 Jun 2021
• Saddle Finance - $275,735 | 20 Jan 2021
• SafeDollar - $248,000 | 28 Jun 2021
5
Source: https://www.rekt.news
More Than $1.2 Billion Stolen
© Black Hills Information Security
@BHInfoSecurity
Growing
Use Cases
for
Blockchain
• Currency
• Decentralized Finance (lending, token
swaps, crowdfunding)
• Digital Identity
• Arts and collectibles (NFTs)
• Supply chain (sourcing transparency,
medical supply tracking)
• Media (anti-piracy)
• Real Estate
• Gaming (play-to-earn, metaverse
property ownership)
• …and more
© Black Hills Information Security
@BHInfoSecurity
A New
Frontier
• Birth of a new industry
• Many projects racing to be “first to
market”
• Established, well-known companies
(Microsoft, IBM, Wal-Mart, Disney,
etc.) are implementing different use
cases
• More than just smart contract
security…
© Black Hills Information Security
@BHInfoSecurity
Blockchain Elements That Need Securing
• Layer 1
• The underlying blockchain protocol itself
(Bitcoin Core, Geth)
• Layer 2
• An overlaying network on top of layer 1
typically focused on scalability (Bitcoin
Lightning network)
• Smart Contracts
• Automatically executing programs
deployed to the blockchain (tokens,
dApps, NFTs, etc.)
• Software Wallets
• Custodial vs. non-custodial
• Hardware Wallets
• Physical devices for storing private keys that are
then used to send and receive funds
• Mining Software
• Programs used to run specialized hardware
used to perform mining
• Centralized Exchanges
• Typically require KYC (Coinbase, Binance, etc.)
• Decentralized Exchanges
• “DeFi” exchanges typically built via Smart
Contract w/ web3 front-end
• People
• Social engineering, rug pulls, asset protection
8
© Black Hills Information Security
@BHInfoSecurity
Introduction to Smart
Contracts
9
© Black Hills Information Security
@BHInfoSecurity
“Smart contract code is unforgiving. Every bug can lead to
monetary loss. You should not treat smart contract
programming the same way as general-purpose programming.
Writing DApps in Solidity is not like creating a web widget in
JavaScript. Rather, you should apply rigorous engineering and
software development methodologies, as you would in
aerospace engineering or any similarly unforgiving discipline.
Once you “launch” your code, there’s little you can do to fix any
problems.”
- Andreas M. Antonopoulos & Dr. Gavin Wood
10
© Black Hills Information Security
@BHInfoSecurity
What are Smart
Contracts?
• Immutable computer programs
• Decentralized execution
• Run on virtual machines via node software
• Typically written in high-level languages
• Get compiled into bytecode prior to
deployment to the blockchain
• Only run if they are called by a transaction
© Black Hills Information Security
@BHInfoSecurity
Ethereum Virtual Machine (EVM)
• Virtual machine on the blockchain
• Uses opcodes to execute tasks
• Each opcode has a base gas cost
• All contracts are executed on all nodes
• Rules for changing the machine state
are defined by the EVM
• Storage can be permanent or volatile
(stack & memory)
• Accounts can be externally owned
(EOA) or contract accounts
12
Source: https://ethereum.org/en/developers/docs/evm/
© Black Hills Information Security
@BHInfoSecurity
Solidity
• High-level language for writing smart
contracts
• By far the most dominant language currently
• Syntax similar to JavaScript or C++
• Remix IDE for dev:
https://remix.ethereum.org
• Code tends to be posted publicly & “verified”
on sites like Etherscan
13
© Black Hills Information Security
@BHInfoSecurity
Solidity Example
14
Source: https://github.com/ethereumbook/ethereumbook/blob/develop/code/Solidity/Faucet.sol
© Black Hills Information Security
@BHInfoSecurity
Ethereum & Solidity Are Not Alone
Bitcoin + Stacks, RSK
Solana + Rust C, C++
Cardano + Plutus
Avalanche + Solidity
Terra + Rust
Chia + Chialisp
Hyperledger Fabric + Go, JavaScript
Nem + Java
15
© Black Hills Information Security
@BHInfoSecurity
Smart
Contract
Vulns
• Typically result in a significant loss of funds
• Since contract code is public, anyone can
analyze it for issues
• Exploits can be tested against private, local
blockchain instances or on a testnet
• No patching since contracts are immutable
• Stolen funds can be very difficult to track
© Black Hills Information Security
@BHInfoSecurity
Smart Contract Vulns:
Reentrancy
• Vulnerability where a function can be re-
entered into prior to completion
• Vuln contract has a function that allows for
withdrawing Ether prior to the balance
update
• Attacker initiates a call to the vulnerable
function from a malicious contract
• Target contract sends Ether to Attacker
contract triggering fallback function
• A fallback function re-enters into the
withdraw function causing a loop until all
funds are drained
17
Source: https://quantstamp.com/blog/what-is-a-re-entrancy-attack
Real World Example: The DAO Hack ($150 Million Stolen)
https://hackingdistributed.com/2016/06/18/analysis-of-the-dao-
exploit/
© Black Hills Information Security
@BHInfoSecurity
Smart Contract Vulns:
Front-Running
• Prior to a block being mined all
transactions are visible in the
mempool
• Observers can see these
transactions and react
• Miners give priority to higher gas
prices so an attacker can have their
transaction mined before the
original sender by paying more
18
Source: https://blog.enigma.co/preventing-dex-front-running-with-enigma-df3f0b5b9e78
Real World Example: Bancor
https://hackernoon.com/front-running-bancor-in-150-lines-of-
python-with-ethereum-api-d5e2bfd0d798
© Black Hills Information Security
@BHInfoSecurity
Smart Contract Vulns:
Integer Overflow and Underflow
• Overflows and underflows can occur by performing
arithmetic operations that exceed maximum or minimum
integer values
• Unsigned Integers (uint)
• Range is: 0 to (2256 - 1)
• Signed Integers (int)
• Range is: -2255 to (2256 - 1)
• Example uint overflow: 1 + (2256 - 1) = 0
• Can be exploited to bypass certain security checks
19
Real World Example: BEC Token
https://techcrunch.com/2018/04/25/overflow-error-shuts-down-
token-trading/
© Black Hills Information Security
@BHInfoSecurity
Smart Contract Vulns:
Denial-of-Service
• Block Gas Limit
• The Ethereum network specifies a block gas limit
• When contracts are called each action performed
requires a certain amount of gas
• If the block limit is exceeded the transaction will revert
• Can lead to issues that are even non-malicious
• Unexpected Revert
• Contract attempts to send funds but malicious contract
reverts any payments
20
Real World Example: GovernMental
https://hackernoon.com/smart-contract-attacks-part-2-ponzi-
games-gone-wrong-d5a8b1a98dd8
© Black Hills Information Security
@BHInfoSecurity
Smart Contract Vulns:
Access Control
• Governs who can transfer assets, mint tokens, vote
on proposals, freeze transfers, etc.
• Ownership over a contract allows administrative
tasks
• By default the owner is the account that deployed it
• Ownership can potentially be transferred via exploit,
lack of privileged action checks, or even abused by
owners themselves
• Can also delay actions using a timelock
21
Real World Example: Parity Wallet
https://blog.openzeppelin.com/on-the-parity-wallet-multisig-
hack-405a8c12e8f7/
Source: https://ethernaut.openzeppelin.com/
© Black Hills Information Security
@BHInfoSecurity
Smart Contract Vulns:
Timestamp Dependence
• Occurs from a misunderstanding of time keeping in a
smart contract
• block.timestamp and block.number can be
used to trigger time-dependent events
• The block timestamp can be modified by miners to a
degree
• Block time is typically 14 seconds but it’s not constant
• Modification of a few seconds may result in
exploitation
22
© Black Hills Information Security
@BHInfoSecurity
More Smart Contract Vulns
• New issues are still being found all the time
• Functions that appear secure on their own may
yield critical issues when combined with others
• Smart Contract Weakness Classification Registry
• https://swcregistry.io/
• Consensys - Smart Contracts Known Attacks
• https://consensys.github.io/smart-contract-best-
practices/known_attacks/
23
© Black Hills Information Security
@BHInfoSecurity
Case Studies
24
© Black Hills Information Security
@BHInfoSecurity
Uranium
Finance
Hack
• April 28, 2021
• $57 million stolen
• Uniswap clone on Binance Smart
Chain
25
© Black Hills Information Security
@BHInfoSecurity
Case Study – Uranium Finance Hack
• Uranium Finance copied code from
Uniswap and modified portions of it
• Portions of the swap function were
changed to a larger value, but the
balance check was unaltered
• Attacker deposited minimum funds
to each of the token pair contracts
• Exploiting the misplaced zero, the
attacker was able to drain each
liquidity pool
26
Source: https://www.rekt.news/uranium-rekt/
© Black Hills Information Security
@BHInfoSecurity
Poly
Network
Hack
• August 10, 2021
• $610 million stolen
• Enables cross-chain transactions
• Ethereum
• Binance Smart Chain
• Polygon
27
© Black Hills Information Security
@BHInfoSecurity
Case Study – Poly Network Hack
• keepers are trusted entities for cross-chain
transactions
• User sends a transaction on one blockchain and it
gets repeated on a destination
• The keepers sign the block on the source blockchain
• User submits the signed block to
EthCrossChainManager on the destination
• If sig is valid, the contract executes the transaction on
the destination blockchain as the
EthCrossChainManager contract, not the user
28
© Black Hills Information Security
@BHInfoSecurity
Case Study – Poly Network Hack
• EthCrossChainManager has the
permission to change keepers via the
EthCrossChainData contract
• Attacker exploited this to make
themselves a keeper
• Attacker could now sign fake blocks
with arbitrary transactions resulting
in $610 million stolen
29
Example transactions of hacked funds being sent to attacker wallet
© Black Hills Information Security
@BHInfoSecurity
Case Study – Poly Network Hack
• But they returned it… all of it
• Why? Bad OPSEC? Are they trying to appear to be a whitehat?
30
Attacker funded their account directly from an exchange (hoo.com)
© Black Hills Information Security
@BHInfoSecurity
Cream
Finance
Hack
• August 30, 2021
• $18.8 million stolen
• Decentralized Lending Protocol
(flash loans)
31
© Black Hills Information Security
@BHInfoSecurity
Case Study – Cream Finance Hack
• Cream protocol implements the ERC777
AMP token contract
• ERC777 has “hooks” that call the sender
and receiver contracts
• The _callPreTransferHooks function
of the AMP token contract enabled
Reentrancy on the Cream contract
• Allowed the attacker to nest a second
borrow() function in the token
transfer() function before the initial
was updated
32
Source: https://www.zengo.com/imbtc-defi-hack-explained/
© Black Hills Information Security
@BHInfoSecurity
Case Study – Cream Finance Hack
• Attacker flash loan borrows 500 ETH,
uses it as collateral to borrow 19 million
AMP
• Exploits reentrancy to borrow 355 more
ETH before initial borrow() is updated
• Creates new contract to liquidate part
of the borrowed AMP
, uses it to repay
flash loan
• 41 ETH and 9.74 Million AMP leftover
sent to attacker
• Rinse & Repeat X 17 times
33
Source: https://twitter.com/peckshield/status/1432250680799027204/photo/1
© Black Hills Information Security
@BHInfoSecurity
Live Exploit Demo
34
© Black Hills Information Security
@BHInfoSecurity
The Setup
• Ganache – Personal Ethereum blockchain hosted on VM
• https://www.trufflesuite.com/ganache
• Truffle – Development framework for Ethereum
• https://www.trufflesuite.com/truffle
• Remix IDE – Web-based IDE for writing and deploying
smart contracts
• https://remix.ethereum.org
• Metamask – Crypto wallet
• https://metamask.io/
• Damn Vulnerable DeFi
• https://www.damnvulnerabledefi.xyz/
35
Blockchain Hacking QuickStart Guide:
https://start.blockchainhax.com
© Black Hills Information Security
@BHInfoSecurity
Exploit
Steps Recap
• Identify vulnerability in smart contract
• Deploy malicious contract that calls
function in the target contract
• Call the exploit function in the malicious
contract specifying the target function
• Exploit sets attacker contract as approved
sender of ERC20 token
• Attacker contract initiates transfer of all
tokens from pool to attacker wallet
© Black Hills Information Security
@BHInfoSecurity
Security Tools
37
© Black Hills Information Security
@BHInfoSecurity
VS Code +
Solidity
Visual
Developer
https://github.com/ConsenSys/vscode-solidity-auditor
• Reading through the code thoroughly is a
must
• Security centric syntax and semantic
highlighting
• Find external calls, developer notes in
comments, storage modifiers, access
modifiers,
• Uses Sūrya for generating call graphs
• Hover over keywords to show basic security
notes
© Black Hills Information Security
@BHInfoSecurity
VS Code + Solidity Visual Developer
39
© Black Hills Information Security
@BHInfoSecurity
Slither
https://github.com/crytic/slither
• Solidity source code analyzer
• Detects many common issues such as
reentrancy, functions that allow users to
self destruct the contract, uninitialized
variables, and more
• Low false positives
• Can create graphic representation of
function calls
© Black Hills Information Security
@BHInfoSecurity
Slither
41
© Black Hills Information Security
@BHInfoSecurity
Mythril &
MythX
https://github.com/ConsenSys/mythril
https://mythx.io/
• Mythril
• Symbolic execution vulnerability scanner
• Can scan bytecode directly
• Free and open source
• MythX
• Static analysis, symbolic analysis & fuzzing
• Has an API you can submit scan jobs to
• Integrates into dev frameworks
• Not free
© Black Hills Information Security
@BHInfoSecurity
Mythril
43
© Black Hills Information Security
@BHInfoSecurity
Resources to Get Started
44
© Black Hills Information Security
@BHInfoSecurity
Resources to
Get Started
• Books
• Mastering Ethereum -
https://github.com/ethereumbook/ethereumbook
• Hands-On Smart Contract Development
• Learn Solidity
• https://cryptozombies.io/ - Free dApp building
game
• https://solidity-by-example.org
• CTF
• Ethernaut
• https://ethernaut.openzeppelin.com/
• Damn Vulnerable DeFi
• https://www.damnvulnerabledefi.xyz/
© Black Hills Information Security
@BHInfoSecurity
Bug Bounties
• Immunefi
• https://immunefi.com/
• Consensys Bug Bounty List
• https://consensys.github.io/smart-contract-best-
practices/bug_bounty_list/
• Code 423n4
• https://code423n4.com/
• Hacken
• https://hackenproof.com/programs
• Chainlink
• https://hackerone.com/chainlink?type=team
• The Graph
• https://thegraph.com/security/
46
© Black Hills Information Security
@BHInfoSecurity
Key Takeaways
1. Use cases for blockchain are growing significantly
2. Hacks typically result in a significant loss of funds
3. As this is an emerging technology, new smart
contract vulnerabilities are still being discovered
4. Security analyzers are good, but understanding the
code is a must
5. Smart contracts are only one piece of the growing
blockchain ecosystem
47
© Black Hills Information Security
@BHInfoSecurity
The End
• Follow me on Twitter
• Beau Bullock - @dafthack
• BlockchainHAX QuickStart Guide
• https://start.blockchainhax.com
• CoinSec Podcast – Weekly show about blockchain
security
• coinsecpodcast.com
• @coinsecpodcast
• Black Hills Information Security
• https://www.blackhillsinfosec.com
• @BHInfoSecurity
48

More Related Content

Getting Started in Blockchain Security and Smart Contract Auditing

  • 1. © Black Hills Information Security @BHInfoSecurity Getting Started in Blockchain Security and Smart Contract Auditing
  • 2. © Black Hills Information Security @BHInfoSecurity Beau Bullock @dafthack • Pentester / Red Team at Black Hills Information Security • Author / Instructor of Breaching the Cloud Training • Host / CoinSec Podcast • Certs: OSCP , OSWP , GXPN, GPEN, GWAPT, GCIH, GCIA, GCFA, GSEC • Speaker: WWHF, DerbyCon, Black Hat Arsenal, BSides, Hack Miami, RVASec • Tool Developer: MailSniper, PowerMeta, DomainPasswordSpray, MSOLSpray, HostRecon, Check- LocalAdminHash, MFASweep • Cyberpunk Synthwave Metal Producer (NOBANDWIDTH) 2 © Black Hills Information Security @BHInfoSecurity
  • 3. © Black Hills Information Security @BHInfoSecurity Roadmap • Why is blockchain security important? • Introduction to smart contracts • Blockchain hack case studies • Smart contract exploit demo • Additional resources to get started 3 © Black Hills Information Security @BHInfoSecurity
  • 4. © Black Hills Information Security @BHInfoSecurity Why Blockchain Security? 4
  • 5. © Black Hills Information Security @BHInfoSecurity Top DeFi Hacks Since September 2020 • Poly Network - $611,000,000 | 10 Aug 2021 • EasyFi - $59,000,000 | 19 Apr 2021 • Uranium Finance - $57,200,000 | 28 Apr 2021 • PancakeBunny - $45,000,000 | 19 May 2021 • Kucoin - $45,000,000 | 29 Sep 2020 • Alpha Finance - $37,500,000 | 13 Feb 2021 • Meerkat Finance - BSC - $32,000,000 | 04 Mar 2021 • Spartan Protocol - $30,500,000 | 02 May 2021 • StableMagnet - $27,000,000 | 23 Jun 2021 • Paid Network - $27,000,000 | 05 Mar 2021 • Harvest Finance - $25,000,000 | 26 Oct 2020 • XToken - $24,000,000 | 12 May 2021 • Popsicle Finance - $20,000,000 | 03 Aug 2021 • Pickle Finance - $19,700,000 | 22 Nov 2020 • bEarn - $18,000,000 | 17 May 2021 • Furucombo - $14,000,000 | 27 Feb 2021 • Compounder Finance - $12,000,000 | 02 Dec 2020 • Value DeFi 3 - $11,000,000 | 7 May 2021 • Yearn - $11,000,000 | 05 Feb 2021 • Rari Capital - $10,000,000 | 8 May 2021 • Value DeFi 2 - $10,000,000 | 5 May 2021 • Cover - $9,400,000 | 29 Dec 2020 • Punk Protocol - $8,950,000 | 10 Aug 2021 • THORChain 2 - $8,000,000 | 22 Jul 2021 • Hack Epidemic (Origin Protocol ) - $8,000,000 | 17 Nov 2020 • Anyswap - $7,900,000 | 10 Jul 2021 • Warp Finance - $7,800,000 | 18 Dec 2020 • BurgerSwap - Arcadia Group - $7,200,000 | 28 May 2021 • Value DeFi - $7,000,000 | 14 Nov 2020 • Alchemix - $6,500,000 | 16 Jun 2021 • Belt - $6,300,000 | 29 May 2021 • Bondly - $5,900,000 | 15 Jul 2021 • Roll - $5,700,000 | 14 Mar 2021 • THORChain - $5,000,000 | 15 Jul 2021 • Eleven Finance - $4,500,000 | 22 Jun 2021 • ChainSwap - $4,400,000 | 11 Jul 2021 • PancakeBunny 2 - $2,400,000 | 16 May 2021 • DODO - $2,000,000 | 09 Mar 2021 • Akropolis - $2,000,000 | 12 Nov 2020 • Levyathan - $1,500,000 | 30 Jul 2021 • The Big Combo (Growth DeFi ) - $1,300,000 | 09 Feb 2021 • Autoshark - $745,000 | 24 May 2021 • Merlin Labs - $680,000 | 26 May 2021 • Merlin Labs 2 - $550,000 | 26 May 2021 • Merlin Labs - $330,000 | 29 Jun 2021 • Saddle Finance - $275,735 | 20 Jan 2021 • SafeDollar - $248,000 | 28 Jun 2021 5 Source: https://www.rekt.news More Than $1.2 Billion Stolen
  • 6. © Black Hills Information Security @BHInfoSecurity Growing Use Cases for Blockchain • Currency • Decentralized Finance (lending, token swaps, crowdfunding) • Digital Identity • Arts and collectibles (NFTs) • Supply chain (sourcing transparency, medical supply tracking) • Media (anti-piracy) • Real Estate • Gaming (play-to-earn, metaverse property ownership) • …and more
  • 7. © Black Hills Information Security @BHInfoSecurity A New Frontier • Birth of a new industry • Many projects racing to be “first to market” • Established, well-known companies (Microsoft, IBM, Wal-Mart, Disney, etc.) are implementing different use cases • More than just smart contract security…
  • 8. © Black Hills Information Security @BHInfoSecurity Blockchain Elements That Need Securing • Layer 1 • The underlying blockchain protocol itself (Bitcoin Core, Geth) • Layer 2 • An overlaying network on top of layer 1 typically focused on scalability (Bitcoin Lightning network) • Smart Contracts • Automatically executing programs deployed to the blockchain (tokens, dApps, NFTs, etc.) • Software Wallets • Custodial vs. non-custodial • Hardware Wallets • Physical devices for storing private keys that are then used to send and receive funds • Mining Software • Programs used to run specialized hardware used to perform mining • Centralized Exchanges • Typically require KYC (Coinbase, Binance, etc.) • Decentralized Exchanges • “DeFi” exchanges typically built via Smart Contract w/ web3 front-end • People • Social engineering, rug pulls, asset protection 8
  • 9. © Black Hills Information Security @BHInfoSecurity Introduction to Smart Contracts 9
  • 10. © Black Hills Information Security @BHInfoSecurity “Smart contract code is unforgiving. Every bug can lead to monetary loss. You should not treat smart contract programming the same way as general-purpose programming. Writing DApps in Solidity is not like creating a web widget in JavaScript. Rather, you should apply rigorous engineering and software development methodologies, as you would in aerospace engineering or any similarly unforgiving discipline. Once you “launch” your code, there’s little you can do to fix any problems.” - Andreas M. Antonopoulos & Dr. Gavin Wood 10
  • 11. © Black Hills Information Security @BHInfoSecurity What are Smart Contracts? • Immutable computer programs • Decentralized execution • Run on virtual machines via node software • Typically written in high-level languages • Get compiled into bytecode prior to deployment to the blockchain • Only run if they are called by a transaction
  • 12. © Black Hills Information Security @BHInfoSecurity Ethereum Virtual Machine (EVM) • Virtual machine on the blockchain • Uses opcodes to execute tasks • Each opcode has a base gas cost • All contracts are executed on all nodes • Rules for changing the machine state are defined by the EVM • Storage can be permanent or volatile (stack & memory) • Accounts can be externally owned (EOA) or contract accounts 12 Source: https://ethereum.org/en/developers/docs/evm/
  • 13. © Black Hills Information Security @BHInfoSecurity Solidity • High-level language for writing smart contracts • By far the most dominant language currently • Syntax similar to JavaScript or C++ • Remix IDE for dev: https://remix.ethereum.org • Code tends to be posted publicly & “verified” on sites like Etherscan 13
  • 14. © Black Hills Information Security @BHInfoSecurity Solidity Example 14 Source: https://github.com/ethereumbook/ethereumbook/blob/develop/code/Solidity/Faucet.sol
  • 15. © Black Hills Information Security @BHInfoSecurity Ethereum & Solidity Are Not Alone Bitcoin + Stacks, RSK Solana + Rust C, C++ Cardano + Plutus Avalanche + Solidity Terra + Rust Chia + Chialisp Hyperledger Fabric + Go, JavaScript Nem + Java 15
  • 16. © Black Hills Information Security @BHInfoSecurity Smart Contract Vulns • Typically result in a significant loss of funds • Since contract code is public, anyone can analyze it for issues • Exploits can be tested against private, local blockchain instances or on a testnet • No patching since contracts are immutable • Stolen funds can be very difficult to track
  • 17. © Black Hills Information Security @BHInfoSecurity Smart Contract Vulns: Reentrancy • Vulnerability where a function can be re- entered into prior to completion • Vuln contract has a function that allows for withdrawing Ether prior to the balance update • Attacker initiates a call to the vulnerable function from a malicious contract • Target contract sends Ether to Attacker contract triggering fallback function • A fallback function re-enters into the withdraw function causing a loop until all funds are drained 17 Source: https://quantstamp.com/blog/what-is-a-re-entrancy-attack Real World Example: The DAO Hack ($150 Million Stolen) https://hackingdistributed.com/2016/06/18/analysis-of-the-dao- exploit/
  • 18. © Black Hills Information Security @BHInfoSecurity Smart Contract Vulns: Front-Running • Prior to a block being mined all transactions are visible in the mempool • Observers can see these transactions and react • Miners give priority to higher gas prices so an attacker can have their transaction mined before the original sender by paying more 18 Source: https://blog.enigma.co/preventing-dex-front-running-with-enigma-df3f0b5b9e78 Real World Example: Bancor https://hackernoon.com/front-running-bancor-in-150-lines-of- python-with-ethereum-api-d5e2bfd0d798
  • 19. © Black Hills Information Security @BHInfoSecurity Smart Contract Vulns: Integer Overflow and Underflow • Overflows and underflows can occur by performing arithmetic operations that exceed maximum or minimum integer values • Unsigned Integers (uint) • Range is: 0 to (2256 - 1) • Signed Integers (int) • Range is: -2255 to (2256 - 1) • Example uint overflow: 1 + (2256 - 1) = 0 • Can be exploited to bypass certain security checks 19 Real World Example: BEC Token https://techcrunch.com/2018/04/25/overflow-error-shuts-down- token-trading/
  • 20. © Black Hills Information Security @BHInfoSecurity Smart Contract Vulns: Denial-of-Service • Block Gas Limit • The Ethereum network specifies a block gas limit • When contracts are called each action performed requires a certain amount of gas • If the block limit is exceeded the transaction will revert • Can lead to issues that are even non-malicious • Unexpected Revert • Contract attempts to send funds but malicious contract reverts any payments 20 Real World Example: GovernMental https://hackernoon.com/smart-contract-attacks-part-2-ponzi- games-gone-wrong-d5a8b1a98dd8
  • 21. © Black Hills Information Security @BHInfoSecurity Smart Contract Vulns: Access Control • Governs who can transfer assets, mint tokens, vote on proposals, freeze transfers, etc. • Ownership over a contract allows administrative tasks • By default the owner is the account that deployed it • Ownership can potentially be transferred via exploit, lack of privileged action checks, or even abused by owners themselves • Can also delay actions using a timelock 21 Real World Example: Parity Wallet https://blog.openzeppelin.com/on-the-parity-wallet-multisig- hack-405a8c12e8f7/ Source: https://ethernaut.openzeppelin.com/
  • 22. © Black Hills Information Security @BHInfoSecurity Smart Contract Vulns: Timestamp Dependence • Occurs from a misunderstanding of time keeping in a smart contract • block.timestamp and block.number can be used to trigger time-dependent events • The block timestamp can be modified by miners to a degree • Block time is typically 14 seconds but it’s not constant • Modification of a few seconds may result in exploitation 22
  • 23. © Black Hills Information Security @BHInfoSecurity More Smart Contract Vulns • New issues are still being found all the time • Functions that appear secure on their own may yield critical issues when combined with others • Smart Contract Weakness Classification Registry • https://swcregistry.io/ • Consensys - Smart Contracts Known Attacks • https://consensys.github.io/smart-contract-best- practices/known_attacks/ 23
  • 24. © Black Hills Information Security @BHInfoSecurity Case Studies 24
  • 25. © Black Hills Information Security @BHInfoSecurity Uranium Finance Hack • April 28, 2021 • $57 million stolen • Uniswap clone on Binance Smart Chain 25
  • 26. © Black Hills Information Security @BHInfoSecurity Case Study – Uranium Finance Hack • Uranium Finance copied code from Uniswap and modified portions of it • Portions of the swap function were changed to a larger value, but the balance check was unaltered • Attacker deposited minimum funds to each of the token pair contracts • Exploiting the misplaced zero, the attacker was able to drain each liquidity pool 26 Source: https://www.rekt.news/uranium-rekt/
  • 27. © Black Hills Information Security @BHInfoSecurity Poly Network Hack • August 10, 2021 • $610 million stolen • Enables cross-chain transactions • Ethereum • Binance Smart Chain • Polygon 27
  • 28. © Black Hills Information Security @BHInfoSecurity Case Study – Poly Network Hack • keepers are trusted entities for cross-chain transactions • User sends a transaction on one blockchain and it gets repeated on a destination • The keepers sign the block on the source blockchain • User submits the signed block to EthCrossChainManager on the destination • If sig is valid, the contract executes the transaction on the destination blockchain as the EthCrossChainManager contract, not the user 28
  • 29. © Black Hills Information Security @BHInfoSecurity Case Study – Poly Network Hack • EthCrossChainManager has the permission to change keepers via the EthCrossChainData contract • Attacker exploited this to make themselves a keeper • Attacker could now sign fake blocks with arbitrary transactions resulting in $610 million stolen 29 Example transactions of hacked funds being sent to attacker wallet
  • 30. © Black Hills Information Security @BHInfoSecurity Case Study – Poly Network Hack • But they returned it… all of it • Why? Bad OPSEC? Are they trying to appear to be a whitehat? 30 Attacker funded their account directly from an exchange (hoo.com)
  • 31. © Black Hills Information Security @BHInfoSecurity Cream Finance Hack • August 30, 2021 • $18.8 million stolen • Decentralized Lending Protocol (flash loans) 31
  • 32. © Black Hills Information Security @BHInfoSecurity Case Study – Cream Finance Hack • Cream protocol implements the ERC777 AMP token contract • ERC777 has “hooks” that call the sender and receiver contracts • The _callPreTransferHooks function of the AMP token contract enabled Reentrancy on the Cream contract • Allowed the attacker to nest a second borrow() function in the token transfer() function before the initial was updated 32 Source: https://www.zengo.com/imbtc-defi-hack-explained/
  • 33. © Black Hills Information Security @BHInfoSecurity Case Study – Cream Finance Hack • Attacker flash loan borrows 500 ETH, uses it as collateral to borrow 19 million AMP • Exploits reentrancy to borrow 355 more ETH before initial borrow() is updated • Creates new contract to liquidate part of the borrowed AMP , uses it to repay flash loan • 41 ETH and 9.74 Million AMP leftover sent to attacker • Rinse & Repeat X 17 times 33 Source: https://twitter.com/peckshield/status/1432250680799027204/photo/1
  • 34. © Black Hills Information Security @BHInfoSecurity Live Exploit Demo 34
  • 35. © Black Hills Information Security @BHInfoSecurity The Setup • Ganache – Personal Ethereum blockchain hosted on VM • https://www.trufflesuite.com/ganache • Truffle – Development framework for Ethereum • https://www.trufflesuite.com/truffle • Remix IDE – Web-based IDE for writing and deploying smart contracts • https://remix.ethereum.org • Metamask – Crypto wallet • https://metamask.io/ • Damn Vulnerable DeFi • https://www.damnvulnerabledefi.xyz/ 35 Blockchain Hacking QuickStart Guide: https://start.blockchainhax.com
  • 36. © Black Hills Information Security @BHInfoSecurity Exploit Steps Recap • Identify vulnerability in smart contract • Deploy malicious contract that calls function in the target contract • Call the exploit function in the malicious contract specifying the target function • Exploit sets attacker contract as approved sender of ERC20 token • Attacker contract initiates transfer of all tokens from pool to attacker wallet
  • 37. © Black Hills Information Security @BHInfoSecurity Security Tools 37
  • 38. © Black Hills Information Security @BHInfoSecurity VS Code + Solidity Visual Developer https://github.com/ConsenSys/vscode-solidity-auditor • Reading through the code thoroughly is a must • Security centric syntax and semantic highlighting • Find external calls, developer notes in comments, storage modifiers, access modifiers, • Uses Sūrya for generating call graphs • Hover over keywords to show basic security notes
  • 39. © Black Hills Information Security @BHInfoSecurity VS Code + Solidity Visual Developer 39
  • 40. © Black Hills Information Security @BHInfoSecurity Slither https://github.com/crytic/slither • Solidity source code analyzer • Detects many common issues such as reentrancy, functions that allow users to self destruct the contract, uninitialized variables, and more • Low false positives • Can create graphic representation of function calls
  • 41. © Black Hills Information Security @BHInfoSecurity Slither 41
  • 42. © Black Hills Information Security @BHInfoSecurity Mythril & MythX https://github.com/ConsenSys/mythril https://mythx.io/ • Mythril • Symbolic execution vulnerability scanner • Can scan bytecode directly • Free and open source • MythX • Static analysis, symbolic analysis & fuzzing • Has an API you can submit scan jobs to • Integrates into dev frameworks • Not free
  • 43. © Black Hills Information Security @BHInfoSecurity Mythril 43
  • 44. © Black Hills Information Security @BHInfoSecurity Resources to Get Started 44
  • 45. © Black Hills Information Security @BHInfoSecurity Resources to Get Started • Books • Mastering Ethereum - https://github.com/ethereumbook/ethereumbook • Hands-On Smart Contract Development • Learn Solidity • https://cryptozombies.io/ - Free dApp building game • https://solidity-by-example.org • CTF • Ethernaut • https://ethernaut.openzeppelin.com/ • Damn Vulnerable DeFi • https://www.damnvulnerabledefi.xyz/
  • 46. © Black Hills Information Security @BHInfoSecurity Bug Bounties • Immunefi • https://immunefi.com/ • Consensys Bug Bounty List • https://consensys.github.io/smart-contract-best- practices/bug_bounty_list/ • Code 423n4 • https://code423n4.com/ • Hacken • https://hackenproof.com/programs • Chainlink • https://hackerone.com/chainlink?type=team • The Graph • https://thegraph.com/security/ 46
  • 47. © Black Hills Information Security @BHInfoSecurity Key Takeaways 1. Use cases for blockchain are growing significantly 2. Hacks typically result in a significant loss of funds 3. As this is an emerging technology, new smart contract vulnerabilities are still being discovered 4. Security analyzers are good, but understanding the code is a must 5. Smart contracts are only one piece of the growing blockchain ecosystem 47
  • 48. © Black Hills Information Security @BHInfoSecurity The End • Follow me on Twitter • Beau Bullock - @dafthack • BlockchainHAX QuickStart Guide • https://start.blockchainhax.com • CoinSec Podcast – Weekly show about blockchain security • coinsecpodcast.com • @coinsecpodcast • Black Hills Information Security • https://www.blackhillsinfosec.com • @BHInfoSecurity 48