跳转到内容

REALITY 的 TLS 1.3 子集

源码文件:11 个 · 核对版本 Etemenanki 2f00a88
  • Etemenanki/reality/src/tls13/mod.rs
  • Etemenanki/reality/src/tls13/record.rs
  • Etemenanki/reality/src/tls13/schedule.rs
  • Etemenanki/reality/src/tls13/messages.rs
  • Etemenanki/reality/src/tls13/session.rs
  • Etemenanki/reality/src/codec.rs
  • Etemenanki/reality/tests/unit/tls13/rfc8448.rs
  • Etemenanki/reality/tests/unit/tls13/record.rs
  • Etemenanki/reality/tests/unit/tls13/schedule.rs
  • Etemenanki/reality/tests/unit/tls13/messages.rs
  • Etemenanki/reality/tests/unit/codec.rs

etemenanki-reality 自带一份 TLS 1.3(RFC 8446),因为 REALITY 必须重放 dest 的 ServerHello,并把 flight(服务端发出的那组握手消息)的每条记录填充到 dest 的长度,现成的实现都做不到。这个子集很小:一次完整握手、三个 TLS 1.3 密码套件、X25519 和 X25519MLKEM768、Ed25519、没有会话恢复。范围见 概述。

本页介绍 reality/src/tls13/ 下的各部分,以及 reality/src/codec.rs 中的编码辅助函数。它们都是 sans-I/O 的:输入字节,输出字节。服务端 和 客户端 中的握手把它们组合起来。

文件 内容
reality/src/tls13/mod.rs 内容类型和握手类型常量、LEGACY_VERSION(0x0303)、TLS13(0x0304)、HashAlg、CipherSuite、Fatal
reality/src/tls13/record.rs 记录头、明文记录、Sealer 和 Opener(通过 OpenSSL EVP 的 AEAD 保护和填充)
reality/src/tls13/schedule.rs Transcript、HashValue、Secret(HKDF-Expand-Label、Derive-Secret、Finished MAC、流量密钥、KeyUpdate)、TrafficKeys、early_secret、handshake_secret、master_secret
reality/src/tls13/messages.rs ClientHello 及其记录读取器、ServerHello、服务端消息的构建函数、MessageReader、客户端一侧的解析函数
reality/src/tls13/session.rs Session:已建立连接的读写密钥及其 KeyUpdate 步骤
reality/src/codec.rs Reader 和 put_vec:带边界检查地读写 TLS 的长度前缀编码
reality/src/tls13/mod.rs
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 说明 TLS 交换为何无法继续,按 RFC 8446 §6.2 为该情况指定的 alert 命名。它打印为 REALITY TLS: 加上 alert 的名字(unexpected message、bad record mac、record overflow、illegal parameter、decode error、decrypt error、internal error),转换成 kind 为 InvalidData 的 io::Error,任何 OpenSSL 错误栈都映射为 InternalError。crate 不会为 Fatal 发送 alert:连接带着这个错误结束。它唯一会写出的 alert 是 close_notify。

reality/src/tls13/record.rs
pub(crate) const HEADER_LEN: usize = 5;
pub(crate) const MAX_PLAINTEXT: usize = 1 << 14; // 16384
pub(crate) const MAX_INNER_PLAINTEXT: usize = MAX_PLAINTEXT + 1; // content, type byte, padding
pub(crate) const MAX_CIPHERTEXT: usize = MAX_PLAINTEXT + 256; // 16640
pub(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 用旧版本号 0x0303 给未受保护的记录(ServerHello、ClientHello、ChangeCipherSpec)加帧。它拒绝空负载和超过 16384 字节的负载。

每个方向持有一个 OpenSSL CipherCtx,密钥只初始化一次,之后每条记录只用 nonce 重新设置。nonce 是 IV 与右对齐的 64 位序列号做异或(RFC 8446 §5.3)。序列号从不回绕:一旦达到 u64::MAX,下一条记录就以 InternalError 失败。AEAD 有意使用 OpenSSL 的:认证通过的连接的每个字节都要经过它,而在同一个核心上,OpenSSL 的 AES-GCM 比纯 Rust 实现快好几倍。

加密(seal)。 受保护记录的外层类型总是 application data(23),版本为 0x0303。seal 写入 content、真实的内容类型,不加填充。seal_padded 把 TLSInnerPlaintext 用零填充到 inner_len,于是线上的记录长 5 + inner_len + 16 字节;REALITY 用它让自己 flight 中的每条消息与 dest 对应记录的长度相同。inner_len 必须大于内容长度(给类型字节留位置)且不超过 16385,否则返回 InternalError。记录头是附加数据。加密失败时 out 会截回原来的长度。

解密(open)。 open 接收恰好一条记录(含记录头),原地解密。它依次检查:

检查 失败时
有五字节的记录头 DecodeError
外层类型是 application data UnexpectedMessage
版本是 0x0303 IllegalParameter
切片恰好是记录头声明的那条记录 DecodeError
记录体不超过 16640 字节 RecordOverflow
记录体至少能容纳一个 tag BadRecordMac
tag 认证通过 BadRecordMac
内部明文不超过 16385 字节 RecordOverflow
存在非零字节(即内容类型) UnexpectedMessage

内容类型是最后一个非零字节,其后的零是填充,会被去掉。open 返回类型以及内容现在在记录中的位置。

reality/src/tls13/schedule.rs
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>;

密钥调度是不含 PSK 的 RFC 8446 §7.1。expand_label 用 tls13 前缀构造 HkdfLabel。derive 是给定消息哈希时的 Derive-Secret。handshake_secret 在 Derive-Secret(early, derived, 空哈希) 之下提取密钥交换的共享密钥;master_secret 在 Derive-Secret(handshake, derived, 空哈希) 之下提取全零输入。握手随后派生 c hs traffic、s hs traffic、c ap traffic 和 s ap traffic。

finished 是 Finished 的 verify_data:用从握手流量密钥扩展出的 finished 密钥,对 transcript 哈希做 HMAC(RFC 8446 §4.4.4)。verify_finished 以常量时间比较对端的值。traffic_keys 扩展出 key(按套件为 16 或 32 字节)和 iv(12 字节)。next_generation 是 RFC 8446 §7.2 中的 KeyUpdate 步骤。

HKDF、HMAC 和哈希使用 workspace 中的 RustCrypto crate(hkdf、hmac、sha2)。它们只在握手和 KeyUpdate 时运行;每条记录的工作由 OpenSSL 完成。

解析器是严格的,从不 panic:任何格式错误、或仅仅超出这个子集的内容,都返回 None。在服务端这意味着“不是我们的,交给 dest”,所以这里的解析器永远不必比 XTLS 更宽松,只需永远不更不安全。

reality/src/tls13/messages.rs
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::parse 接收一条完整的消息(含消息头),并逐字节保留:transcript 对这些字节做哈希,REALITY 也对它们做认证。它记录 session_id、SNI 主机名和每个 key share 的偏移,以便服务端读取它们、客户端原地封入 session_id。它拒绝:

  • 类型不是 ClientHello,或长度与消息体不符;
  • 超过 32 字节的 session_id;
  • 空的或长度为奇数的密码套件列表;
  • 不恰好是 null 方法的压缩方法;
  • 扩展之后还有字节;
  • 重复的扩展;
  • server_name 列表为空、出现第二个主机名(Go 也拒绝)、主机名为空或以点结尾;其他名字类型会被跳过;
  • 空的 supported_versions 列表,或其后还有字节;
  • 空的 key share,或 key share 列表之后还有字节;
  • 不是最后一个扩展的 pre_shared_key(RFC 8446 §4.2.11)。

legacy_version 会被读取但不检查:TLS 1.3 在 supported_versions 中协商。列表中没有 0x0304 的 hello 也能解析,由 supports_tls13() 说明这一点。key share 保持原顺序,重复的也保留;key_share_for 返回某个组的第一个 share。

ClientHelloReader::advance 从客户端发来的最初几条记录中拼出 ClientHello。调用方传入目前收到的全部内容;读取器按整条记录消费,只保留握手字节。以下情况返回 Invalid:记录不是握手记录、版本的高字节不是 0x03、记录为空或超过 16384 字节(Go 的“看起来不像 TLS 握手”检查加上 RFC 8446 的上限);第一条消息不是 ClientHello 或声明超过 64 KiB(Go 的 maxHandshake);某条记录携带了 hello 结束之后的字节。Done 报告 hello 的记录占用了多少输入字节。

ServerHello::parse 只放行 REALITY 能够模仿的 TLS 1.3 ServerHello:旧版本号 0x0303,random 不是 HelloRetryRequest 的值,session_id 不超过 32 字节,选择三个套件之一,null 压缩,扩展只有一个 supported_versions(必须为 0x0304)和一个长度与其组相符的 key_share(X25519 为 32 字节,X25519MLKEM768 为 1120 字节)。任何其他扩展、PSK、重复、尾随字节或缺少的扩展都会让它失败。set_key_share 原地替换 key share 的字节,长度不变:这就是 REALITY 对 dest 的 ServerHello 所做的全部改动。

函数 消息
encrypted_extensions(server_name_ack) 与 XTLS 的服务端发出的一致的 EncryptedExtensions:没有 ALPN,客户端发了 SNI 时带一个空的 server_name 扩展
certificate(der) Certificate,请求上下文为空,一个条目,没有扩展
certificate_verify(scheme, signature) CertificateVerify
server_signed_content(transcript) 服务端的 CertificateVerify 签名的内容(RFC 8446 §4.4.3)
finished(verify_data) Finished
key_update(update_requested) KeyUpdate

MessageReader 从握手记录的内容中重组握手消息,一条记录可能拆开一条消息,也可能携带多条。它的 max_message 限制单条消息体的大小,从而限制缓冲区;声明更长的消息会以 UnexpectedMessage 失败。is_empty 说明此处是否可以是记录边界,Finished 和 KeyUpdate 的检查会用到它。

客户端一侧用以下函数读取服务端的 flight:

解析函数 接受 拒绝时返回
parse_encrypted_extensions 格式正确、不重复的扩展;只指定一个非空协议的 ALPN 扩展;空的 server_name DecodeError,重复时为 IllegalParameter
parse_certificate 空的请求上下文和至少一个非空条目;跳过每个条目的扩展 DecodeError
parse_certificate_verify 一个签名方案和一个非空签名,其后没有内容 DecodeError
parse_finished 恰好 Hash.length 字节 DecodeError
parse_key_update 一个字节,0 或 1 其他字节值为 IllegalParameter,其他长度为 DecodeError
reality/src/tls13/session.rs
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
}

Session 持有已建立连接的应用流量密钥,以及由它们构建的 Opener 和 Sealer。每次更新把一个方向推进到下一代密钥,并由它构建新的 Opener 或 Sealer。会话由 RealityStream 持有;见 服务端。

reality/src/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 读取大端整数和带长度前缀的向量。每次读取越过末尾时返回 None 而不是 panic;take 和整数读取失败时不消费任何字节。子读取器记住自己在最外层缓冲区中的起点,所以解析器可以记录之后可能原地改写的字段的偏移:客户端封入的 session_id、服务端替换的 key share。put_vec 预留 1、2 或 3 字节的长度前缀,让 body 写入向量,再填好前缀;内容超出前缀能表示的长度时以 InternalError 失败。

两种握手都使用的握手密钥:

flowchart TB
  es["early_secret:Extract(0, 0)"] --> hs["handshake_secret:Extract(derived, 共享密钥)"]
  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["握手密钥和 Finished MAC"]
  shs --> keys1
  cap --> sess["Session(KeyUpdate:traffic upd)"]
  sap --> sess

c hs traffic 和 s hs traffic 基于截至 ServerHello 的 transcript 派生;应用流量密钥基于截至服务端 Finished 的 transcript 派生。

  • 任何输入都不会让解析器 panic,解析器也不会留下半套状态:它返回一个值或 None(或一个 Fatal)。
  • ClientHello 和 ServerHello 都逐字节保留;只有 session_id(客户端)和 key share(服务端)会被改写,而且是原地、按原长度改写。
  • 加密出的记录长度正好是调用方要求的长度,所以 flight 能与 dest 的记录大小一致。
  • 序列号从不回绕;秘密值和密钥在 drop 时清零,在 Debug 中脱敏。
  • Finished 的值以常量时间比较。
限制 值 位置
记录内容 16384 字节 MAX_PLAINTEXT
内部明文 16385 字节 MAX_INNER_PLAINTEXT
记录体 16640 字节 MAX_CIPHERTEXT
ClientHello 消息体 64 KiB MAX_CLIENT_HELLO
ClientHello 的记录片段 1 到 16384 字节 ClientHelloReader::advance
session_id 32 字节 ClientHello::parse、ServerHello::parse
握手消息 调用方给定的 max_message MessageReader
文件 覆盖内容
reality/tests/unit/tls13/rfc8448.rs 以十六进制向量给出的 RFC 8448 简单 1-RTT 握手,供其他测试文件共用。
reality/tests/unit/tls13/schedule.rs RFC 8448 的每个秘密值、流量密钥和 Finished MAC,拒绝错误的 Finished,SHA-384 扩展和 ChaCha20 密钥与 OpenSSL 自己的 HKDF 对照(RFC 8448 没有 SHA-384 或 ChaCha20 的握手),KeyUpdate 步骤,Debug 输出。
reality/tests/unit/tls13/record.rs RFC 8448 中按顺序排列的受保护记录,拒绝乱序和被篡改的记录,在解密前拒绝帧错误,填充的添加和去除,填充的边界,全零和过长的内部明文,序列号从不回绕,每个套件与 OpenSSL 的一次性 AEAD 对照,明文记录按 TLS 1.2 加帧。
reality/tests/unit/tls13/messages.rs RFC 8448 的 ClientHello 和 ServerHello,hello 中的偏移,key share 的顺序和重复,与 Go 一致的服务器名处理,每种拒绝一个用例,ClientHello 的每种截断以及 ClientHello 和 ServerHello 各 20,000 次随机变异都不 panic,记录读取器整条读取、逐字节读取和跨记录读取,构建函数与 Go 的输出和 RFC 8448 对照,消息读取器。
reality/tests/unit/codec.rs 带位置的整数和向量读取,越过末尾的读取,带长度前缀的写入,内容超出前缀能表示的长度。