REALITY's TLS 1.3 subset
Source files: 11 · checked against Etemenanki 2f00a88
Etemenanki/reality/src/tls13/mod.rsEtemenanki/reality/src/tls13/record.rsEtemenanki/reality/src/tls13/schedule.rsEtemenanki/reality/src/tls13/messages.rsEtemenanki/reality/src/tls13/session.rsEtemenanki/reality/src/codec.rsEtemenanki/reality/tests/unit/tls13/rfc8448.rsEtemenanki/reality/tests/unit/tls13/record.rsEtemenanki/reality/tests/unit/tls13/schedule.rsEtemenanki/reality/tests/unit/tls13/messages.rsEtemenanki/reality/tests/unit/codec.rs
etemenanki-reality carries its own TLS 1.3 (RFC 8446) because REALITY must replay dest’s ServerHello and pad every record of its flight to dest’s lengths, which no stock stack does. The subset is small: one full handshake, the three TLS 1.3 cipher suites, X25519 and X25519MLKEM768, Ed25519, no resumption. See the overview for the scope.
This page covers the pieces under reality/src/tls13/ and the encoding helpers in reality/src/codec.rs. They are all sans-I/O: they take and return bytes. The server and client handshakes on Server and Client put them together.
Responsibilities
Section titled “Responsibilities”| File | Contents |
|---|---|
reality/src/tls13/mod.rs |
Content and handshake type constants, LEGACY_VERSION (0x0303), TLS13 (0x0304), HashAlg, CipherSuite, Fatal |
reality/src/tls13/record.rs |
Record header, plaintext records, Sealer and Opener (AEAD protection through OpenSSL EVP, padding) |
reality/src/tls13/schedule.rs |
Transcript, HashValue, Secret (HKDF-Expand-Label, Derive-Secret, Finished MAC, traffic keys, KeyUpdate), TrafficKeys, early_secret, handshake_secret, master_secret |
reality/src/tls13/messages.rs |
ClientHello and its record reader, ServerHello, builders for the server’s messages, MessageReader, parsers for the client’s side |
reality/src/tls13/session.rs |
Session: an established connection’s read and write keys and their KeyUpdate steps |
reality/src/codec.rs |
Reader and put_vec: bounds-checked reading and writing of TLS’s length-prefixed encodings |
Key types
Section titled “Key types”Suites, hashes and errors
Section titled “Suites, hashes and errors”pub(crate) enum HashAlg { Sha256, Sha384 } // len(): 32 or 48
pub(crate) enum CipherSuite { Aes128GcmSha256, // 0x1301, key 16 bytes, SHA-256 Aes256GcmSha384, // 0x1302, key 32 bytes, SHA-384 Chacha20Poly1305Sha256, // 0x1303, key 32 bytes, SHA-256}impl CipherSuite { pub(crate) fn from_id(id: u16) -> Option<Self>; pub(crate) fn cipher(self) -> &'static CipherRef; // OpenSSL's AEAD}
pub(crate) const IV_LEN: usize = 12;pub(crate) const TAG_LEN: usize = 16;
pub(crate) enum Fatal { UnexpectedMessage, BadRecordMac, RecordOverflow, IllegalParameter, DecodeError, DecryptError, InternalError,}Fatal names why a TLS exchange cannot go on, after the alert RFC 8446 §6.2 assigns to the condition. It prints as REALITY TLS: followed by the alert’s name (unexpected message, bad record mac, record overflow, illegal parameter, decode error, decrypt error, internal error), becomes an io::Error of kind InvalidData, and every OpenSSL error stack maps to InternalError. The crate sends no alert for a Fatal: the connection ends with the error. The only alert it ever writes is close_notify.
Records
Section titled “Records”pub(crate) const HEADER_LEN: usize = 5;pub(crate) const MAX_PLAINTEXT: usize = 1 << 14; // 16384pub(crate) const MAX_INNER_PLAINTEXT: usize = MAX_PLAINTEXT + 1; // content, type byte, paddingpub(crate) const MAX_CIPHERTEXT: usize = MAX_PLAINTEXT + 256; // 16640pub(crate) const MAX_RECORD: usize = HEADER_LEN + MAX_CIPHERTEXT;
pub(crate) struct Header { pub(crate) content_type: u8, pub(crate) version: u16, pub(crate) len: usize }
pub(crate) fn write_plaintext(content_type: u8, payload: &[u8], out: &mut Vec<u8>) -> Result<(), Fatal>;
pub(crate) struct Sealer(/* Protection */);impl Sealer { pub(crate) fn new(keys: &TrafficKeys) -> Result<Self, Fatal>; pub(crate) fn seal(&mut self, content_type: u8, content: &[u8], out: &mut Vec<u8>) -> Result<(), Fatal>; pub(crate) fn seal_padded(&mut self, content_type: u8, content: &[u8], inner_len: usize, out: &mut Vec<u8>) -> Result<(), Fatal>;}
pub(crate) struct Opener(/* Protection */);impl Opener { pub(crate) fn new(keys: &TrafficKeys) -> Result<Self, Fatal>; pub(crate) fn open(&mut self, record: &mut [u8]) -> Result<(u8, Range<usize>), Fatal>;}write_plaintext frames an unprotected record (the ServerHello, the ClientHello, a ChangeCipherSpec) with the legacy version 0x0303. It refuses an empty payload or one over 16384 bytes.
Each direction keeps one OpenSSL CipherCtx, initialised with the key once and re-keyed only by its nonce for each record. The nonce is the IV XOR the 64-bit sequence number, right-aligned (RFC 8446 §5.3). The sequence number never wraps: once it reaches u64::MAX, the next record fails with InternalError. The AEAD is OpenSSL’s on purpose: every byte of an authenticated connection crosses it, and OpenSSL’s AES-GCM is several times faster than the pure-Rust one on the same core.
Sealing. A protected record’s outer type is always application data (23) with version 0x0303. seal writes content, the real content type and no padding. seal_padded zero-pads the TLSInnerPlaintext to inner_len, so the record on the wire is 5 + inner_len + 16 bytes; REALITY uses it to give each message of its flight the length of dest’s record. inner_len must be greater than the content length (room for the type byte) and at most 16385, otherwise InternalError. The header is the associated data. A failed seal truncates out back to where it started.
Opening. open takes exactly one record, header included, and decrypts it in place. It checks, in order:
| Check | Fails with |
|---|---|
| A five-byte header is there | DecodeError |
| The outer type is application data | UnexpectedMessage |
The version is 0x0303 |
IllegalParameter |
| The slice is exactly the record the header announces | DecodeError |
| The body is at most 16640 bytes | RecordOverflow |
| The body holds at least a tag | BadRecordMac |
| The tag authenticates | BadRecordMac |
| The inner plaintext is at most 16385 bytes | RecordOverflow |
| A non-zero byte exists (the content type) | UnexpectedMessage |
The content type is the last non-zero byte; the zeros after it are padding and are dropped. open returns the type and where the content now lies in the record.
Key schedule
Section titled “Key schedule”pub(crate) enum Transcript { Sha256(Sha256), Sha384(Sha384) }impl Transcript { pub(crate) fn new(hash: HashAlg) -> Self; pub(crate) fn update(&mut self, message: &[u8]); pub(crate) fn current(&self) -> HashValue; // the hash so far; the transcript carries on}
pub(crate) struct Secret { /* hash, bytes: [u8; 48] */ }impl Secret { pub(crate) fn expand_label(&self, label: &[u8], context: &[u8], out: &mut [u8]) -> Result<(), Fatal>; pub(crate) fn derive(&self, label: &[u8], messages: &HashValue) -> Result<Self, Fatal>; pub(crate) fn next_generation(&self) -> Result<Self, Fatal>; // "traffic upd" pub(crate) fn finished(&self, transcript: &HashValue) -> Result<HashValue, Fatal>; pub(crate) fn verify_finished(&self, transcript: &HashValue, received: &[u8]) -> bool; pub(crate) fn traffic_keys(&self, suite: CipherSuite) -> Result<TrafficKeys, Fatal>;}
pub(crate) fn early_secret(hash: HashAlg) -> Secret; // HKDF-Extract(0, 0)pub(crate) fn handshake_secret(hash: HashAlg, shared: &[u8]) -> Result<Secret, Fatal>;pub(crate) fn master_secret(handshake: &Secret) -> Result<Secret, Fatal>;The schedule is RFC 8446 §7.1 without PSKs. expand_label builds the HkdfLabel with the tls13 prefix. derive is Derive-Secret given the messages’ hash. handshake_secret extracts the key exchange’s shared secret under Derive-Secret(early, derived, empty hash); master_secret extracts zeros under Derive-Secret(handshake, derived, empty hash). The handshakes then derive c hs traffic, s hs traffic, c ap traffic and s ap traffic.
finished is the Finished verify_data: HMAC over the transcript hash under the finished key expanded from a handshake traffic secret (RFC 8446 §4.4.4). verify_finished compares a peer’s value in constant time. traffic_keys expands key (16 or 32 bytes by suite) and iv (12 bytes). next_generation is the KeyUpdate step of RFC 8446 §7.2.
HKDF, HMAC and the hashes are the workspace’s RustCrypto crates (hkdf, hmac, sha2). They run only during the handshake and on a KeyUpdate; the per-record work is OpenSSL’s.
Handshake messages
Section titled “Handshake messages”The parsers are strict and never panic: anything malformed, or merely outside the subset, comes back as None. On the server that means “not ours, hand it to dest”, so a parser here never has to be more lenient than XTLS, only never less safe.
pub(crate) mod group { pub(crate) const X25519: u16 = 0x001d; pub(crate) const X25519_MLKEM768: u16 = 0x11ec; }pub(crate) const ED25519: u16 = 0x0807;pub(crate) const MAX_CLIENT_HELLO: usize = 1 << 16;
pub(crate) struct ClientHello { /* raw bytes, session_id range, suites, SNI range, key shares, supports_tls13 */ }impl ClientHello { pub(crate) fn parse(raw: Vec<u8>) -> Option<Self>; pub(crate) fn raw(&self) -> &[u8]; pub(crate) fn random(&self) -> Option<&[u8; 32]>; pub(crate) fn session_id(&self) -> &[u8]; pub(crate) fn session_id_range(&self) -> Range<usize>; pub(crate) fn server_name(&self) -> Option<&[u8]>; pub(crate) fn key_shares(&self) -> &[KeyShare]; pub(crate) fn key_share_for(&self, group: u16) -> Option<&[u8]>; pub(crate) fn supports_tls13(&self) -> bool;}
pub(crate) struct ClientHelloReader { /* handshake bytes so far, record bytes consumed */ }pub(crate) enum HelloProgress { NeedMore, Done { hello: ClientHello, consumed: usize }, Invalid }
pub(crate) struct ServerHello { /* raw bytes, suite, group, key share range */ }impl ServerHello { pub(crate) fn parse(raw: Vec<u8>) -> Option<Self>; pub(crate) fn set_key_share(&mut self, share: &[u8]) -> Result<(), Fatal>;}
pub(crate) struct MessageReader { /* buffer, max_message */ }ClientHello
Section titled “ClientHello”ClientHello::parse takes one complete message, header included, and keeps it byte for byte: the transcript hashes those bytes and REALITY authenticates them. It records the offsets of the session_id, the SNI host name and every key share, so the server can read them and the client can seal its session_id in place. It refuses:
- a type other than ClientHello, or a length that does not match the body;
- a session_id over 32 bytes;
- an empty or odd-length cipher suite list;
- compression methods other than exactly the null method;
- bytes after the extensions;
- a repeated extension;
- a
server_namewith an empty list, a second host name (Go refuses one), an empty host name or one with a trailing dot; other name types are skipped; - an empty
supported_versionslist, or bytes after it; - an empty key share, or bytes after the key share list;
- a
pre_shared_keythat is not the last extension (RFC 8446 §4.2.11).
legacy_version is read and not checked: TLS 1.3 negotiates in supported_versions. A hello without 0x0304 in that list parses, and supports_tls13() says so. Key shares keep their order, duplicates included; key_share_for returns the first of a group.
ClientHelloReader::advance gathers a ClientHello from the first records a client sends. The caller passes everything received so far; the reader consumes whole records and keeps only the handshake bytes. It returns Invalid for a record that is not a handshake record, whose version’s major byte is not 0x03, that is empty or longer than 16384 bytes (Go’s “does not look like a TLS handshake” check plus RFC 8446’s limits), for a first message that is not a ClientHello or announces more than 64 KiB (Go’s maxHandshake), and for a record that carries bytes past the end of the hello. Done reports how many input bytes the hello’s records took.
ServerHello
Section titled “ServerHello”ServerHello::parse passes only a TLS 1.3 ServerHello that REALITY can mirror: legacy version 0x0303, a random that is not the HelloRetryRequest value, a session_id of at most 32 bytes, one of the three suites, null compression, and extensions limited to one supported_versions (which must say 0x0304) and one key_share whose length matches its group (32 bytes for X25519, 1120 for X25519MLKEM768). Any other extension, a PSK, a repeat, a trailing byte or a missing extension fails it. set_key_share replaces the key share bytes in place, keeping their length: that is all REALITY changes in dest’s ServerHello.
Builders
Section titled “Builders”| Function | Message |
|---|---|
encrypted_extensions(server_name_ack) |
EncryptedExtensions as XTLS’s server sends it: no ALPN, and an empty server_name extension when the client sent an SNI |
certificate(der) |
Certificate with an empty request context, one entry and no extensions |
certificate_verify(scheme, signature) |
CertificateVerify |
server_signed_content(transcript) |
What a server’s CertificateVerify signs (RFC 8446 §4.4.3) |
finished(verify_data) |
Finished |
key_update(update_requested) |
KeyUpdate |
Reading handshake messages
Section titled “Reading handshake messages”MessageReader reassembles handshake messages from the content of handshake records, which may split a message or carry several. Its max_message bounds one message body and so the buffer; a longer announced message fails with UnexpectedMessage. is_empty tells whether a record boundary may fall here, which the Finished and KeyUpdate checks use.
The client’s side reads the server’s flight with:
| Parser | Accepts | Refuses with |
|---|---|---|
parse_encrypted_extensions |
Well-formed, unrepeated extensions; an ALPN extension naming exactly one non-empty protocol; an empty server_name |
DecodeError, IllegalParameter for a repeat |
parse_certificate |
An empty request context and at least one non-empty entry; per-entry extensions are skipped | DecodeError |
parse_certificate_verify |
A scheme and a non-empty signature, nothing after | DecodeError |
parse_finished |
Exactly Hash.length bytes |
DecodeError |
parse_key_update |
One byte, 0 or 1 |
IllegalParameter for another byte, DecodeError for another length |
Session
Section titled “Session”pub(crate) struct Session { read_secret: Secret, opener: Opener, write_secret: Secret, sealer: Sealer }impl Session { pub(crate) fn update_read(&mut self) -> Result<(), Fatal>; // after the peer's KeyUpdate pub(crate) fn update_write(&mut self) -> Result<(), Fatal>; // after sending a KeyUpdate}A Session holds an established connection’s application traffic secrets and the Opener and Sealer built from them. Each update moves one side to the next generation of its secret and builds a fresh Opener or Sealer from it. RealityStream owns the session; see Server.
codec.rs
Section titled “codec.rs”pub(crate) struct Reader<'a> { bytes: &'a [u8], base: usize }impl<'a> Reader<'a> { pub(crate) fn new(bytes: &'a [u8]) -> Self; pub(crate) fn position(&self) -> usize; // offset in the outermost buffer pub(crate) fn take(&mut self, n: usize) -> Option<&'a [u8]>; pub(crate) fn sub(&mut self, n: usize) -> Option<Self>; pub(crate) fn u8(&mut self) -> Option<u8>; pub(crate) fn u16(&mut self) -> Option<u16>; pub(crate) fn u24(&mut self) -> Option<usize>; pub(crate) fn vec8(&mut self) -> Option<Self>; // one-byte length prefix pub(crate) fn vec16(&mut self) -> Option<Self>; pub(crate) fn vec24(&mut self) -> Option<Self>;}
pub(crate) fn put_vec(out: &mut Vec<u8>, width: usize, body: impl FnOnce(&mut Vec<u8>) -> Result<(), Fatal>) -> Result<(), Fatal>;Reader reads big-endian integers and length-prefixed vectors. Every read returns None past the end instead of panicking; take and the integer reads consume nothing when they fail. A sub-reader remembers where it starts in the outermost buffer, so a parser can record the offset of a field it may later rewrite in place: the session_id the client seals, the key share the server replaces. put_vec reserves a length prefix of 1, 2 or 3 bytes, lets body write the vector, then fills the prefix; a body too long for its prefix fails with InternalError.
Data flow
Section titled “Data flow”The handshake’s secrets, as both handshakes use them:
flowchart TB es["early_secret: Extract(0, 0)"] --> hs["handshake_secret: Extract(derived, shared secret)"] hs --> chs["c hs traffic"] hs --> shs["s hs traffic"] hs --> ms["master_secret: Extract(derived, 0)"] ms --> cap["c ap traffic"] ms --> sap["s ap traffic"] chs --> keys1["handshake keys and the Finished MACs"] shs --> keys1 cap --> sess["Session (KeyUpdate: traffic upd)"] sap --> sess
c hs traffic and s hs traffic are derived over the transcript through the ServerHello; the application secrets over the transcript through the server’s Finished.
Invariants
Section titled “Invariants”- No parser panics on any input, and no parser leaves half a state: it returns a value or
None(or aFatal). - A ClientHello and a ServerHello are kept byte for byte; only the session_id (client) and the key share (server) are ever rewritten, in place and at their original length.
- A sealed record’s length is exactly what the caller asked for, so a flight can match dest’s record sizes.
- A sequence number never wraps; secrets and keys are wiped on drop and redacted in
Debug. - Finished values are compared in constant time.
Limits
Section titled “Limits”| Limit | Value | Where |
|---|---|---|
| Record content | 16384 bytes | MAX_PLAINTEXT |
| Inner plaintext | 16385 bytes | MAX_INNER_PLAINTEXT |
| Record body | 16640 bytes | MAX_CIPHERTEXT |
| ClientHello body | 64 KiB | MAX_CLIENT_HELLO |
| ClientHello record fragment | 1 to 16384 bytes | ClientHelloReader::advance |
| session_id | 32 bytes | ClientHello::parse, ServerHello::parse |
| Handshake message | The caller’s max_message |
MessageReader |
| File | Covers |
|---|---|
reality/tests/unit/tls13/rfc8448.rs |
The RFC 8448 simple 1-RTT handshake as hex vectors, shared by the other test files. |
reality/tests/unit/tls13/schedule.rs |
Every secret, traffic key and Finished MAC of RFC 8448, a wrong Finished refused, SHA-384 expansion and ChaCha20 keys against OpenSSL’s own HKDF (RFC 8448 has no SHA-384 or ChaCha20 handshake), the KeyUpdate step, Debug output. |
reality/tests/unit/tls13/record.rs |
RFC 8448’s protected records in sequence, out-of-sequence and tampered records refused, framing errors refused before decryption, padding added and stripped, padding bounds, all-zero and over-long inner plaintexts, the sequence number never wrapping, every suite against OpenSSL’s one-shot AEAD, plaintext records framed as TLS 1.2. |
reality/tests/unit/tls13/messages.rs |
The RFC 8448 ClientHello and ServerHello, offsets into the hello, key-share order and duplicates, server names following Go, one case per refusal, every truncation of a ClientHello and 20,000 random mutations each of a ClientHello and a ServerHello without a panic, the record reader whole, byte by byte and split over records, the builders against Go’s output and RFC 8448, the message reader. |
reality/tests/unit/codec.rs |
Integer and vector reads with positions, reads past the end, length-prefixed writes, a body too long for its prefix. |