Week9 SmartContract Secuirty Update-1
Week9 SmartContract Secuirty Update-1
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
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
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?
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
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
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
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
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 }
...
}
...
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 ...
https://github.com/SRI-CSL/solidity/tree/boogie/
55
Reentrancy revisited
Invariant: must hold before and
Attack scenario example
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