Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Smart Contract Security

Avatar for mjansing mjansing
October 18, 2018

Smart Contract Security

Schon 1999 formulierte Lawrence Lessig “Code is law”. Diese Aussage ist im Bezug auf Smart Contracts relevanter denn je. Reale und virtuelle Welt verschmelzen hier miteinander, Security-Probleme können direkt zu immensen materiellen Schäden führen.

Smart Contracts bringen eine ganze Reihe von sicherheitsrelevanten Besonderheiten mit, die bei der alltäglichen Software-Entwicklung nicht auftreten, beispielsweise: ein einfaches Redeployment ist nicht möglich, Testen ist alles andere als trivial und Monitoring ist extrem schwer.

Lernen Sie in diesem Vortrag die typischen Fallstricke bei der Entwicklung von Smart Contracts kennen, und wie Sie diese vermeiden können.

Avatar for mjansing

mjansing

October 18, 2018

Other Decks in Technology

Transcript

  1. Smart Contract Security: Sichere Verträge auf der Blockchain HEISE DEVSEC

    2018 / HEIDELBERG / 18.10.2018 CHRISTOPH ISERLOHN & MARC JANSING
  2. Agenda • Einführung • Was ist eine Blockchain? • Was

    sind Smart Contracts? • Smart Contract Security • Warum sollte man sich damit beschäftigen? • The DAO • Fallstricke / Eigenheiten von Smart Contracts • Best Practices / Tipps
  3. Was ist eine Blockchain? • Eine Liste von Datensätzen (Datenbank)

    • Kryptographisch gesicherte Verkettung • Bestehende Datensätze sind unveränderlich • Neue Datensätze können hinzugefügt werden • Verteilt / Distributed Consensus • Löst das double-spending Problem
  4. Block • Metadaten • Timestamp • Hash des vorigen Blocks

    (PREV) • Protokollversion (Difficulty) • Proof (NONCE) • ... • Payload • Transaktion 1 • Transaktion 2 • ... • Transaktion X
  5. Distributed Consensus • Proof of Work • Proof of Stake

    • Proof of Capacity • Proof of Authority • Proof of X
  6. Proof of Work • Mathematisches/Kryptografisches Aufgabe lösen • Belohnung als

    Anreiz • Wettbewerb - nur ein Gewinner pro Block • Schwierigkeitsgrad anpassbar
  7. Proof of Work - Beispiel Finde einen Hash von Payload,

    Timestamp, Blockindex, Protokollversion und dem NONCE, beim dem die ersten drei Bytes 00 sind: SHA256(payload + timestamp + index + protocol_vsn + NONCE) == 000000??????????????????????????????????????????????????????????
  8. Proof of Work - Mining def mine(payload, t, idx, proto):

    for n in range(0, max_nonce): h = sha256(payload + t + idx + proto + n) if (h[0:3] == b'\x00\x00\x00‘): return (True, n) return (False, 0)
  9. „A smart contract is a set of promises, specified in

    digital form, including protocols within which the parties perform on these promises.“ Nick Szabo, 1996
  10. Was sind Smart Contracts? • = Digitalisierte Verträge inkl. Bedingungen

    & Abläufen • Vollständig automatisiert • Unveränderbar • Verteilt (auf Blockchain-Plattform deployed) • ohne Intermediär
  11. Crowdfunding • Team benötigt Geld für Umsetzung einer Produktidee •

    Projekt wird auf Crowdfunding-Plattform eingestellt • Unterstützer können Projekt/Produkt unterstützen • Finanzierungsziel muss bis Datum Y erreicht sein
  12. Crowdfunding ! "# $ % & ' ( ? Produktteam

    Unterstützer Plattform Kickstarter ) ) ) ) ) )
  13. Crowdfunding ! "# $ % & ' ( ? NODE

    NODE NODE NODE NODE NODE C C C C C C C ) ) ) ) ) ) ) )) ))) Produktteam Unterstützer Smart Contract Plattform
  14. Ethereum • Dezentrale Smart Contract Plattform als globale, transaktionsbasierte state

    machine • Ethereum Virtual Machine (EVM) als „Turing- Vollständige“ Laufzeitumgebung • Formal spezifizifiert (Yellow Paper) • Programmausführung verbraucht „Gas“ • Ether (ETH) als Token/Währung
  15. Ethereum • Account-Typen • Externally owned accounts (EOA) • Contract

    accounts (Programmcode) • Höhere Programmiersprachen kompilieren zu EVM- Bytecode • LLL, Serpend, Solidity, Vyper, Bamboo
  16. Was ist eine DAO? • DAO = Decentralized Autonomous Organisation

    • Struktur und Regeln werden durch Smart Contracts festgesetzt • Keine traditionellen Entscheidungsgremien
  17. The DAO • Bekannteste DAO • Venture capital fund •

    Rekord Crowdfunding/Crowdsale April – Mai 2016 • $150 Millionen in knapp einem Monat • DAO.Link als legale Entität in der Schweiz – „Take money from an unknown source as long as you know where it‘s going“
  18. The DAO Hack • Mehrstufiger Angriff / Reentrancy Problem •

    $50 Millionen entwendet • Hack? • Fork in Ethereum und Ethereum Classic • The DAO wurde danach aufgelöst
  19. Smart Contract Eigenschaften • Unveränderbar • Code kann nach Deployment

    nicht geändert werden • Neue Instanz möglich • Kein Sonderrechte für „Administratoren“ • Außer explizit implementiert • Löschen/Leeren wenn explizit implementiert • Public by Design • Jeder kann mit Vertrag interagieren
  20. Visibility • Funktionen haben implizite Sichtbarkeit • Visibility modifiers •

    Public (default ⚠) • External • Private • Internal • Sichtbarkeit sollte immer explizit definiert werden
  21. Visibility pragma solidity 0.4.25; contract HashForEther { function withdrawWinnings() {

    // Winner if the last 8 hex characters of the address are 0 require(uint32(msg.sender) == 0); _sendWinnings(); } function _sendWinnings() { msg.sender.transfer(this.balance); } }
  22. Visibility pragma solidity 0.4.25; contract HashForEther { function withdrawWinnings() public

    { // Winner if the last 8 hex characters of the address are 0 require(uint32(msg.sender) == 0); _sendWinnings(); } function _sendWinnings() private { msg.sender.transfer(this.balance); } }
  23. Over/Underflow • EVM spezifiziert feste Datengrößen für Integer • int8/uint8

    (8 Bit, Range [0, 255] • int256/uint256 (256 Bit, Range [0, 2256] • Overflow = Addieren über max. Datentypgröße • Underflow = Subtrahieren über min. Datentypgröße • Nutze sichere, geprüfte Bibliotheken für arithmetische Operationen (z.B. SafeMath)
  24. pragma solidity 0.4.25; contract OverflowUnderFlowExample { uint256 public min =

    0; uint256 public max = 2**256-1; function underflow() public { min -= 1; // produce overflow } function overflow() public { max += 1; // produce underflow } } Over/Underflow
  25. pragma solidity 0.4.25; import "./SafeMath.sol"; contract OverflowUnderFlowExample { using SafeMath

    for uint256; uint256 public min = 0; function insecureSubtract() public { min -= 1; // overflow } function secureSubtract() public { min = min.sub(1); // throws exception } } Over/Underflow
  26. • Bekannt vom DAO-Hack • Problem bei Zustandsänderungen nach externen

    Aufrufen • „Checks-Effects-Interactions“-Pattern beachten 1. Prüfungen durchführen 2. Zustand aktualisieren 3. Externe Aufrufe Reentrancy
  27. contract EtherStore { mapping(address => uint) private userBalances; function depositFunds()

    public payable { userBalances[msg.sender] += msg.value; } function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; // INSECURE: external call before state change require(msg.sender.call.value(amountToWithdraw)()); userBalances[msg.sender] = 0; } } Reentrancy
  28. import "EtherStore.sol"; contract Attack { EtherStore public etherStore; constructor(address _etherStoreAddress)

    { etherStore = EtherStore(_etherStoreAddress); } function attackEtherStore() public payable { etherStore.depositFunds.value(msg.value)(); // send eth to depositFunds() etherStore.withdrawBalance(msg.value); // start the magic } function () payable { etherStore.withdrawBalance(msg.value); // where the magic happens } } Reentrancy
  29. contract EtherStore { mapping(address => uint) private userBalances; function depositFunds()

    public payable { userBalances[msg.sender] += msg.value; } function withdrawBalance() public { uint amountToWithdraw = userBalances[msg.sender]; // SECURE: external call at the end userBalances[msg.sender] = 0; require(msg.sender.call.value(amountToWithdraw)()); } } Reentrancy
  30. Weitere… • Delegatecall • Unexpected Ether • Entropy Illusion •

    External Contract Referencing • Short Address/Parameter Attack • Unchecked CALL Return Values • Race Conditions/Front Running • Denial of Service (DoS) • Block Timestamp Manipulation • Constructors with Care • Uninitialized Storage Pointers • Floating Point and Precision • Tx.Origin Authentication
  31. Zusammenfassung • Wenn Ihr Glück/Pech habt, werden viele/einige von Euch

    freiwillig/gezwungenermaßen in den nächsten zwei Jahren mit Blockchain und Smart Contracts zu tun haben
  32. Zusammenfassung • Smart Contracts sind normale Programme • Programme haben

    Bugs • Bugs können sicherheitsrelevant sein • Sicherheitslücken in Smart Contracts haben in der Regel direkte monetäre Auswirkung • Bugfixes für Smart Contracts können nicht einfach deployt werden
  33. Literatur • https://ethereum.org/ • Solidity Dokumentation: Security Considerations • Consensys

    Ethereum Smart Contract Security Best Practices • Buchempfehlung „Mastering Ethereum“ • Artikel: Kluge Kontrakte auf Basis von Ethereum • https://openzeppelin.org/ • https://truffleframework.com/
  34. Danke! Fragen? www.innoq.com innoQ Deutschland GmbH Krischerstr. 100 40789 Monheim

    am Rhein Germany +49 2173 3366-0 Ohlauer Str. 43 10999 Berlin Germany Ludwigstr. 180E 63067 Offenbach Germany Kreuzstr. 16 80331 München Germany Gewerbestr. 11 CH-6330 Cham Switzerland +41 41 743 01 11 Albulastr. 55 8048 Zürich Switzerland innoQ Schweiz GmbH Marc Jansing [email protected] Christoph Iserlohn [email protected]