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

Implementando Serviços Seguros com Node.js, Ty...

Implementando Serviços Seguros com Node.js, TypeScript e libSodium

Primitivas e construções criptográficas modernas oferecem altos níveis teóricos de segurança. Infelizmente, na prática, a criptografia é muitas vezes utilizada de forma incorreta, resultando em diversas vulnerabilidades e brechas de segurança.

Uma biblioteca moderna e multi-plataforma, a libSodium, foi criada justamente para facilitar o desenvolvimento de serviços seguros, e existe uma versão para Node.js.

Nesta palestra, vamos usar Typescript e libSodium para demostrar como é possível evitar muitos dos erros mais comuns, uma vez que essa biblioteca libSodium fornece um conjunto de blocos seguros já testados e prontos para inclusão nas suas aplicações Node.

Avatar for Sean Michael Wykes

Sean Michael Wykes

December 07, 2018
Tweet

More Decks by Sean Michael Wykes

Other Decks in Programming

Transcript

  1. TDC / 2018 2 Sean Michael Wykes • British born

    and educated, living in Brazil since 1997 • Masters Degree (’92) in Information Engineering from Southampton University • 20+ years experience in design and development of systems and secure applications, based on technologies such as smart-cards and secure elements. • Author of “Criptografia Essencial - a Jornada do Criptógrafo” – Elsevier 2016. https://CriptografiaEssencial.com.br
  2. TDC / 2018 4 Onde o Node.js está sendo usado

    Servidor de Aplicações Web Frameworks como Express e semelhantes, servindo html, js, css + recursos Comandos e Processamento Linha de comando, build, transpilação Ferramentas, processamento Embarcado Dispositivos integrados rodando JS + Node. APIs e Web-services Backend para web-apps, aplicativos mobile, dispositivos IoT. Arquiteturas de Microservices, etc
  3. TDC / 2018 5 “Javascript that scales” TypeScript == JS

    para desenvolvedor C# Tipos, Classes, Interfaces Modules, Namespaces, imports Transpilado Gera Javascript de vários sabores – ES3, 5, 6, 2018, .. Bom para: Aplicações de média/grande porte Bibliotecas e APIs Desenvolvedores RAIZ
  4. TDC / 2018 7 Tríade da Segurança da Informação C

    I A T CONFIDENCIALIDADE Confidentiality INTEGRIDADE Integrity DISPONIBILIDADE Availability RASTREABILIDADE Traceability + Tétrade +++
  5. TDC / 2018 8 Componentes x Segurança 1 2 3

    Componente que não é inseguro Componente não contém bugs, falhas ou funcionalidades que podem ser aproveitadas por uma parte maliciosa. + possui features de segurança Incluí funcionalidades explicitas que são necessárias para tornar o componente ou sistema seguro. + é um feature de segurança Provê serviços de segurança, como criptografia, autenticação, autorização, validação, para outros componentes do sistema NÍVEL 0 Componente inseguro Componente contém falhas ou funcionalidades que podem ser aproveitadas por uma parte maliciosa.
  6. TDC / 2018 9 Desenvolvimento Seguro Processos de Desenvolvimento Seguro

    Requisitos de Segurança, Design Seguro, Desenvolvimento de Código Seguro, Validação e Testes de Segurança, SecDevOps Atividades Seguras Incluir atividades novas relacionadas à Segurança, como a Modelagem de Ameaças, Revisão e Análise de Código e os Testes de Penetração Mindset de Segurança Pensar sobre Segurança ajuda a: 1) pensar melhor sobre a Solução e 2) desenvolver produtos melhores e mais seguros +
  7. TDC / 2018 11 11 “Security Thinking é a mentalidade,

    ou mind- set, de tornar segurança uma parte integral do processo de desenvolvimento de software e hardware, através de uma compreensão da importância, complexidade, sutileza e profundidade da Segurança Sistêmica” Security Thinking
  8. TDC / 2018 12 As 5 Máximas do Security Thinking

    Equilíbrio Simplicidade Desconfiança Encapsulamento Abertura
  9. TDC / 2018 13 Os 4 Caminhos de Testes Seguros

    1. FELIZ Condições de Erro Condições Maliciosas Condições Normais 2. INFELIZ Condições Excepcionais 3.FALHA 4. HACKED
  10. TDC / 2018 15 O Produto BaaS Tavern Gateway Brewery

    Server Tavern Admin Smart Tap IoB Wallet Keg RFID NFC
  11. TDC / 2018 16 Arquitetura do Produto BaaS Tavern Gateway

    Smart Tap Brewery Server Keg TCP/IP UDP Tavern Admin IoB Wallet HTTP RFID NFC HTTP Heterogêneos Conectados Semiautônomos Limitados Safe & Secure Características dos sistemas IoT
  12. TDC / 2018 17 PROTEGER: LOGS DO SERVIDOR ARQUIVOS DE

    CONFIGURAÇÃO ENCRIPTAR: COMUNICAÇÕES (DATAGRAMAS, STREAMS) AUTENTICAR: USUÁRIOS DISPOSITIVOS COMANDOS CRÉDITOS DE CONSUMO ... Onde precisamos incluir segurança?
  13. TDC / 2018 19 A new Paradigm Practical High-Level Building

    Blocks q “result” oriented Simple + Intuitive API q designed for clarity C-library (dll,.so) q multiple platforms q multiple programming languages Modern Algorithms (from NaCL) q Stream ciphers - XChacha20, XSalsa20 q Elliptic Curve – Curve25519 / Ed25519 q Password Hash – Argon2 q Authentication – Poly1305 HIGH-LEVEL CRYPTOGRAPHY Only for New Projects
  14. TDC / 2018 20 Password Hashing ü ARGON2 - Password

    Hashing Competition winner ü CPU-intensive ü Memory-hard Modern Uses Server Relief SALTED HASHES ü ‘secure’ Password storage ü Secret key derivation from a password ü Salts, iterations, memory-use parameters ü Alleviate server load ü Calculate password hash on client, store H(hash) on server
  15. TDC / 2018 23 Public Key Cryptography ü Data Integrity,

    Authenticity, Non-repudiation ü Receiver can guarantee Sender’s ID ü Not addressed SIGNED SEALED WRAPPED DATA ENVELOPES ü Data Integrity, Authenticity and Confidentiality ü Addressed to Receiver ü No link to Sender (anonymous) ü Sender cannot open, once sealed ü Data Integrity, Authenticity and Confidentiality ü Addressed to Receiver, but also to Sender ü Plausible deniability (Repudiation)
  16. TDC / 2018 28 Secret Key Cryptography ü Authentication Tag

    (MAC) ü Data Integrity & Authenticity ü Plausible deniability (Repudiation) AUTH’ED ONE-TIME AUTH’ED WRAPPED DATA ENVELOPES ü Shorter Authentication Tag ü Key must be used ONCE only ü AEAD – Authenticated Encryption with Additional Data ü Data Integrity, Authenticity and Confidentiality ü Needs non-repeating NONCE (192 bits)
  17. TDC / 2018 29 Public Key Exchanges ü ECDH –

    mix together secret/public key-pair and a public-key to derive two symmetric keys. PUBLIC EXCHANGE SYMMETRY CLIENT/SERVER KEYS ü Client and Server get the same two keys, but use different (symmetric) API calls.
  18. TDC / 2018 30 Crypto Streams ü Authenticated Encryption for

    streams and channels ü Stream initialized - initial “chunk” generated ü Client pushes data-blocks, generating new chunks ü Server processes chunks, pulling data-blocks SIMPLE “CHUNKY” PUSH/PULL DATA
  19. TDC / 2018 31 Curve 25519 Public Keys ü 32-bytes

    ü Offers 128-bits of security SECRET KEY (private) PUBLIC KEY DERIVABLE FROM SEED 256-BIT “SAFECURVE”ELLIPTIC CURVES ü 32 bytes (2255 – 19) ü ECDH, so can regenerate from Secret Key ü No special values or restrictions ü Deterministically derive key-pairs from a 32-byte seed
  20. TDC / 2018 32 Random Numbers and Key-Generation ü Platform

    “independent” RNG ü Uses best-available entropy sources ü TRNG (hardware) where possible Entropy Helpers Seeds RNG ü Wrappers for random key-generation ü Uniformly-spread random 0..(n-1) ü Wrappers for deterministic key-generation from seed-values.
  21. TDC / 2018 33 Memory and Basic Protection ü Guard

    Pages ü Canaries ü Memory-exception fault on overrun/underrun Bounded Protected No Side Channels “MORE”-SECURE MEMORY BUFFERS ü Locked physical memory - paging/dumps disabled ü Clear when unlocked ü Dynamically adjust visibility/access-conditions: Ø Read-write (normal) Ø Read-only Ø No-access (hidden) ü Time-constant memory compare ü All crypto is time-constant, no array accessed using secret data
  22. TDC / 2018 35 Why yet another crypto library? ü

    High-Level, cross-platform library ü Developer usability as a priority (API) ü No known security problems Modern Vetted Secure BORING CRYPTOGRAPHY ü Best-of-breed Cryptographic Mechanisms ü Strong Primitives, Key-sizes, Nonces ü No magic constants or unexplained tweaks ü Community-validated Cryptographic Primitives ü Solid implementation ü Side-channels - all crypto is time-constant, no array accesses using secret data, time-constant compare
  23. TDC / 2018 36 The Good & Bad bits ü

    Focus on higher-level security problems ü Menu of “trusted” cryptographic building-blocks ü Abstracts multiple details Higher Level Good news Problems FOCUS ü You can now make new mistakes, not old ones! ü Security is still difficult to get right ü New “Algorithms” ü API Bloat ! Remember: If your basic premises are wrong, even the best library will not help. ü libsodium getting wide adoption ü More scrutiny makes better security