0% found this document useful (0 votes)
4 views60 pages

Week9 SmartContract Secuirty Update-1

Uploaded by

mzmindykkyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views60 pages

Week9 SmartContract Secuirty Update-1

Uploaded by

mzmindykkyan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

Smart Contracts, Security Issues

and Verification Process

Pritom Rajkhowa
How to write a unit test case for a
smart contract
Contract Decoding
Useful URLs

https://abi.hashex.org/
How to verify a smart contract on
Etherscan
What is Truffle Suite
The Truffle Suite is a comprehensive development framework and
toolset for building decentralized applications (dapps) on the Ethereum
blockchain. It offers a range of powerful tools that streamline the entire
development process, from smart contract creation and testing to
deployment and asset management.
Truffle

Truffle is the core component of the Truffle Suite, serving as a


comprehensive development framework for Ethereum dapps. It provides
developers with tools, including a smart contract compiler, automated
testing, and deployment scripts. With Truffle, developers can efficiently
write and manage smart contracts using the Solidity programming
language. It simplifies the development process by offering features like
contract migration, network management, and debugging.

Truffle also integrates with popular testing frameworks and allows


developers to simulate real-world scenarios, ensuring the reliability and
security of their smart contracts before deployment.
What are the Features of
Truffle?
Truffle offers a range of powerful features, making it a comprehensive development framework for Ethereum dapps. Some key features include:
1. Smart Contract Management
Truffle provides tools for creating, organizing, and maintaining smart contracts within projects, simplifying contract management.
2. Automated Contract Testing
Developers can write comprehensive test suites using Truffle’s testing framework, ensuring the correctness and robustness of their smart contracts.
3. Scriptable Migration and Deployment
Truffle automates the migration and deployment of smart contracts across different networks, making managing and deploying contracts easy.
4. Network Management
Truffle allows developers to connect and configure various Ethereum networks, facilitating seamless switching between networks during development
and deployment.
5. Interactive Console
Truffle’s interactive console enables developers to interact directly with deployed contracts and the Ethereum blockchain, aiding debugging and
exploration.
6. Contract Compilation and Deployment
Truffle provides a streamlined process for compiling and deploying smart contracts, simplifying the deployment workflow.
7. Asset Management
Truffle helps manage project assets, including contract artifacts, libraries, and configurations, ensuring efficient organization and deployment of
resources.
Truffle empowers developers to efficiently build, test, and deploy decentralized applications on the Ethereum blockchain with these features.
Multi-signature wallet
Multi-signature wallet is a smart contract that allows multiple users in a
blockchain to sign digitally on agreeing on the transaction. In muti
signature wallets you can set up multiple owners for a wallet with
multiple private keys by which no one can send a transaction without
those multiple signatories.
“ Thus Multi-sig holds enormous potential like trust-less escrow, trust
less margin, user funds security, allowing the faster transaction,
simplified access of wallets etc."
● If only a single key is used to access funds and that key is lost or
hacked it is not possible to regain the funds.
● In such situation, 3 keys are issued to the users in which 2 of them
are used to access funds for the transaction.
● The first key will be kept in an online wallet and the second key in a
safe offline location and the third key is held by the multi-signature
provider.
The multi-signature provider cannot hold or have the access to your
funds, they can only hold the key for only approving the transaction.
Thus multisig wallet adds the layer of security for cryptocurrency
transactions.
Multisig wallet in Crypto/Token exchange: Using the multi-signature
wallet is the safety precaution for users. Giving the token exchange
service through the ethereum multisig wallet is the modern day of
development. More importantly, it can avoid the scams entirely.
Smart Contracts: What could go
wrong?
TheDAO hack (2016) Parity Wallet bug (2017)
• TheDAO raised ~$150M in ICO • Parity wallet library was used to
• Soon after, it got hacked ~$50M manage multisig wallet
contracts
• Price of Ether halved
• Parity wallet has been removed
• Ethereum community decided due to a "bug"
to hard-fork
• Dependent contracts became
• Attacker used a re-entrancy unable to send funds
vulnerability
• Around $280M frozen
What can possibly go wrong?
function withdraw(uint amount) {
require(balances[msg.sender] >=
amount);
• Programming language / contracts msg.sender.transfer(amount);
balances[msg.sender] -= amount;
• Call to the unknown }
• Gasless send
function withdraw(uint amount) {
• Mishandled exceptions require(balances[msg.sender] >=
• Type casts amount);
msg.sender.send(amount);
• Reentrancy balances[msg.sender] -= amount;
• Keeping secrets }

• Unchecked caller function withdraw(uint amount) {


require(balances[msg.sender] >=
• Input validation amount);
if (!msg.sender.send(amount))
revert();
balances[msg.sender] -= amount;
}
15
Reentrancy attack

Reentrancy attack is one of the most common attacks on EVM-based smart contracts. It is an attack
with devastating damages, which can be seen in many past incidents such as:
• The DAO attack
• Cream Finance attack
Quick look at Reentrancy attack
Quick look at Reentrancy attack
Quick look at Reentrancy attack
Quick look at Reentrancy attack
Quick look at Reentrancy attack
Step 1: Contract B will call the withdrawal
function of contract A.
Step 2: Contract A check balance is greater than 0 or not. If this
condition is satisfied, contract A will send Ether to contract B
and make the fallback function of contract B is executed:
Step 3: The fallback function of contract B calls the withdraw
function of contract A while the balance value of B is recorded
by A is still greater than 0:
Step 4: Contract A will send Ether to
contract B again.
Motivating example Attack scenario example

contract Bank { Data: balance of each user


• Simplified version of the DAO hack
mapping(address=>uint) balances; Operation: deposit money
C
Balances
U1 U2
U2
function deposit() payable { Withdraw 50
Receive money
balances[msg.sender] += msg.value; 100 50+50
} Increase balance
Check ok
function withdraw(uint amount) { Operation: withdraw money
if (balances[msg.sender] >= amount) {
Check balance 50 50+50 Transfer 50
if (!msg.sender.call.value(amount)
("")) { Transfer money Withdraw 50
revert(); Reduce balance
} Check ok
balances[msg.sender] -= amount; Transfer 50
} 0 50+50
} 0 Reduce 50
}
50+0
0 50+ Reduce 50
Vikram Dhillon, David Metcalf, and Max Hooper. The DAO hacked. (-50)
In: Blockchain Enabled Applications, pp. 67–78. Springer, 2017.
26
Type of Reentrancy

• Single Function Reentrancy


• Cross-Function Reentrancy
• Cross-Contract Reentrancy
Okay, but is this reentrancy attack a
significant problem?
• Uniswap/Lendf.Me hacks (April 2020) – $25 mln, attacked by a hacker
using a reentrancy.
• The BurgerSwap hack (May 2021) – $7.2 mln, because of a fake token
contract and a reentrancy exploit.
• The SURGEBNB hack (August 2021) – $4 mln, seems to be a
reentrancy-based price manipulation attack.
• CREAM FINANCE hack (August 2021) – $18.8 mln, reentrancy
vulnerability allowed the exploiter for the second borrow.
• Siren protocol hack (September 2021) – $3.5 mln, AMM pools were
exploited through reentrancy attack
Cross-Contract Reentrancy

Cross-contract reentrancy can happen when a state from one contract is used in another contract, but that
state is not fully updated before getting called.
The conditions required for the cross-contract reentrancy to be possible are as follows:
• The execution flow can be controlled by the attacker to manipulate the contract state.
• The value of the state in the contract is shared or used in another contract.
What can possibly go wrong?

• Execution engine uint8 x = 255;


uint8 y = 1;
• Under/overflows
• Immutable bugs uint8 z = x + y; // z ==
• Ether lost in transfer 0
• Stack size limit int8 x = 127;
int8 y = 1;

int8 z = x + y; // z == -128

32
The BECToken
contract BecTokenSimplified {
using SafeMath for uint256;
Total tokens
uint256 public totalSupply;
Balance of each user
mapping(address => uint256) balances;
Initialization
constructor() {
totalSupply = 7000000000 * (10**18); Creator gets 7x10
27

balances[msg.sender] = totalSupply;
} Batch transfer value to N receivers
function batchTransfer(address[] receivers, uint256 value) returns (bool)
{ Total amount = value x N
uint256 amount = receivers.length * value;
require(value > 0 && balances[msg.sender] >= amount); Reduce sender balance by total
balances[msg.sender] = balances[msg.sender].sub(amount);
Increase receiver balances
for (uint i = 0; i < receivers.length; i++) {
balances[receivers[i]] = balances[receivers[i]].add(value); by value N times
}
return true;
} 33
}
The BECToken
Creator
7x1027
Attacker1
0
Attacker2
0
Attacker3
0
Attacker4
0
Attacker5
0
Σ 7x1027
• Let’s "print” money
value =
28948022309329048855892746252171976963317496166410141009864396001978282409984;
attacker1: bectoken.batchTransfer([attacker2, attacker3, attacker4,
N = 4
attacker5], value)
amount = value * N = 0

Creator Attacker1 Attacker2 Attacker3 Attacker4 Attacker5


7x1027 0 2.9x1076 2.9x1076 2.9x1076 2.9x1076 Σ 1.16x1077
 Really happened (with different parameters)

https://medium.com/@peckshield/alert-new-batchoverflow-bug-in-multiple-erc20-smart-contracts-cve-2018-10299-511067db6536
34
What can possibly go wrong? contract Market {
uint public price;
uint public stock;
...
• Blockchain and cross-peer protocols function setPrice(uint _price) {
if (msg.sender == owner)
• Unpredictable state price = _price;
• Transaction ordering dependency }
function buy(uint quantity) {
• Generating randomness if (msg.value < quantity * price ||
• Time constraints stock < quantity) revert();
stock -= quantity;
• Timestamp dependency ...
}
}
buy
setPrice

setPrice buy

35
A vulnerability using Self
Destruct
• A malicious contract can use selfdestruct to force sending Ether to any
other contract.
• A contract without a receive or fallback function can only receive
ether through a coinbase transaction (miner block reward) or if
someone sets it as the destination of a selfdestruct. These are the
only ether transfers a contract cannot react to nor reject.
Delegatecall

delegatecall is tricky to use and wrong usage or incorrect understanding


can lead to devastating results.
We must keep 2 things in mind when using delegatecall
• delegatecall preserves context (storage, caller, etc...)
• storage layout must be the same for the contract calling delegatecall and
the contract getting called
Accessing Private Data

All data on a smart contract can be read.

Let's see how we can read private data. In the process you will learn
how Solidity stores state variables.
2*256 slot
Source of Randomness

blockhash and block.timestamp are not reliable sources for


randomness.
Denial of Service

There are many ways to attack a smart contract to make it unusable.


One exploit we introduce here is denial of service by making the function to
send Ether fail.
Phishing with tx.origin

What's the difference between msg.sender and tx.origin?


If contract A calls B, and B calls C, in C msg.sender is B and tx.origin is A.
Vulnerability
A malicious contract can deceive the owner of a contract into calling a
function that only the owner should be able to call.
Hiding Malicious Code with
External Contract
In Solidity any address can be casted into specific contract, even if the
contract at the address is not the one being casted.
Honeypot

A honeypot is a trap to catch hackers.


Vulnerability
Combining two exploits, reentrancy and hiding malicious code, we can build
a contract that will catch malicious users.
Front Running

Transactions take some time before they are mined. An attacker can
watch the transaction pool and send a transaction, have it included in a
block before the original transaction. This mechanism can be abused to
re-order transactions to the attacker's advantage.
Block Timestamp Manipulation

Vulnerability
block.timestamp can be manipulated by miners with the following
constraints
• it cannot be stamped with an earlier time than its parent
• it cannot be too far in the future
Signature Replay

Signing messages off-chain and having a contract that requires that


signature before executing a function is a useful technique.
• reduce number of transaction on chain
• gas-less transaction, called meta transaction
Vulnerability
Same signature can be used multiple times to execute a function. This
can be harmful if the signer's intention was to approve a transaction
once.
Why is this important?
 Real consequences  Public platforms: open world
o Contracts manage real-life assets o Available to everyone
• Ethereum: 15B USD market cap o Everyone sees the code
o Not only financial aspects o Everyone can send transactions
• E.g., smart lock

 Permanent
o Once deployed, no patching1 Let’s do
o No transaction reverting2
verification!
o Compile time verification needed
1
There are patterns to kill a contract or redirect calls, but that brings up new vulnerabilities
2
Apart from solutions involving a central authority
48
Verification
Approaches

49
Testing
x=2
y=3
• Contract state + input  expected state + output
• Traditional testing strategies and techniques
• Frameworks help (e.g., Truffle) f(y) {
x0 = x;
• Setup test network with initial state x += y;
• Execute steps, check state and output return x0;
}
• Advantages and drawbacks
• Efficient in finding bugs, understanding the code
• Test high-level business logic 2
• Manual process x=5
• Cannot test every state and input
• Complex scenarios: other users, contracts, miners
• DAO requires an attacker contract https://truffleframework.com/docs/truffle/testing/testing-your-contracts

50
Audit / Review
• Experts review and analyze the contracts
• Contact, get a quote
• Perform audit
• Report
• Fix issues
• Advantages and drawbacks
• Detailed, high/low-level analysis
• Expensive
• Time consuming, non-interactive
• Experts are human too, can make mistakes
https://zeppelin.solutions/security
https://solidity.readthedocs.io/en/v0.5.4/security-considerations.html
51
Vulnerability patterns function f() { function g() {
... ...
if
a.send(value); (a.send(value)) ...;
• Pattern matching }
...
}
...

• Abstract syntax tree (AST)


• Violation/compliance patters FunctionBody FunctionBody

• Advantages and drawbacks FunctionCall IfStatement

• Fully automated a send value


FunctionCall
• Scalable to large contracts
a send value
• False alarms
• Missed bugs
• No high-level properties

Luu, Chu, Olickel, Saxena, Hobor - Making Smart Contracts Smarter (2016)
Tsankov, Dan, Drachsler-Cohen, Gervais, Bunzli, Vechev - Securify Practical Security Analysis of Smart Contracts (2018)
52
Symbolic execution ret = a.send(value);
if (x) {
if (ret) { ... }
...
• Reason about paths symbolically } else {
...
• Control flow patterns if (ret) { ... }
}
• Data flow patterns ...

• Advantages and drawbacks ret = a.send(value)


• Similar to pattern-based
x
• Higher-level patterns ret

• Less false alarms …
• Less scalable ret
… …
Return value of send is
https://mythx.io/ checked on all paths …
https://github.com/melonproject/oyente
53
Formal verification techniques
function abs(int x) returns
(int) {
int y;
• Translate code to formal representation if (x >= 0) y = x;Overflow!
• Apply mathematical reasoning else y = -x;
assert(y >= 0);
• Formal requirement needed too return y;
• E.g., assert, require, annotations }
• Advantages and drawbacks
• Automated ( 𝑥≥0∧ 𝑦=𝑥 ) ? ¿∨ ⟹ 𝑦 ≥0
• High-level properties ( 𝑥≱ 0∧ 𝑦=−𝑥 ) ¿ ¿ ¿ ¿
• Fully formal, real errors, bugs not missed
• Depending on assumptions and abstractions
• Might suffer from scalability issues
• Extra developer effort for requirements https://github.com/SRI-CSL/solidity/tree/boogie/
D’Silva, Kroening, Weissenbacher – A Survey of Automated Techniques for Formal Software Verification (2008)
54
Reentrancy revisited
Invariant: must hold before and
Attack scenario example

after every public function call


Balances U2
C U1 U2 Withdraw 50
/** @notice invariant this.balance ==
100 50+50
sum(balances) */
contract Bank { Check ok

mapping(address=>uint) balances; 50 50+50 Transfer 50


Withdraw 50
function withdraw(uint amount) {
if (balances[msg.sender] >= amount) {
if (!msg.sender.call.value(amount)("")) {
revert(); Invariant
} violated
balances[msg.sender] -= amount;
}
}
}

https://github.com/SRI-CSL/solidity/tree/boogie/
55
Reentrancy revisited
Invariant: must hold before and
Attack scenario example

after every public function call


Balances U2
C U1 U2 Withdraw 50
/** @notice invariant this.balance ==
100 50+50
sum(balances) */
contract Bank { Check ok

mapping(address=>uint) balances; 100 50+0 Reduce 50

function withdraw(uint amount) { 50 50+0 Transfer 50


if (balances[msg.sender] >= amount) { Withdraw 50
balances[msg.sender] -= amount;
if (!msg.sender.call.value(amount)("")) {
revert(); Check FAIL
}
First reduce
} then transfer
}
Specification
} holds
https://github.com/SRI-CSL/solidity/tree/boogie/
56
Tools
• Truffle Suite
• Development environment and testing framework
• Securify, Oyente, Maian, MythX, Slither
• Pattern-based, symbolic execution
• Solc-verify
• Automated formal verification
• VeriSolid
• Model-based design and code generation
https://truffleframework.com/ https://mythx.io/
https://securify.chainsecurity.com/ https://github.com/trailofbits/slither
https://github.com/melonproject/oyente https://github.com/SRI-CSL/solidity/tree/boogie/
https://github.com/MAIAN-tool/MAIAN https://github.com/VeriSolid/smart-contracts
57
Conclusions
• Smart contracts are not so smart
• Infamous hacks: DAO, BECToken
• Vulnerabilities on different levels
• Importance of verification
• Verification approaches
• Audit, testing, pattern-based,
symbolic execution, formal methods
• Tools

58
MythX
Mythx Feature Comparison
Features MythX

Re-Entrancy(RE)

Unhandled Exceptions
(UE)
Locked Ether (LE)

Transaction Order
Dependency (TO)
Integer Overflow (IO)

Unrestricted Action
(UA)
User added
Assertion(AS)
Average Time T

False Positive
Thank You

You might also like