Secure channels: Building real world crypto systems
Sander Demeester
BruCON 0x09 · Day 1
Overview
In this insightful talk from BruCON, Sander Demeester delves into the intricate process of constructing and implementing real-world cryptographic systems, with a particular focus on secure channels. The presentation meticulously dissects the theoretical underpinnings of secure communication, transitioning into practical design considerations and real-world implementations. Demeester guides the audience through fundamental security notions, protocol design principles, and the evolution of secure communication standards, using TLS 1.3 and SSHv2 as primary case studies.

Key moments
- 0:00 Introduction and talk overview
- 1:00 Defining core secure channel properties
- 10:00 Formal definition of data confidentiality
- 22:00 Three phases of secure channel construction
- 31:00 Explaining Perfect Forward Secrecy (PFS)
- 46:00 Authenticated Encryption (AEAD) and safe MAC usage
- 50:00 TLS 1.3 record protocol implementation details
- 56:00 SSHv2 CBC plaintext recovery attack
Secure channels: Building real world crypto systems
Speakers: Sander Demeester
Conference: BruCON
YouTube: https://www.youtube.com/watch?v=1ypA7r6CDZ0
Overview
In this insightful talk from BruCON, Sander Demeester delves into the intricate process of constructing and implementing real-world cryptographic systems, with a particular focus on secure channels. The presentation meticulously dissects the theoretical underpinnings of secure communication, transitioning into practical design considerations and real-world implementations. Demeester guides the audience through fundamental security notions, protocol design principles, and the evolution of secure communication standards, using TLS 1.3 and SSHv2 as primary case studies.
The core objective of a secure channel, as elucidated by Demeester, is to guarantee confidentiality, integrity, and authenticity of data exchanged over an inherently untrusted network. This talk is crucial for anyone involved in designing, implementing, or auditing network security, as it unpacks the complexities of cryptographic primitives and their assembly into robust, secure communication links. It highlights why seemingly minor design decisions can have profound security implications, demonstrating these through formal models and a concrete attack example against SSHv2.
Demeester's presentation underscores the importance of a holistic approach to building secure channels, moving beyond mere encryption to encompass authenticated key exchange, key derivation, and the correct application of authenticated encryption schemes. By contrasting the design philosophies of TLS 1.3 and SSHv2, the talk provides valuable lessons on best practices and common pitfalls, offering a comprehensive understanding of what it truly means to establish and maintain a secure communication link in today's interconnected world.
Background
▶ Watch: Introduction and talk overview (0:00)
The concept of a secure channel is foundational to modern digital communication, driven by the omnipresent need to transmit sensitive information across insecure networks. Historically, significant research has been dedicated to formalizing this concept, with a secure channel being defined as a protocol that concurrently provides secure authentication and secure encryption. This means not only ensuring that data remains secret but also verifying the identities of the communicating parties and guaranteeing that the data has not been tampered with.
At its core, a secure channel aims to achieve three primary security properties: confidentiality (data secrecy, preventing unauthorized reading), integrity (detecting any modification of data during transit), and data authenticity (verifying the origin of the data). Beyond these cryptographic guarantees, practical secure channels also need to support protocol multiplexing (allowing multiple higher-level protocols to use the same channel) and robust alert communication (notifying higher layers when security issues arise). To illustrate these concepts, Demeester employs the classic Alice, Bob, and Eve model, where Alice and Bob are legitimate communicators, and Eve is the omnipresent adversary.
To formally define "secure," Demeester introduces a series of "mind games" or simplified models. For confidentiality, an adversary (Eve) attempts to distinguish between encryptions of two chosen messages (m0 and m1). If Eve's chance of guessing which message was encrypted is no better than 1/2 (random guessing), the scheme provides confidentiality. A critical insight here is that deterministic encryption fails when keys are reused, as identical plaintexts would always produce identical ciphertexts, allowing Eve to easily distinguish. For authenticity and integrity, the models extend to include an oracle that can perform arbitrary decryptions, with restrictions. The goal for Eve becomes forging a valid ciphertext that Bob accepts as authentic, or making changes to a ciphertext that Bob cannot detect. The ability of the receiving party to detect invalid ciphertexts is central to integrity. Finally, the talk also touches upon the need for stateful channels to ensure the correct order of messages, addressing potential reordering attacks often handled by lower-layer protocols like TCP.
Key Findings
▶ Watch: Formal definition of data confidentiality (10:00)
Sander Demeester's talk distills the complex process of building secure channels into several critical findings, highlighting best practices and common pitfalls in real-world cryptographic system design:
- Multi-Phase Construction: Secure channels are not monolithic but rather constructed in distinct phases: Key Establishment (agreeing on shared secrets), Key Derivation (generating multiple keys from the initial shared secret), and Data Protection (encrypting and authenticating actual messages). Each phase requires careful cryptographic design.
- Authenticated Key Exchange (AKE) is Paramount: The initial key exchange must inherently include authentication of the communicating parties. It's not enough to simply establish a shared secret; both parties must be assured of the other's identity. This is often achieved by combining key exchange mechanisms (like Diffie-Hellman or RSA) with digital signatures or certificates.
- Perfect Forward Secrecy (PFS) is Essential: A robust secure channel must guarantee Perfect Forward Secrecy. This means that even if a long-term private key is compromised in the future, past session keys and the confidentiality of past communications remain protected. PFS is achieved by using ephemeral, short-term session keys for encryption, which are then authenticated by long-term keys. The long-term key authenticates the ephemeral exchange but does not contribute to the session key's entropy.
- One Shared Secret is Insufficient: The initial AKE typically yields a single shared secret. However, a secure channel requires multiple keys (e.g., separate encryption and MAC keys for each direction, and potentially for different purposes). Robust Key Derivation Functions (KDFs) like HKDF (used in TLS 1.3) are crucial for securely expanding this single secret into a suite of necessary cryptographic keys.
- Authenticated Encryption (AEAD) is the Gold Standard: Simple encryption modes like CTR or CBC only provide confidentiality and are vulnerable to integrity attacks. Relying on separate MACs introduces complexity and potential vulnerabilities if not implemented correctly. The "Encrypt-then-MAC" paradigm is critical: always verify the MAC before decrypting or processing any part of the ciphertext. The modern solution is Authenticated Encryption with Associated Data (AEAD) schemes (e.g., GCM, OCB, CCM), which provide confidentiality and integrity in a single cryptographic primitive, often allowing for additional authenticated but unencrypted data (AD).
- Design Choices Have Profound Security Implications: The talk vividly illustrates how seemingly minor design decisions in protocol architecture can lead to significant vulnerabilities. The SSHv2 CBC plaintext recovery attack serves as a prime example, stemming from SSH's "MAC-then-Encrypt" approach and its reliance on decrypting the length field before MAC verification. This contrasts sharply with TLS 1.3's design, which uniformly adopts AEAD and avoids such pitfalls.
Technical Deep Dive
▶ Watch: Explaining Perfect Forward Secrecy (PFS) (31:00)
The construction of a secure channel is broken down into three fundamental phases: Key Establishment, Key Derivation, and Data Protection.
Phase 1: Key Establishment Protocol (Authenticated Key Exchange - AKE)
The initial step involves establishing a shared secret key between communicating parties (Alice and Bob) over an untrusted network. This is achieved through an Authenticated Key Exchange (AKE) protocol. Two primary methods are discussed:
- Key Creation (e.g., Diffie-Hellman): Both parties contribute ephemeral (short-lived) values to a mathematical exchange, from which they can independently compute a shared secret. This is a common choice for Perfect Forward Secrecy (PFS).
- Key Transport (e.g., RSA): One party generates a secret and encrypts it using the other party's public key. The recipient then uses their private key to decrypt and recover the secret. This was common in older TLS versions but generally does not provide PFS on its own.
Crucially, the key exchange must be authenticated. This means the identities of the parties exchanging keys must be verified, often through digital certificates signed by a Certificate Authority (CA). The speaker emphasizes that key exchange and authentication are often inseparable.
Perfect Forward Secrecy (PFS): PFS is a critical property ensuring that even if a long-term private key (e.g., a server's RSA key from a certificate) is compromised in the future, any session keys derived from past communications remain secure. This is achieved by generating short-term (ephemeral) keys (e.g., Diffie-Hellman parameters) for each session. These ephemeral values are then signed or authenticated using the long-term key. The session key itself is derived only from the ephemeral values, meaning the long-term key's compromise does not allow an adversary to decrypt past session data.
Phase 2: Key Derivation
A single shared secret from the AKE is rarely sufficient. Secure channels typically require multiple keys for different cryptographic operations (e.g., separate encryption and Message Authentication Code (MAC) keys for each direction of communication, IVs, etc.). Key Derivation Functions (KDFs) are used to expand this initial shared secret into a set of cryptographically strong session keys.
- TLS 1.3: Employs HKDF (HMAC-based Key Derivation Function, specified in RFC 5869). HKDF is a robust KDF that can extract a fixed-length pseudorandom key from a non-uniformly distributed input keying material, and then expand it into multiple cryptographically strong output keys.
- SSHv2: Uses a simpler approach, concatenating the derived key (K) with a hash (H), a label, and an ID, then hashing the result to derive additional keys. While simpler, it's less formally analyzed than HKDF.
Phase 3: Data Protection
This phase focuses on the actual encryption and authentication of application data.
- Symmetric Encryption Modes of Operation:
- CTR (Counter Mode): Transforms a block cipher (e.g., AES) into a stream cipher. A unique Initialization Vector (IV) and a counter are encrypted under the session key, and the resulting keystream is XORed with the plaintext to produce ciphertext. CTR provides confidentiality but no inherent integrity or authenticity.
- CBC (Cipher Block Chaining): Each plaintext block is XORed with the previous ciphertext block (or an IV for the first block) before encryption. This chaining ensures that identical plaintext blocks encrypt to different ciphertext blocks, providing a form of randomization. Like CTR, CBC provides confidentiality but no inherent integrity or authenticity.
- Message Authentication Codes (MACs): To add integrity and authenticity, MACs are used. A MAC function
S(key, message) -> taggenerates a tag for a message using a shared secret key. A verification functionV(key, message, tag) -> 1/0checks if the tag is valid for the given message and key. HMAC (Hash-based MAC) is a common construction.
- The "Doom" Principle (Moxie Marlinspike): A critical security principle states: "If you have to perform any type of cryptographic operation on the ciphertext before you verify it or validate the MAC, it will lead to doom." This means the MAC must be verified before any decryption or processing of the ciphertext. This prevents padding oracle attacks and other vulnerabilities arising from an attacker being able to infer information based on error messages produced during decryption before authentication. This principle underpins the Encrypt-then-MAC paradigm (encrypt data, then MAC the ciphertext) as superior to MAC-then-Encrypt (MAC the plaintext, then encrypt both).
- Authenticated Encryption (AE) and AEAD: To simplify and secure data protection, Authenticated Encryption (AE) modes were developed, combining confidentiality and integrity into a single primitive. Decryption of an AE ciphertext either yields the plaintext or an explicit error indicating tampering. Authenticated Encryption with Associated Data (AEAD) extends AE by allowing additional data (AD) to be authenticated but not encrypted. This is useful for protocol headers or other metadata that needs integrity protection but doesn't require confidentiality. Common AEAD modes include GCM (Galois/Counter Mode), OCB (Offset Codebook Mode), and CCM (Counter with CBC-MAC Mode).
Real-World Protocol Implementations
The talk contrasts two prominent secure channel implementations:
- TLS 1.3: Designed with modern cryptographic principles in mind.
- Comprises the TLS Handshake Protocol (for AKE and key derivation using HKDF) and the TLS Record Protocol (for data protection).
- All record messages are protected using AEAD schemes (e.g., GCM), ensuring both confidentiality and integrity in a single step.
- The "additional data" (AD) field in TLS 1.3 AEAD is always zero, meaning the entire application data payload is encrypted and authenticated.
- Supports multiplexing of handshake messages, application data, and alerts.
- SSHv2: A multi-layered architecture, with its secure channel functionality primarily residing in the Transport Layer and its Binary Packet Protocol.
- The Binary Packet Protocol defines a packet format including sequence number, length field, padding length, payload, and padding.
- A critical design choice in SSHv2 is that the MAC is computed on the plaintext (specifically, the sequence number, length, padding length, payload, and padding) before encryption. This is a MAC-then-Encrypt approach.
- Uses CBC mode with a "chained IV," where the IV for the next message is derived from the last ciphertext block of the previous message. This design choice, coupled with MAC-then-Encrypt, makes SSHv2 vulnerable to certain attacks.
Demo / Proof of Concept
▶ Watch: Authenticated Encryption (AEAD) and safe MAC usage (46:00)
The talk features a concrete plaintext recovery attack against SSHv2 using CBC mode, highlighting a critical vulnerability arising from the protocol's design choices.
The Vulnerability:
SSHv2's design involves computing the MAC on the plaintext data, then encrypting the entire packet (including the MAC). Crucially, when the SSH server receives an encrypted packet, it first attempts to decrypt the initial part of the packet to extract the length field. This length field dictates how many subsequent blocks the server expects to receive before it can perform the MAC verification. This is a classic example of violating Moxie Marlinspike's "doom" principle: cryptographic operations (decryption of the length field) are performed before the message's authenticity is verified.
The Attack Steps:
- Attacker Sends a Modified First Block: The attacker sends a crafted first block of ciphertext to the SSH server. Since the server decrypts this block before MAC verification, the attacker can manipulate the decrypted content.
- Server Decrypts Length Field: The server decrypts the first 32 bits (4 bytes) of this block, interpreting them as the plaintext length of the entire packet. Because the attacker controls the ciphertext, they can influence this "decrypted" length value.
- Attacker Sends Subsequent Random Blocks: Based on the (potentially garbage) length value extracted by the server, the attacker then sends a series of random 16-byte blocks.
- MAC Error Reveals Length: The attacker continues sending random blocks until the SSH server registers a MAC error. This MAC error is triggered when the server has received the number of blocks indicated by the previously decrypted length field, attempts to decrypt the entire message, and then fails the MAC verification.
- Inferring Original Plaintext Length: The fact that a MAC error was generated at a specific point (after N random blocks) tells the attacker precisely what length the server believed the packet should have been. This effectively reveals the plaintext value of the first four bytes of the original, legitimate message (because the attacker knows the IV used and the random blocks sent).
- Plaintext Recovery via CBC Algebra: Using the algebraic properties of CBC mode, specifically how XOR operations chain within the decryption process, this knowledge (the inferred length) can be leveraged. By carefully manipulating the IV and ciphertext blocks, the attacker can use the server as an oracle to recover the first four bytes of any CBC-encrypted block. This is done by essentially creating a "test" block, observing if the MAC error is triggered at a specific length, and iteratively guessing the underlying plaintext bytes.
This attack, originally discovered by researchers at Royal Holloway, demonstrates a critical vulnerability stemming from SSHv2's MAC-then-Encrypt approach combined with early decryption of protocol metadata (the length field). It underscores why AEAD modes and strict Encrypt-then-MAC discipline are paramount in modern cryptographic protocol design.
Defensive Implications
▶ Watch: SSHv2 CBC plaintext recovery attack (56:00)
The detailed exploration of secure channel construction and the SSH CBC attack provide several crucial defensive implications for developers, system administrators, and security professionals:
- Prioritize Authenticated Encryption with Associated Data (AEAD): Always use AEAD modes like GCM, OCB, or CCM for data protection. These modes intrinsically provide both confidentiality and integrity in a single, robust primitive, eliminating the complexities and vulnerabilities associated with separate encryption and MAC schemes. TLS 1.3's universal adoption of AEAD is a prime example of best practice.
- Adhere to the "Encrypt-then-MAC" Principle (or use AEAD): If AEAD is not directly available, implement the "Encrypt-then-MAC" paradigm: encrypt the data, then compute a MAC over the ciphertext. Crucially, the MAC must be verified before any decryption or processing of the ciphertext takes place. This prevents a wide range of oracle attacks, as demonstrated by the SSH CBC vulnerability where decryption of the length field occurred prior to MAC validation.
- Implement Perfect Forward Secrecy (PFS): Ensure that key exchange protocols (e.g., Diffie-Hellman) are configured to use ephemeral (short-lived) session keys for data encryption, authenticated by long-term keys (e.g., server certificates). This protects the confidentiality of past communications even if long-term secret keys are compromised in the future.
- Utilize Robust Key Derivation Functions (KDFs): Never generate multiple keys directly from a single shared secret without a proper KDF. Use strong, cryptographically vetted KDFs like HKDF to derive all necessary session keys (for encryption, MACs, IVs, etc.) from the initial shared secret in a secure and unpredictable manner.
- Be Wary of Custom Cryptographic Constructions: Custom designs for secure channels or cryptographic operations are highly prone to errors and subtle vulnerabilities. Whenever possible, rely on well-vetted, standardized protocols and cryptographic libraries that implement established best practices.
- Ensure Stateful Channel Management: Protocols should properly manage session state to prevent replay attacks and ensure the correct ordering of messages. While transport layers like TCP often handle ordering, the secure channel layer should have mechanisms (e.g., sequence numbers) to detect and reject out-of-order or replayed messages.
- Stay Updated and Patch Systems: The SSH CBC attack highlights that even widely used protocols can harbor vulnerabilities due to design flaws. Regularly update cryptographic libraries and protocols to their latest, most secure versions (e.g., migrating from older TLS versions to TLS 1.3) to benefit from improved security designs and patched vulnerabilities.
- Avoid Deterministic Encryption: Always use randomized IVs or nonces with encryption modes to ensure that identical plaintexts encrypt to different ciphertexts. This prevents adversaries from easily distinguishing between encrypted messages, a basic requirement for confidentiality.
Key Takeaways
- Secure channels are fundamental for secure communication, demanding robust implementations of confidentiality, integrity, and authenticity over untrusted networks.
- Modern secure channel design relies heavily on three pillars: Authenticated Key Exchange (AKE) for establishing shared secrets and verifying identities, Perfect Forward Secrecy (PFS) to protect past communications against future key compromises, and Authenticated Encryption with Associated Data (AEAD) for combined, robust data protection.
- The principle of **verifying message authenticity before any decryption or processing** is paramount. Violating this (e.g., MAC-then-Encrypt with early decryption) can lead to critical vulnerabilities like plaintext recovery attacks, as demonstrated by the SSH CBC exploit.
- Key derivation functions (KDFs) like HKDF are essential for securely expanding a single shared secret into the multiple distinct keys required for various cryptographic operations within a secure channel.
- Protocol design choices have profound security implications. The contrast between TLS 1.3 (favoring AEAD and robust key derivation) and SSHv2 (with its MAC-then-Encrypt and early decryption of metadata) vividly illustrates how subtle decisions can introduce significant weaknesses.
- Always prefer standardized, well-analyzed cryptographic primitives and protocols over custom implementations, and ensure systems are regularly updated to benefit from the latest security improvements and patched vulnerabilities.
About the Speaker(s)
Sander Demeester is a security expert with a focus on cryptographic systems and secure channel construction. His presentation at BruCON demonstrates a deep understanding of both the theoretical foundations and practical challenges in building real-world secure communication protocols.