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

Bridge with Encryption

Bridge with Encryption

By Brice

Buzzvil

April 12, 2018
Tweet

More Decks by Buzzvil

Other Decks in Programming

Transcript

  1. /35 Contents • Overview of the Task • Structure of

    Bridge • Cryptographic Part • Cryptographic Decision: ECDH with Curve25519, ChaCha20-Poly1305 • Study of cryptography • Implementation Part • Library • Class Structure • Handshake • Flows • Remain Works 3
  2. /35 Overview of the Task • Object • Encrypt messages

    between M app and L app on the bridge • Problems • Save the secret key in the source code? • If use asymmetric cipher, then how handle the handshake • If a message is lost… • If both start handshake at the same time • If the session key is lost… • Hard to reproduce corner cases of the parallel processing • If encryption is failed, the communication is blocked • If once it released, can we change the handshake algorithm compatible with older one? • ….. • Need your help! 4
  3. /35 Structure of Bridge L App M App Bridge Bridge

    DataStorage EventHandler RequestHandler 5
  4. /35 Structure of Full Migration L App M App MigrationTo

    MigrationFrom Bridge Bridge BuzzScreen DataStorage EventHandler RequestHandler BuzzScreen 6
  5. /35 Structure of Light Migration L App M App MigrationClient

    MigrationHost Bridge Bridge BuzzScreen DataStorage EventHandler RequestHandler BuzzScreen 7
  6. /35 Cryptographic Decisions • Key Exchange • Elliptic-Curve Diffie-Hellman •

    Elliptic-Curve • Curve25519 • Symmetric Cryptography • ChaCha20 • Message Authenticaion Code • Poly1305 Gains • Small battery usage • Small key with high security level • Fast encryption / decryption • Forward secrecy 8
  7. /35 Security Level (Bits of security) • n-bit security: 2"

    operations are needed to break it • Sufficient Length • 128 bits of security is sufficient until next revolutionary breakthrough in either mathematics or technology • 112 bits of security is sufficient until 2030 • Symmetric cryptography • Normally equal to the key size • AES-128 (key size 128 bits) offers a 128-bit security level • Asymmetric cryptography • The entropy is decrease because it have to provide asymmetric function • RSA-3072 offers a 128-bit security level 9
  8. /35 Discrete Logarithm Problem • RSA / Traditional DH •

    $ = • A, B, x are integers, p is a public prime • A is a public information, B is a public key • It is easy to calculate B from x • It is hard to calculate x from B • Elliptic Curve Cryptography • = • P, G is a point with integer coordiante, n is an integer, p is a public prime • G is a public information, P is a public key • It is easy to calculate P from n • It is hard to calculate n from P 10
  9. /35 Elliptic Curve Cryptography • Using special computations on elliptic

    curve (0 = 2 + + ) What is the pros? • Short encryption key • 256 bits are enough to offer 128-bits of security (compare to RSA-3072) • Faster • With 256-bit key is over 20 times faster than RSA-2048 11
  10. /35 Famous Elliptic Curves • NIST-p256 • NIST-p384 • NIST-p521

    • Curve25519 • OpenSSL default • … 12
  11. /35 Perfect Forward Secrecy (PFS) To provide PFS • Use

    temporary session key • Do not save session key in permanent storage 13
  12. /35 Diffie-Hellman(-Merkle) Key Exchange (DHM, DH) • An method allows

    two parties can have a shared secret key over an insecure channel without prior knowledge • Traditional DIffie-Hellman (DH) • = = () = ()= • Elliptic-Curve Diffie-Hellman (ECDH) • = = () = () = • Pros • Share a session key through unsafe channel • Perfect forward secrecy 14
  13. /35 Symmetric Cryptography + MAC (AEAD) • AES • AES-CBC

    • Widely used • Attack on CBC mode is emerged • AES-GCM • No known breaks • Slow • Small size nonce (8 bytes) • ChaCha20-Poly1305 • Faster than AES • No known breaks • Chosen by • Google • Cloudflare • TLS 1.3 15
  14. /35 Nonce • An arbitrary number that can only be

    used once • Can be public to share same value between sender and receiver • Create different encrypted text with same plain text • Action: Utils.leIntToByteArray(sequence number) || 0x00000100 • Data: Utils.leIntToByteArray(sequence number) || 0x00000200 • Same plain text: Hello World! • 8L58Vr3ZNAiFq91KjhvgTKTs2g/sMzjW… • hsBDhUcLpoC4bNwxB56sEQez9rv7tovi… • VRiKEd/HFcxekHSRHEmp3JuYniqBNY49… 16
  15. /35 DJB • 종로빈대떡 아닙니다 • Danial J. Bernstein •

    Bernstein v. United States • Challenges to the restriction on the export of cryptography from the United States • SipHash • Curve25519 • ed25519 • ChaCha20 • Poly1305 17
  16. /35 Library • Needs JNI • OpenSSL • Libsodium •

    High-level API • All ABIs are supported by published aar • arm64-v8a, armeabi, armeabi-v7a, mips, mips64, x86, x86_64 19
  17. /35 Using APIs of Libsodium • Sodium.randombytes_buf(ByteArray buffer, int length)

    • Sodium.crypto_scalarmult_curve25519_base(ByteArray pk, ByteArray sk) • Sodium.crypto_scalarmult_curve25519(ByteArray sessionKey, sk, pk) • Sodium.crypto_aead_chacha20poly1305_encrypt( cipherTextBuffer, ctLength, payloadBuffer, plLength, associatedData, adLength, notUsed, nonce, sessionKey) • Sodium.crypto_aead_chacha20poly1305_decrypt( plainTextBuffer, ptLength, notUsed, cipherTextBuffer, ctLength, associatedData, adLength, nonce, sessionKey) 20
  18. /35 Class Structure • CryptoContext • Management status of crypto

    • Provide functions of crypto (encrypt, decrypt) L App M App Bridge Bridge DataStorage EventHandler RequestHandler CryptoContext CryptoContext CryptoManager CryptoManager CryptoManager CryptoManager 21
  19. /35 Develop Environment • Modify bridge (or other) module of

    buzzscreen-sdk • Increase the version • Deploy to local maven repository (~/.m2/…) • Create L and M app using migration-client and migration-host • Communicate using the EventHandler and RequestHandler • Increase the version of the module • Load bridge (or other) module from local maven repository • Build • Run • See log 22
  20. /35 Develop Environment – Test 23 val r = Random()

    val handler = Handler(Looper.getMainLooper()) handler.postDelayed(object : Runnable { override fun run() { bridgeType = if (r.nextBoolean()) BridgeType.EVENT_HANDLER else BridgeType.REQUEST_HANDLER sendMessage(inputMessage.text) handler.postDelayed(this, r.nextInt(2000).toLong()) } }, r.nextInt(2000).toLong())
  21. /35 Custom Bundle (temp. name) • To distinguish encrypted bundle

    and non-encrypted, handshake bundles • All *Bundle is attached into a bundle using putSerializable(key, *Bundle) • Constants.EVENT_BUZZVIL_BRIDGE_CRYPTO = "EVENT_BUZZVIL_BRIDGE_CRYPTO"; • Constants.REQUEST_CODE_BUZZVIL_BRIDGE_CRYPTO = 500; • sendersPublicKey • receiversPublicKey • sequenceNumber • id • data • sequenceNumber • failedToDecrypt HandshakeBundle EncryptedBundle EncryptedAckBundle 24 • handshakeVersion BaseBundle
  22. /35 Set receivers • Initializers are must called • com.buzzvil.buzzscreen.bridge.EventHandler.init(context,

    packageName) • com.buzzvil.buzzscreen.bridge.MsgSender.init(context, packageName) • Each initializer initiate it’s CryptoManager • The receivers are set in the constructor of each CryptoManager 25
  23. /35 Handshake Sa, Pa 1, Pa, null Sb, Pb 1,

    Pa, Pb A B 1, Pa, Pb 1, Encrypted Messages Session Key Session Key 26
  24. /35 Handshake Algorithm • When the CryptoContext is refreshed, the

    hadnshake version is increased • Ignore when the packet’s handshake version is lower than mine • If the packet’s handshake version is higher than mine • If it is encrypted: change my version to that version + 1, and refresh handshake • If it is handshake: change my version to that version, and recreate key pair • Always trust sender’s public key in HandshakeBundle • Refresh handshakes when receiver’s public key in HandshakeBundle from mine • Remove saved secret key, public key, partner’s public key and session key • Send encrypted bundles after correct HandshakeBundle(Pa, Pb) is received 27
  25. /35 Encryption / Decryption of EventHandler A B EncryptedBundle(seq n)

    EncryptedAckBundle(seq n) Decrypt and handle it 28
  26. /35 Encryption / Decryption of RequestHandler A B EncryptedBundle(seq n)

    EncryptedAckBundle(seq n), EncryptedBundle(seq m) Decrypt and handle it Encrypt the response bundle 29
  27. /35 Flows of sender • EventHandler.post() or RequestHandler.request() is called

    • Save the (action, bundle) or request(requestCode, bundle, listener) to a buffer • If there is a session key • Encrypt (action or requestCode, bundle) and send • elif no handshake process is on • Handshake • Encrypt (action or requestCode, bundle) and send for all entries in buffers 30
  28. /35 Flows of receiver • Receivers are set • Handshake

    is received • Do the handshake process • Encrypted is received • Decrypt failed • Clear CryptoContext and re-handshake • Decrypt succeeded • Parse (action or requestCode, bundle) and run the handler • send EncryptedAck with the sequence number of Encrypted • send Encrypted if response bundle have to be sent • EncryptedAck is received • If decrypted successfully, remove the entry of sequence number of it from the buffer 31
  29. /35 Flows of Encryption • Bundle • byte[] Util.serializeBundle(Bundle) •

    Convert to a ByteStream using parcel • Gzip the ByteStream • ByteStream encrypted CryptoContext.encrypt(byte[] nonce, byte[] plainText) • ByteArray output from encrypt using cipher chacha20poly1305 • return output • Create EncryptedBundle • int sequenceNumber, byte[] idBytes, byte[] dataBytes • Bundle.setSerialize(key, EncryptedBundle) 32
  30. /35 Flows of Decryption • Bundle.getSerialized(key) • EcnryptedBundle • Get

    context from EncryptedBundle • int sequenceNumber, byte[] idBytes, byte[] dataBytes • byte[] CryptoContext.decrypt(encrypted, nonce) • ByteArray output from decrypt using cipher chacha20poly1305 • Bundle Util.deserializeBundle(byte[]) • Un-gzip the ByteStream • Convert to a bundle using parcel • Bundle 33
  31. /35 Extension • EventHandler.post(action, bundle, boolean encrypt) • RequestHandler.request(request, boolean

    encrypt) • Freely choose whether to encrypt or not • Both encrypt • One-way encrypt • No encrypt 34
  32. /35 Remain Works • Add entry to the open source

    software library list • Add encrypt options to buzzscreen-client / buzzscreen-host • Documentation • Various tests • Obfuscation (proguard) and parcel compatibility issue • Merge the crypto process code of CryptoManager in two classes and decoupling from outer class 35