SIGPL Smart Contract 분석과 PL 2018-08-20 이종협
Blockchain intro Bitcoin Ethereum Hyperledger Transaction Model State + account model Framework State n Transaction State n+1 + EVM (Ethereum Virtual Machine)
- 믿지 않는 사용자간의 agreement + coordination - 블록체인에 복잡한 기능을 제공 Smart contract “Contract 를 구현하고, 강제하고, 실행시켜 주는 code” … Smart contract money money data data Blockchain
Solidity code contract MyToken { /* This creates an array with all balances */ Storage mapping (address => uint256) public balanceOf; /* Initializes contract with initial supply tokens to the creator of the contract */ function MyToken ( uint256 initialSupply ) public { /* (or constructor ( uint256 initialSupply ) public { ) */ Constructor balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens } /* Send coins */ function transfer (address _to, uint256 _value) public { require (balanceOf[msg.sender] >= _value); // Check if the sender has enough Function require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows (Public) balanceOf[msg.sender] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient } /* Fallback */ function () payable { Fallback ... function } }
Storage 어떠한 (Money!) Balance ! 가지는가? 의미를 Smart contracts 어떻게 볼 것인가 ? Vending Distributed Secure machine objects execution (External) ≃ Threads using concurrent objects in shared memory
Academic Pedigree from “Bitcoin’s academic pedigree” Narayanan et al.
Smart contracts - category Distribution of transactions by category from “an empirical analysis of smart contracts” Bartoletti et al.
Smart contract lifecycle Solidity Compiler EOA EOA Tx EOA EOA EVM C Vyper Tx Compiler EOA EOA Bytecode C Tx Tx EOA Tx C Tx Tx EOA C EOA EOA Tx Tx C C LLL Compiler C EOA Tx Tx Tx C C Tx EOA C EOA Tx Deployment C Deploy (Runtime EVM C EOA Code code) C Tx (Ethereum Virtual Machine) EVM Tx (Ethereum Virtual Machine) EVM Ethereum C EOA (Ethereum Virtual Machine) C Full (Miner) EVM Ethereum Runtime node (Ethereum Virtual Machine) Full (Miner) Ethereum Code node Full (Miner) EVM Ethereum node (Ethereum Virtual Machine) Full (Miner) node Ethereum Full (Miner) node
Ethereum Virtual Machine EVM Bytecode EOA Tx Tx EOA Deploy C Tx Tx C EOA C Smart contract 를 위한 execution model Redundantly parallel EVM (Ethereum Virtual Machine) Turing complete! Ethereum GAS Full (Miner) node Design Goal Simplicity Space e ffi ciency Determinism? Specialization Security
Ethereum Virtual Machine Ethereum Smart Contract Called by TX EOA Internal balance Tx Internal contract state Tx EOA Deploy C Permanent storage Tx “Immutable!” Tx C EOA C EVM (Ethereum Virtual Machine) Ethereum Full (Miner) node
EVM internals - GAS 32, 000 200 5 3 2 … … … execution add mul pop sload create ( ) Gas (cost) x Gas price
EVM assembly code PUSH 0 DUP1 PUSH 100 EXP DUP2 SLOAD DUP2 PUSH FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF MUL NOT AND SWAP1 DUP4 PUSH FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF AND MUL OR SWAP1 SSTORE POP
EVM internals - data Stack push / pop / dup / swap / … Data Memory mstore / mload (Var) Volatile, Byte addressing No registers! Storage sstore / sload Permanant (expensive!) Map: 256 bit -> 256 bit
EVM internals - data Arithmetic add / mul / div / sub / … Logical and / not / … Func. System log / codecopy / … call External call (fixed / precompiled)
EVM instructions - “Yellow paper” (pop) (push) In out δ α Value Mnemonic Description 0x00 0 0 Halts execution. STOP stack μ [0] : a 0x01 2 1 Addition operation. ADD μ [1] : b μ ’ [0] : a+b µ 0 s [0] ⌘ µ s [0] + µ s [1] ADD μ [2] : c μ ’ [1] : c 0x02 2 1 Multiplication operation. MUL µ 0 s [0] ⌘ µ s [0] ⇥ µ s [1] 0x51 1 1 Load word from memory. MLOAD µ 0 s [0] ⌘ µ m [ µ s [0] . . . ( µ s [0] + 31)] µ 0 i ⌘ max( µ i , d ( µ s [0] + 32) ÷ 32 e ) The addition in the calculation of µ 0x54 1 1 Load word from storage. SLOAD µ 0 s [0] ⌘ σ [ I a ] s [ µ s [0]] μ : Machine state σ : World state
Execution model Eth Info. data value gasLimit to (Calldata) (Callvalue) gasPrice / init stack Execution environment memory Transaction Smart gas Contract pc nonce v,r,s storage code nonce balance hash hash
Function call handling Function call 과 fall back Fallback function () == == calldata function function payable? signature signature ( callvalue ) sha3( func1 name func2 arg type ... )[0:4]
EVM internals - control (JUMPDEST) Basic block JUMP / JUMPI STOP / REVERT / INVALID / RETURN / SELFDESTRUCT
무엇이 문제인가?
왜 해킹의 대상이 되는가? - 공격자가 즉각적인 reward를 얻는다. - Immutable! - 개발자들에게도 생소한 execution model - Solidity의 abstraction과 실제 EVM과의 mismatch TheDAO Hack - Smart contract는 기본적으로 항상 online + open … Parity MultiSig Wallet
Smart contract를 작성한다는 것은.. “ I want you to write a program that has to run in a concurrent environment under Byzantine circumstances where any adversary can invoke your program with any arguments of their choosing. The environment in which your program executes (and hence any direct or indirect environmental dependencies) is also under adversary control. If you make a single exploitable mistake or oversight in the implementation, or even in the logical design of the program, then either you personally or perhaps the users of your program could lose a substantial amount of money. Where your program will run, there is no legal recourse if things go wrong. Oh, and once you release the first version of your program, you can never change it. It has be right first time. from blog.acolyer.org
취약점? 3. action contract Wallet { (1) mapping(address => uint) private userBalances; (2) function withdrawBalance() { (3) uint amountToWithdraw = userBalances[msg.sender]; (4) if (amountToWithdraw > 0) { (5) msg.sender.call(userBalances[msg.sender]); (6) userBalances[msg.sender] = 0; (7) } (8) } (9) ... (9) } (10) contract AttackerContract { (1) function () { (2) Wallet wallet; (3) wallet.withdrawBalance(); (4) } (5) } (6) Re- entrancy 1. 조건을 확인하고 2. state 를 변경하고 from “ZEUS: Analyzing Safety of Smart Contracts” Kalra et al.
Smart contract 취약점 from “ZEUS: Analyzing Safety of Smart Contracts” Kalra et al. Unchecked send - prodigal SC if(gameHasEnded && !prizePaidOut) { (1) - suicidal SC winner.send(1000); // send a prize to the winner (2) - greedy SC Logic prizePaidOut = True; (3) - posthumous SC } (4) error - DoS (w/ deadlock) while (balance > (1) - unprotected functions persons[payoutCursor Id ].deposit/100*115) { payout = persons[payoutCursor Id ].deposit/100*115; (2) - reentrancy persons[payoutCursor Id].EtherAddress.send(payout); (3) balance -= payout; (4) payoutCursor Id ++; (5) - short address } (6) Incorrect - inconsistent view Undefined logic - force transfer behaviors - integer overflow - DoS (w/ GAS) uint payout = balance/participants.length; (1) for (var i = 0; i < participants.length; i++) (2) participants[i].send(payout); (3) - front running EVM-level Integer - block state dep. overflow + The Ethernaut: https://ethernaut.zeppelin.solutions
무엇을 분석할 것인가? 어떻게 분석하는가? 왜 분석하는가? 어떻게 해결하는가?
근본적인 고민 문제 해결책 제대로 된 나름의 지금 어디에 있는가?
Dijkstra’s three golden rules for successful scientific research (…) Always try to work as closely as possible at the boundary of 1. your abilities. Do this, because it is the only way of discovering how that boundary should be moved forward. We all like our work to be socially relevant and scientifically sound. 2. (…) If the two targets are in conflict with each other, let the requirement of scientific soundness prevail. Never tackle a problem of which you can be pretty sure that 3. it will be tackled by others who are, in relation to that problem, at least as competent and well-equipped as you.
Blockchain에서 Smart contract란 어떤 의미인가?
Smart contract의 안전성이란? Correctness와 fairness의 기준은 무엇인가? Token economy Decentralized governance 구조와 Incentive mechanism으로 정의 무엇에 대하여? Smart contract가 이것을 위배하는가? Smart contracts Correct? Fair?
접근 방법의 변화 보장해야 당위성을 가진다. 변화에 대한 모델이 필요하다. 새로운 프로그래밍 적용할 수 있다. 실용적으로 복잡도가 높은 기술도 프로그램의 한다. 안전성을 특징 생소하다. 실행환경이 한다) (작아야 크기가 작다. Smart Contracts “Symbolic execution” “Formal verification” “Model checking” “Domain-specific …”
Recommend
More recommend