diff --git a/CHANGELOG.md b/CHANGELOG.md index 1995c44d..ccecb79d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ - Fixed payload loss after fragmented VLESS response headers, WebSocket framing after nonempty Ping frames, and preread-byte loss in ShadowTLS authentication fallback. Added deterministic regressions and handler-level AnyTLS authentication and fallback coverage. - Added server-first TCP half-close and same-name kernel TUN reload coverage, hardened isolated-test selection checks, and enabled macOS process-watcher unit tests. +- Replaced REALITY's custom TLS state machine and record crypto with a pinned `cfal/rustls` fork. Authentication, ML-DSA policy, transparent forwarding and Vision remain in Shoes. Outbound ClientHello now uses rustls's native fingerprint, not Chrome/uTLS emulation; clients still fail closed on non-REALITY certificates. +- REALITY servers preserve admitted target ServerHello bytes except the key share and follow the target's cipher within the configured allowlist. Every synthetic handshake record must fit its target length. Unsupported layouts, cipher conflicts and insufficient capacity forward transparently before synthetic output; targets that previously worked only because Shoes enlarged records may now fail outbound REALITY authentication. - Fixed Naive HTTP/2 writes stalling on already available flow-control credit after a pending write is cancelled and retried with a smaller buffer. The historical sing-box interoperability timeout remains unconfirmed; its test now reports per-stream progress and carrier-forwarder failures. - Switched Mihomo REALITY/TLS 1.2 interoperability coverage to reply-first sequencing while retaining early half-close as an opt-in regression for the pinned peer's full-close limitation. No Shoes TLS errors are suppressed and no peer patch is applied. - Fixed TUN startup resets for queued TCP connections, rejected SYN admission, and stale passive listeners after handshake resets. TUN and WireGuard now defer inbound routing and hostname sniffing until TCP establishment; half-open TUN connections expire after 30 seconds instead of retaining the established-connection timeout. diff --git a/src/crypto/crypto_tls_stream.rs b/src/crypto/crypto_tls_stream.rs index 159d5c0a..59118015 100644 --- a/src/crypto/crypto_tls_stream.rs +++ b/src/crypto/crypto_tls_stream.rs @@ -521,8 +521,7 @@ impl AsyncStream for CryptoTlsStream { #[cfg(test)] mod tests { use super::*; - use crate::address::{Address, NetLocation}; - use crate::reality::{RealityServerConfig, RealityServerConnection}; + use crate::reality::RealityServerConnection; use futures::task::noop_waker_ref; struct PendingWriteIo; @@ -610,20 +609,7 @@ mod tests { impl AsyncStream for ZeroWriteIo {} fn completed_reality_connection() -> RealityServerConnection { - let config = RealityServerConfig { - mldsa65_key: None, - private_key: [0; 32], - short_ids: vec![[0; 8]], - dest: NetLocation::new(Address::UNSPECIFIED, 443), - max_time_diff: None, - min_client_version: None, - max_client_version: None, - cipher_suites: Vec::new(), - }; - RealityServerConnection::new(config) - .unwrap() - .complete_for_test() - .unwrap() + crate::reality::established_pair().1 } #[cfg(target_os = "linux")] @@ -819,14 +805,14 @@ mod tests { let payload = vec![42; 40_000]; for split in [0, 1, 4, 5, 10, 20_000, usize::MAX] { - let mut sender = completed_reality_connection(); + let (mut sender, receiver) = crate::reality::established_pair(); sender.writer().write_all(&payload).unwrap(); let mut ciphertext = Vec::new(); sender.write_tls(&mut ciphertext).unwrap(); let split = split.min(ciphertext.len()); let (io, mut peer) = tokio::io::duplex(65536); peer.write_all(&ciphertext[split..]).await.unwrap(); - let session = CryptoConnection::new_reality_server(completed_reality_connection()); + let session = CryptoConnection::new_reality_server(receiver); let mut stream = CryptoTlsStream::handshake(io, session, TlsReadMode::Stream, &ciphertext[..split]) .await diff --git a/src/reality/common.rs b/src/reality/common.rs index 01538d46..b568d5a9 100644 --- a/src/reality/common.rs +++ b/src/reality/common.rs @@ -1,269 +1,19 @@ -// TLS constants and utilities for REALITY client/server implementations - -use std::io::{self, Error, ErrorKind}; - -// TLS ContentType values -pub const CONTENT_TYPE_CHANGE_CIPHER_SPEC: u8 = 0x14; -pub const CONTENT_TYPE_ALERT: u8 = 0x15; -pub const CONTENT_TYPE_HANDSHAKE: u8 = 0x16; -pub const CONTENT_TYPE_APPLICATION_DATA: u8 = 0x17; - -// TLS alert levels and descriptions -pub const ALERT_LEVEL_WARNING: u8 = 0x01; -pub const ALERT_DESC_CLOSE_NOTIFY: u8 = 0x00; - -// TLS 1.2 version bytes (0x03, 0x03) used in TLS 1.3 record layer for compatibility -pub const VERSION_TLS_1_2_MAJOR: u8 = 0x03; -pub const VERSION_TLS_1_2_MINOR: u8 = 0x03; - -// TLS 1.3 handshake message types -pub const HANDSHAKE_TYPE_SERVER_HELLO: u8 = 2; -pub const HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS: u8 = 8; -pub const HANDSHAKE_TYPE_CERTIFICATE: u8 = 11; -pub const HANDSHAKE_TYPE_CERTIFICATE_VERIFY: u8 = 15; -pub const HANDSHAKE_TYPE_FINISHED: u8 = 20; - -// TLS 1.3 record size limits per RFC 8446 -// -// The TLS record header's `length` field specifies the size of the ENCRYPTED payload. -// Per RFC 8446, the TLS 1.3 limit is stricter than TLS 1.2: -// -// - TLS 1.3: Plaintext limit = 16,384 bytes (2^14) -// Encryption overhead allowance = 256 bytes -// Ciphertext limit = 16,384 + 256 = 16,640 bytes -// -// - TLS 1.2: Plaintext limit = 16,384 bytes (2^14) -// Encryption overhead allowance = 2,048 bytes -// Ciphertext limit = 16,384 + 2,048 = 18,432 bytes -// -// REALITY uses TLS 1.3, so we MUST use the TLS 1.3 limit. Using the larger -// TLS 1.2 limit causes "record overflow" errors in libraries like utls. - -/// Maximum TLS 1.3 ciphertext payload size (16,640 bytes) -pub const MAX_TLS_CIPHERTEXT_LEN: usize = 16384 + 256; - -/// Maximum plaintext payload size for a single TLS 1.3 record -/// -/// RFC 8446 Section 5.1: "The record layer fragments information blocks into -/// TLSPlaintext records carrying data in chunks of 2^14 bytes or less." -/// -/// This is the hard limit enforced by TLS implementations. -/// The 256-byte allowance in MAX_TLS_CIPHERTEXT_LEN is for: -/// - AEAD tag (16 bytes for AES-GCM) -/// - Content type byte (1 byte) -/// - Optional padding (up to 239 bytes) -/// -/// We MUST NOT exceed 16384 bytes of actual plaintext per record, or clients -/// will reject with "record overflow" error. -pub const MAX_TLS_PLAINTEXT_LEN: usize = 16384; - -/// TLS record header size (ContentType + ProtocolVersion + Length) -pub const TLS_RECORD_HEADER_SIZE: usize = 5; - -/// Maximum TLS record size (ciphertext + header) -pub const TLS_MAX_RECORD_SIZE: usize = MAX_TLS_CIPHERTEXT_LEN + TLS_RECORD_HEADER_SIZE; - -pub(crate) fn checked_record_size(payload_len: usize) -> std::io::Result { - if payload_len > MAX_TLS_CIPHERTEXT_LEN { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "TLS record length exceeds maximum", - )); - } - Ok(TLS_RECORD_HEADER_SIZE + payload_len) -} - -/// Buffer capacity for ciphertext read (2x TLS max record for safety) -pub const CIPHERTEXT_READ_BUF_CAPACITY: usize = TLS_MAX_RECORD_SIZE * 2; - -/// Buffer capacity for plaintext read -pub const PLAINTEXT_READ_BUF_CAPACITY: usize = TLS_MAX_RECORD_SIZE * 2; - -/// Combined limit for queued plaintext and ciphertext (matches rustls DEFAULT_BUFFER_LIMIT) +/// Combined outgoing plaintext/ciphertext bound, matching rustls's default. pub const OUTGOING_BUFFER_LIMIT: usize = 64 * 1024; -/// Strip TLS 1.3 content type trailer from decrypted plaintext slice. -/// -/// TLS 1.3 format: content || type_byte -/// Returns (content_type, valid_content_length) without modifying the slice. -/// -/// This is the zero-allocation version for use with in-place decryption. -/// NOTE: Does NOT strip padding zeros - our implementation doesn't add padding. #[cfg(test)] -#[inline] -pub fn strip_content_type_slice(plaintext: &[u8]) -> io::Result<(u8, usize)> { - if plaintext.is_empty() { - return Err(Error::new(ErrorKind::InvalidData, "Empty plaintext")); - } - - // No padding in our implementation - let content_type = plaintext[plaintext.len() - 1]; - - if content_type != CONTENT_TYPE_HANDSHAKE - && content_type != CONTENT_TYPE_APPLICATION_DATA - && content_type != CONTENT_TYPE_ALERT - { - return Err(Error::new( - ErrorKind::InvalidData, - format!("Invalid content type: 0x{:02x}", content_type), - )); - } - - Ok((content_type, plaintext.len() - 1)) -} - -/// Strip TLS 1.3 content type trailer from decrypted plaintext. -/// -/// TLS 1.3 format: content || type_byte -/// Returns the actual content type and modifies plaintext to contain only content. -/// -/// NOTE: This function does NOT strip padding zeros. Our REALITY implementation -/// does not add padding, so stripping zeros could corrupt data that legitimately -/// ends with zero bytes. Use `strip_content_type_with_padding` for messages from -/// external implementations that may use padding. -/// -/// Only used by tests. +pub const CONTENT_TYPE_HANDSHAKE: u8 = 22; #[cfg(test)] -pub fn strip_content_type(plaintext: &mut Vec) -> io::Result { - let (content_type, valid_len) = strip_content_type_slice(plaintext)?; - plaintext.truncate(valid_len); - Ok(content_type) -} - -/// Strip TLS 1.3 content type trailer and padding from decrypted plaintext. -/// -/// TLS 1.3 format: content || type_byte || padding_zeros -/// Returns the actual content type and modifies plaintext to contain only content. -/// -/// Use this for messages from external TLS implementations (e.g., sing-box) that -/// may add optional padding per RFC 8446 Section 5.4. -pub fn strip_content_type_with_padding(plaintext: &mut Vec) -> io::Result { - if plaintext.is_empty() { - return Err(Error::new(ErrorKind::InvalidData, "Empty plaintext")); - } - - // Remove trailing zeros (padding) per RFC 8446 Section 5.4 - while !plaintext.is_empty() && *plaintext.last().unwrap() == 0 { - plaintext.pop(); - } - - if plaintext.is_empty() { - return Err(Error::new(ErrorKind::InvalidData, "Plaintext is all zeros")); - } - - let content_type = plaintext.pop().unwrap(); - - if content_type != CONTENT_TYPE_HANDSHAKE - && content_type != CONTENT_TYPE_APPLICATION_DATA - && content_type != CONTENT_TYPE_ALERT - { - return Err(Error::new( - ErrorKind::InvalidData, - format!("Invalid content type: 0x{:02x}", content_type), - )); - } - - Ok(content_type) -} - +pub const VERSION_TLS_1_2_MAJOR: u8 = 3; #[cfg(test)] -mod tests { - #[test] - fn record_lengths_are_checked_before_buffering() { - assert_eq!( - super::checked_record_size(super::MAX_TLS_CIPHERTEXT_LEN).unwrap(), - super::TLS_MAX_RECORD_SIZE - ); - for size in [ - super::MAX_TLS_CIPHERTEXT_LEN + 1, - u16::MAX as usize, - usize::MAX, - ] { - assert_eq!( - super::checked_record_size(size).unwrap_err().kind(), - std::io::ErrorKind::InvalidData - ); - } - } - use super::*; - - #[test] - fn test_strip_content_type_app_data() { - let mut plaintext = vec![0x01, 0x02, 0x03, CONTENT_TYPE_APPLICATION_DATA]; - let ct = strip_content_type(&mut plaintext).unwrap(); - assert_eq!(ct, CONTENT_TYPE_APPLICATION_DATA); - assert_eq!(plaintext, vec![0x01, 0x02, 0x03]); - } - - #[test] - fn test_strip_content_type_handshake() { - let mut plaintext = vec![0xAA, 0xBB, CONTENT_TYPE_HANDSHAKE]; - let ct = strip_content_type(&mut plaintext).unwrap(); - assert_eq!(ct, CONTENT_TYPE_HANDSHAKE); - assert_eq!(plaintext, vec![0xAA, 0xBB]); - } - - #[test] - fn test_strip_content_type_alert() { - let mut plaintext = vec![0x01, 0x00, CONTENT_TYPE_ALERT]; - let ct = strip_content_type(&mut plaintext).unwrap(); - assert_eq!(ct, CONTENT_TYPE_ALERT); - assert_eq!(plaintext, vec![0x01, 0x00]); - } - - #[test] - fn test_strip_content_type_preserves_zeros() { - // Trailing zeros in data should be preserved (not treated as padding) - let mut plaintext = vec![0x01, 0x00, 0x00, CONTENT_TYPE_APPLICATION_DATA]; - let ct = strip_content_type(&mut plaintext).unwrap(); - assert_eq!(ct, CONTENT_TYPE_APPLICATION_DATA); - assert_eq!(plaintext, vec![0x01, 0x00, 0x00]); - } - - #[test] - fn test_strip_content_type_empty() { - let mut plaintext = Vec::new(); - assert!(strip_content_type(&mut plaintext).is_err()); - } - - #[test] - fn test_strip_content_type_invalid() { - let mut plaintext = vec![0x01, 0xFF]; // 0xFF is invalid - assert!(strip_content_type(&mut plaintext).is_err()); - } - - #[test] - fn test_strip_with_padding_no_padding() { - let mut plaintext = vec![0x01, 0x02, CONTENT_TYPE_APPLICATION_DATA]; - let ct = strip_content_type_with_padding(&mut plaintext).unwrap(); - assert_eq!(ct, CONTENT_TYPE_APPLICATION_DATA); - assert_eq!(plaintext, vec![0x01, 0x02]); - } - - #[test] - fn test_strip_with_padding_strips_zeros() { - // TLS 1.3 format: content || type || padding - let mut plaintext = vec![0x01, 0x02, CONTENT_TYPE_HANDSHAKE, 0x00, 0x00, 0x00]; - let ct = strip_content_type_with_padding(&mut plaintext).unwrap(); - assert_eq!(ct, CONTENT_TYPE_HANDSHAKE); - assert_eq!(plaintext, vec![0x01, 0x02]); - } - - #[test] - fn test_strip_with_padding_empty() { - let mut plaintext = Vec::new(); - assert!(strip_content_type_with_padding(&mut plaintext).is_err()); - } - - #[test] - fn test_strip_with_padding_all_zeros() { - let mut plaintext = vec![0x00, 0x00, 0x00]; - assert!(strip_content_type_with_padding(&mut plaintext).is_err()); - } - - #[test] - fn test_strip_with_padding_invalid_type() { - let mut plaintext = vec![0x01, 0xFF, 0x00]; // 0xFF with padding - assert!(strip_content_type_with_padding(&mut plaintext).is_err()); - } -} +pub const VERSION_TLS_1_2_MINOR: u8 = 3; +#[cfg(test)] +pub const HANDSHAKE_TYPE_SERVER_HELLO: u8 = 2; +#[cfg(test)] +pub const HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS: u8 = 8; +#[cfg(test)] +pub const HANDSHAKE_TYPE_CERTIFICATE: u8 = 11; +#[cfg(test)] +pub const HANDSHAKE_TYPE_CERTIFICATE_VERIFY: u8 = 15; +#[cfg(test)] +pub const HANDSHAKE_TYPE_FINISHED: u8 = 20; diff --git a/src/reality/mod.rs b/src/reality/mod.rs index 69c542b6..18879e04 100644 --- a/src/reality/mod.rs +++ b/src/reality/mod.rs @@ -3,27 +3,30 @@ // REALITY protocol: TLS obfuscation using X25519, HKDF-SHA256, AES-256-GCM, HMAC-SHA512 mod common; -mod reality_aead; mod reality_auth; mod reality_certificate; mod reality_cipher_suite; mod reality_client_connection; mod reality_client_verify; +mod reality_connection; mod reality_io_state; mod reality_key_exchange; mod reality_mldsa; mod reality_reader_writer; -mod reality_records; +mod reality_rustls; mod reality_server_connection; mod reality_server_handler; -mod reality_tls13_keys; +mod reality_target_template; +#[cfg(test)] mod reality_tls13_messages; mod reality_util; #[cfg(test)] mod reality_pq_tests; #[cfg(test)] -pub(crate) use reality_pq_tests::default_target_records; +mod reality_rustls_tests; +#[cfg(test)] +pub(crate) use reality_pq_tests::{default_target_records, established_pair}; pub use reality_cipher_suite::{CipherSuite, DEFAULT_CIPHER_SUITES}; #[allow(unused_imports)] diff --git a/src/reality/reality_aead.rs b/src/reality/reality_aead.rs deleted file mode 100644 index fb1360fc..00000000 --- a/src/reality/reality_aead.rs +++ /dev/null @@ -1,438 +0,0 @@ -// TLS 1.3 AEAD encryption/decryption using aws-lc-rs. -// Record framing is handled by reality_records.rs. - -use aws_lc_rs::aead::{Aad, LessSafeKey, Nonce, UnboundKey}; -use std::io::{self, Error, ErrorKind}; - -use super::common::strip_content_type_with_padding; -use super::reality_cipher_suite::CipherSuite; - -/// AEAD key for TLS 1.3 encryption/decryption. -/// -/// Wraps aws-lc-rs LessSafeKey and provides a cleaner API. -/// Create once per connection direction and reuse for all records. -pub struct AeadKey(LessSafeKey); - -impl AeadKey { - /// Create a new AEAD key from raw key bytes. - pub fn new(cipher_suite: CipherSuite, key: &[u8]) -> io::Result { - let algorithm = cipher_suite.algorithm(); - let expected_len = cipher_suite.key_len(); - - if key.len() != expected_len { - return Err(Error::new( - ErrorKind::InvalidInput, - format!( - "Invalid key length for {:?}: {} (expected {})", - cipher_suite, - key.len(), - expected_len - ), - )); - } - - let unbound = UnboundKey::new(algorithm, key) - .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid key: {:?}", e)))?; - - Ok(Self(LessSafeKey::new(unbound))) - } - - /// Encrypt in-place, appending 16-byte auth tag. - /// - /// The buffer is modified: plaintext -> ciphertext || tag - #[inline] - pub fn seal_in_place( - &self, - buf: &mut Vec, - iv: &[u8], - seq: u64, - aad: &[u8], - ) -> io::Result<()> { - let nonce = Self::make_nonce(iv, seq)?; - self.0 - .seal_in_place_append_tag(nonce, Aad::from(aad), buf) - .map_err(|e| { - Error::new( - ErrorKind::InvalidData, - format!("Encryption failed: {:?}", e), - ) - }) - } - - /// Encrypt with copy, returning new Vec containing ciphertext || tag. - /// - /// Use this for small buffers where allocation overhead doesn't matter. - #[inline] - #[cfg_attr(not(test), allow(dead_code))] // Used by test helpers - pub fn seal(&self, plaintext: &[u8], iv: &[u8], seq: u64, aad: &[u8]) -> io::Result> { - let mut buf = plaintext.to_vec(); - self.seal_in_place(&mut buf, iv, seq, aad)?; - Ok(buf) - } - - /// Decrypt in-place on a mutable slice, returning the plaintext portion. - /// - /// This is the zero-allocation decryption API. The slice is decrypted in-place - /// and a sub-slice containing only the plaintext (without the auth tag) is returned. - /// - /// # Arguments - /// * `buf` - Mutable slice containing ciphertext + auth tag - /// * `iv` - 12-byte IV/nonce base - /// * `seq` - Sequence number to XOR with IV - /// * `aad` - Additional authenticated data - /// - /// # Returns - /// Sub-slice of `buf` containing only the decrypted plaintext - #[inline] - pub fn open_in_place_slice<'a>( - &self, - buf: &'a mut [u8], - iv: &[u8], - seq: u64, - aad: &[u8], - ) -> io::Result<&'a mut [u8]> { - let nonce = Self::make_nonce(iv, seq)?; - self.0 - .open_in_place(nonce, Aad::from(aad), buf) - .map_err(|e| { - Error::new( - ErrorKind::InvalidData, - format!("Decryption failed: {:?}", e), - ) - }) - } - - /// Decrypt with copy, returning new Vec containing plaintext. - /// - /// Used for handshake decryption and tests where allocation is acceptable. - #[inline] - pub fn open(&self, ciphertext: &[u8], iv: &[u8], seq: u64, aad: &[u8]) -> io::Result> { - let mut buf = ciphertext.to_vec(); - let plaintext = self.open_in_place_slice(&mut buf, iv, seq, aad)?; - let plaintext_len = plaintext.len(); - buf.truncate(plaintext_len); - Ok(buf) - } - - /// Construct TLS 1.3 nonce: IV XOR sequence_number - fn make_nonce(iv: &[u8], seq: u64) -> io::Result { - if iv.len() != 12 { - return Err(Error::new( - ErrorKind::InvalidInput, - format!("Invalid IV length: {} (expected 12)", iv.len()), - )); - } - - let mut nonce_bytes = [0u8; 12]; - nonce_bytes.copy_from_slice(iv); - - // XOR last 8 bytes with sequence number (big-endian) - let seq_bytes = seq.to_be_bytes(); - for i in 0..8 { - nonce_bytes[4 + i] ^= seq_bytes[i]; - } - - Nonce::try_assume_unique_for_key(&nonce_bytes) - .map_err(|e| Error::new(ErrorKind::InvalidInput, format!("Invalid nonce: {:?}", e))) - } -} - -/// Decrypt a TLS 1.3 handshake message. -/// -/// Builds the AAD from the record length and decrypts. -/// Returns plaintext with content type trailer stripped. -pub fn decrypt_handshake_message( - cipher_suite: CipherSuite, - key: &[u8], - iv: &[u8], - seq: u64, - ciphertext: &[u8], - record_len: u16, -) -> io::Result> { - // Build AAD: TLS record header - let aad = [ - 0x17, // ApplicationData - 0x03, - 0x03, // TLS 1.2 version - (record_len >> 8) as u8, - (record_len & 0xff) as u8, - ]; - - let aead_key = AeadKey::new(cipher_suite, key)?; - let mut plaintext = aead_key.open(ciphertext, iv, seq, &aad)?; - - // Strip content type and optional padding (external implementations may pad) - let _ = strip_content_type_with_padding(&mut plaintext)?; - - Ok(plaintext) -} - -#[cfg(test)] -pub(crate) fn encrypt_tls13_record( - cipher_suite: CipherSuite, - key: &[u8], - iv: &[u8], - seq: u64, - plaintext: &[u8], - aad: &[u8], -) -> io::Result> { - AeadKey::new(cipher_suite, key)?.seal(plaintext, iv, seq, aad) -} - -#[cfg(test)] -pub(crate) fn decrypt_tls13_record( - cipher_suite: CipherSuite, - key: &[u8], - iv: &[u8], - seq: u64, - ciphertext: &[u8], - aad: &[u8], -) -> io::Result> { - AeadKey::new(cipher_suite, key)?.open(ciphertext, iv, seq, aad) -} - -#[cfg(test)] -mod tests { - use super::*; - - const CS: CipherSuite = CipherSuite::AES_128_GCM_SHA256; - - #[test] - fn test_encrypt_decrypt_record() { - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let plaintext = b"Hello, TLS 1.3!"; - let aad = b"additional data"; - - let ciphertext = encrypt_tls13_record(CS, &key, &iv, 0, plaintext, aad).unwrap(); - - let decrypted = decrypt_tls13_record(CS, &key, &iv, 0, &ciphertext, aad).unwrap(); - - assert_eq!(&decrypted[..], plaintext); - } - - #[test] - fn test_aead_key_seal_open() { - let key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let plaintext = b"Test message"; - let aad = b"aad"; - - let ciphertext = key.seal(plaintext, &iv, 0, aad).unwrap(); - let decrypted = key.open(&ciphertext, &iv, 0, aad).unwrap(); - - assert_eq!(&decrypted[..], plaintext); - } - - #[test] - fn test_aead_key_in_place() { - let key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let plaintext = b"Test in-place"; - let aad = b"aad"; - - let mut buf = plaintext.to_vec(); - key.seal_in_place(&mut buf, &iv, 0, aad).unwrap(); - - // buf now contains ciphertext + tag - assert_eq!(buf.len(), plaintext.len() + 16); - - let decrypted = key.open_in_place_slice(&mut buf, &iv, 0, aad).unwrap(); - assert_eq!(decrypted, plaintext); - } - - #[test] - fn test_encrypt_with_sequence_number() { - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let plaintext = b"Test with sequence"; - let aad = b"aad"; - - // Test that different sequence numbers produce different ciphertexts - let cipher1 = encrypt_tls13_record(CS, &key, &iv, 1, plaintext, aad).unwrap(); - let cipher2 = encrypt_tls13_record(CS, &key, &iv, 2, plaintext, aad).unwrap(); - let cipher3 = encrypt_tls13_record(CS, &key, &iv, 100, plaintext, aad).unwrap(); - - // Ciphertexts should all be different - assert_ne!(cipher1, cipher2); - assert_ne!(cipher2, cipher3); - assert_ne!(cipher1, cipher3); - - // But they should all decrypt correctly - let decrypt1 = decrypt_tls13_record(CS, &key, &iv, 1, &cipher1, aad).unwrap(); - let decrypt2 = decrypt_tls13_record(CS, &key, &iv, 2, &cipher2, aad).unwrap(); - let decrypt3 = decrypt_tls13_record(CS, &key, &iv, 100, &cipher3, aad).unwrap(); - - assert_eq!(decrypt1, plaintext); - assert_eq!(decrypt2, plaintext); - assert_eq!(decrypt3, plaintext); - } - - #[test] - fn test_decrypt_with_wrong_sequence_number() { - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let plaintext = b"Test sequence"; - let aad = b"aad"; - - let ciphertext = encrypt_tls13_record(CS, &key, &iv, 5, plaintext, aad).unwrap(); - - // Decrypting with wrong sequence number should fail - let result = decrypt_tls13_record(CS, &key, &iv, 6, &ciphertext, aad); - assert!(result.is_err()); - } - - #[test] - fn test_decrypt_with_wrong_aad() { - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let plaintext = b"Test AAD"; - let aad = b"correct aad"; - let wrong_aad = b"wrong aad"; - - let ciphertext = encrypt_tls13_record(CS, &key, &iv, 0, plaintext, aad).unwrap(); - - // Decrypting with wrong AAD should fail - let result = decrypt_tls13_record(CS, &key, &iv, 0, &ciphertext, wrong_aad); - assert!(result.is_err()); - } - - #[test] - fn test_encrypt_invalid_key_length() { - let invalid_key = vec![0x42u8; 15]; // Wrong length (not 16) - let iv = vec![0x99u8; 12]; - let plaintext = b"Test"; - let aad = b"aad"; - - let result = encrypt_tls13_record(CS, &invalid_key, &iv, 0, plaintext, aad); - assert!(result.is_err()); - assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidInput); - } - - #[test] - fn test_encrypt_invalid_iv_length() { - let key = vec![0x42u8; 16]; - let invalid_iv = vec![0x99u8; 11]; // Wrong length (not 12) - let plaintext = b"Test"; - let aad = b"aad"; - - let result = encrypt_tls13_record(CS, &key, &invalid_iv, 0, plaintext, aad); - assert!(result.is_err()); - assert_eq!(result.unwrap_err().kind(), ErrorKind::InvalidInput); - } - - #[test] - fn test_decrypt_corrupted_ciphertext() { - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let plaintext = b"Test corruption"; - let aad = b"aad"; - - let mut ciphertext = encrypt_tls13_record(CS, &key, &iv, 0, plaintext, aad).unwrap(); - - // Corrupt the ciphertext - ciphertext[5] ^= 0xFF; - - let result = decrypt_tls13_record(CS, &key, &iv, 0, &ciphertext, aad); - assert!(result.is_err()); - } - - #[test] - fn test_encrypt_empty_plaintext() { - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let plaintext = b""; - let aad = b"aad"; - - let ciphertext = encrypt_tls13_record(CS, &key, &iv, 0, plaintext, aad).unwrap(); - - // Should still produce a ciphertext with auth tag - assert!(ciphertext.len() >= 16); // At least the auth tag - - let decrypted = decrypt_tls13_record(CS, &key, &iv, 0, &ciphertext, aad).unwrap(); - assert_eq!(decrypted, plaintext); - } - - #[test] - fn test_large_plaintext() { - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let plaintext = vec![0xAB; 16384]; // 16KB - let aad = b"aad"; - - let ciphertext = encrypt_tls13_record(CS, &key, &iv, 42, &plaintext, aad).unwrap(); - let decrypted = decrypt_tls13_record(CS, &key, &iv, 42, &ciphertext, aad).unwrap(); - - assert_eq!(decrypted, plaintext); - } - - #[test] - fn test_decrypt_handshake_message() { - use super::decrypt_handshake_message; - use crate::reality::common::CONTENT_TYPE_HANDSHAKE; - - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let handshake_msg = vec![0xABu8; 100]; // Simulated handshake message - - // Build plaintext: handshake_msg || content_type - let mut plaintext_with_type = handshake_msg.clone(); - plaintext_with_type.push(CONTENT_TYPE_HANDSHAKE); - - // Calculate ciphertext length for AAD - let ciphertext_len = (plaintext_with_type.len() + 16) as u16; - - // Build AAD (TLS record header) - let aad = [ - 0x17, // ApplicationData - 0x03, - 0x03, // TLS 1.2 version - (ciphertext_len >> 8) as u8, - (ciphertext_len & 0xff) as u8, - ]; - - // Encrypt - let ciphertext = - encrypt_tls13_record(CS, &key, &iv, 0, &plaintext_with_type, &aad).unwrap(); - - // Decrypt using decrypt_handshake_message - let decrypted = - decrypt_handshake_message(CS, &key, &iv, 0, &ciphertext, ciphertext_len).unwrap(); - - assert_eq!(decrypted, handshake_msg); - } - - #[test] - fn test_decrypt_handshake_message_with_padding() { - use super::decrypt_handshake_message; - use crate::reality::common::CONTENT_TYPE_HANDSHAKE; - - let key = vec![0x42u8; 16]; - let iv = vec![0x99u8; 12]; - let handshake_msg = vec![0xCDu8; 50]; - - // Build plaintext with padding: handshake_msg || content_type || padding_zeros - let mut plaintext_with_type_and_padding = handshake_msg.clone(); - plaintext_with_type_and_padding.push(CONTENT_TYPE_HANDSHAKE); - plaintext_with_type_and_padding.extend_from_slice(&[0x00, 0x00, 0x00]); // 3 bytes padding - - let ciphertext_len = (plaintext_with_type_and_padding.len() + 16) as u16; - - let aad = [ - 0x17, - 0x03, - 0x03, - (ciphertext_len >> 8) as u8, - (ciphertext_len & 0xff) as u8, - ]; - - let ciphertext = - encrypt_tls13_record(CS, &key, &iv, 0, &plaintext_with_type_and_padding, &aad).unwrap(); - - // Padding should be stripped - let decrypted = - decrypt_handshake_message(CS, &key, &iv, 0, &ciphertext, ciphertext_len).unwrap(); - - assert_eq!(decrypted, handshake_msg); - } -} diff --git a/src/reality/reality_auth.rs b/src/reality/reality_auth.rs index 37a66d64..ad0911c7 100644 --- a/src/reality/reality_auth.rs +++ b/src/reality/reality_auth.rs @@ -143,9 +143,9 @@ pub fn encrypt_session_id( let aad_obj = Aad::from(aad); // aws-lc-rs requires in-place encryption - let mut in_out = plaintext.to_vec(); + let mut in_out = zeroize::Zeroizing::new(plaintext.to_vec()); sealing_key - .seal_in_place_append_tag(nonce_obj, aad_obj, &mut in_out) + .seal_in_place_append_tag(nonce_obj, aad_obj, &mut *in_out) .map_err(|_| CryptoError::EncryptionFailed)?; if in_out.len() != 32 { @@ -187,7 +187,7 @@ pub fn decrypt_session_id( let aad_obj = Aad::from(aad); // aws-lc-rs requires in-place decryption - let mut in_out = ciphertext_and_tag.to_vec(); + let mut in_out = zeroize::Zeroizing::new(ciphertext_and_tag.to_vec()); let plaintext = opening_key .open_in_place(nonce_obj, aad_obj, &mut in_out) .map_err(|_| CryptoError::DecryptionFailed)?; diff --git a/src/reality/reality_cipher_suite.rs b/src/reality/reality_cipher_suite.rs index 8588695a..9b61770c 100644 --- a/src/reality/reality_cipher_suite.rs +++ b/src/reality/reality_cipher_suite.rs @@ -1,14 +1,4 @@ -//! TLS 1.3 Cipher Suite definitions for REALITY protocol -//! -//! This module defines the CipherSuite type which bundles cipher suite ID -//! with its associated algorithms for AEAD encryption, transcript hashing, -//! and HKDF key derivation. - -use aws_lc_rs::{ - aead::{AES_128_GCM, AES_256_GCM, Algorithm, CHACHA20_POLY1305}, - digest, - hmac::{self, HMAC_SHA256, HMAC_SHA384}, -}; +//! Configurable TLS 1.3 cipher suite identifiers for REALITY. /// Default TLS 1.3 cipher suites in preference order pub const DEFAULT_CIPHER_SUITES: &[CipherSuite] = &[ @@ -17,20 +7,9 @@ pub const DEFAULT_CIPHER_SUITES: &[CipherSuite] = &[ CipherSuite::CHACHA20_POLY1305_SHA256, ]; -/// TLS 1.3 Cipher Suite with all associated algorithms -/// -/// This struct bundles the cipher suite ID with its corresponding AEAD algorithm, -/// digest algorithm (for transcript hashing), and HMAC algorithm (for HKDF operations). -/// Per RFC 8446, different cipher suites require different hash algorithms: -/// - TLS_AES_128_GCM_SHA256 (0x1301): SHA256 -/// - TLS_AES_256_GCM_SHA384 (0x1302): SHA384 -/// - TLS_CHACHA20_POLY1305_SHA256 (0x1303): SHA256 #[derive(Clone, Copy)] pub struct CipherSuite { id: u16, - algorithm: &'static Algorithm, - digest_algorithm: &'static digest::Algorithm, - hmac_algorithm: hmac::Algorithm, } impl PartialEq for CipherSuite { @@ -42,36 +21,11 @@ impl PartialEq for CipherSuite { impl Eq for CipherSuite {} impl CipherSuite { - pub const AES_128_GCM_SHA256: Self = Self { - id: 0x1301, - algorithm: &AES_128_GCM, - digest_algorithm: &digest::SHA256, - hmac_algorithm: HMAC_SHA256, - }; + pub const AES_128_GCM_SHA256: Self = Self { id: 0x1301 }; - pub const AES_256_GCM_SHA384: Self = Self { - id: 0x1302, - algorithm: &AES_256_GCM, - digest_algorithm: &digest::SHA384, - hmac_algorithm: HMAC_SHA384, - }; + pub const AES_256_GCM_SHA384: Self = Self { id: 0x1302 }; - pub const CHACHA20_POLY1305_SHA256: Self = Self { - id: 0x1303, - algorithm: &CHACHA20_POLY1305, - digest_algorithm: &digest::SHA256, - hmac_algorithm: HMAC_SHA256, - }; - - /// Get CipherSuite from wire format ID - pub fn from_id(id: u16) -> Option { - match id { - 0x1301 => Some(Self::AES_128_GCM_SHA256), - 0x1302 => Some(Self::AES_256_GCM_SHA384), - 0x1303 => Some(Self::CHACHA20_POLY1305_SHA256), - _ => None, - } - } + pub const CHACHA20_POLY1305_SHA256: Self = Self { id: 0x1303 }; /// Get CipherSuite from standard TLS name pub fn from_name(name: &str) -> Option { @@ -98,42 +52,6 @@ impl CipherSuite { pub fn id(&self) -> u16 { self.id } - - /// AEAD algorithm (AES_128_GCM, AES_256_GCM, or CHACHA20_POLY1305) - #[inline] - pub fn algorithm(&self) -> &'static Algorithm { - self.algorithm - } - - /// Key length in bytes (16 for AES-128, 32 for AES-256/ChaCha20) - #[inline] - pub fn key_len(&self) -> usize { - self.algorithm.key_len() - } - - /// Nonce/IV length in bytes (always 12 for TLS 1.3) - #[inline] - pub fn nonce_len(&self) -> usize { - self.algorithm.nonce_len() - } - - /// Hash output length in bytes (32 for SHA256, 48 for SHA384) - #[inline] - pub fn hash_len(&self) -> usize { - self.digest_algorithm.output_len() - } - - /// Digest algorithm for transcript hashing - #[inline] - pub fn digest_algorithm(&self) -> &'static digest::Algorithm { - self.digest_algorithm - } - - /// HMAC algorithm for HKDF operations - #[inline] - pub fn hmac_algorithm(&self) -> hmac::Algorithm { - self.hmac_algorithm - } } impl std::fmt::Debug for CipherSuite { diff --git a/src/reality/reality_client_connection.rs b/src/reality/reality_client_connection.rs index f97511f3..581581e9 100644 --- a/src/reality/reality_client_connection.rs +++ b/src/reality/reality_client_connection.rs @@ -1,1471 +1,63 @@ -// REALITY client connection with rustls-compatible API +use std::io; +use std::sync::Arc; -use std::io::{self, Read, Write}; +use super::CipherSuite; +use super::reality_connection::{RealityTransport, delegate_tls}; +use super::reality_rustls::{client_authentication, io_error, provider}; -use super::reality_key_exchange::{ - KeyShareRef, RealityGroup, complete_client_exchange, extract_server_key_share, generate_mlkem, -}; -use aws_lc_rs::{agreement, digest, kem}; -use rand::Rng; -use subtle::ConstantTimeEq; - -use super::common::{ - ALERT_DESC_CLOSE_NOTIFY, ALERT_LEVEL_WARNING, CIPHERTEXT_READ_BUF_CAPACITY, CONTENT_TYPE_ALERT, - CONTENT_TYPE_APPLICATION_DATA, CONTENT_TYPE_CHANGE_CIPHER_SPEC, CONTENT_TYPE_HANDSHAKE, - HANDSHAKE_TYPE_CERTIFICATE, HANDSHAKE_TYPE_CERTIFICATE_VERIFY, - HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, HANDSHAKE_TYPE_FINISHED, MAX_TLS_PLAINTEXT_LEN, - PLAINTEXT_READ_BUF_CAPACITY, TLS_MAX_RECORD_SIZE, TLS_RECORD_HEADER_SIZE, -}; -use super::reality_aead::{AeadKey, decrypt_handshake_message}; -use super::reality_auth::{derive_auth_key, encrypt_session_id, perform_ecdh}; -use super::reality_cipher_suite::{CipherSuite, DEFAULT_CIPHER_SUITES}; -use super::reality_client_verify::{ - extract_certificate_der, extract_certificate_verify_signature, extract_ed25519_public_key, - verify_certificate_hmac, verify_certificate_verify_signature, -}; -use super::reality_io_state::RealityIoState; -use super::reality_reader_writer::{RealityReader, RealityWriter}; -use super::reality_records::{RecordDecryptor, RecordEncryptor}; -use super::reality_tls13_keys::{ - compute_finished_verify_data, derive_application_secrets, derive_handshake_keys, - derive_traffic_keys, -}; -use super::reality_tls13_messages::{ - DEFAULT_ALPN_PROTOCOLS, construct_client_hello, construct_finished, write_record_header, -}; -use super::reality_util::extract_server_cipher_suite; -use crate::slide_buffer::SlideBuffer; -use crate::util::allocate_vec; - -// Matches the maximum handshake size accepted by Xray's REALITY implementation. -const MAX_HANDSHAKE_PLAINTEXT: usize = 4 * MAX_TLS_PLAINTEXT_LEN; - -fn append_handshake_plaintext(accumulated: &mut Vec, plaintext: &[u8]) -> io::Result<()> { - if accumulated.len().saturating_add(plaintext.len()) > MAX_HANDSHAKE_PLAINTEXT { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "REALITY handshake exceeds maximum size", - )); - } - accumulated.extend_from_slice(plaintext); - Ok(()) -} - -/// Configuration for REALITY client connections #[derive(Clone)] pub struct RealityClientConfig { pub mldsa65_verify: Option, - /// Server's X25519 public key (32 bytes) pub public_key: [u8; 32], - /// Short ID for authentication (8 bytes) pub short_id: [u8; 8], - /// Server name for SNI pub server_name: String, - /// Supported TLS 1.3 cipher suites (empty = use defaults) pub cipher_suites: Vec, } -/// Handshake state machine for REALITY client -enum HandshakeState { - /// ClientHello sent, waiting for ServerHello - AwaitingServerHello { - client_hello_bytes: Vec, // Full ClientHello handshake message (raw bytes for transcript) - client_private_key: [u8; 32], - mlkem_private: Option, - auth_key: [u8; 32], // REALITY authentication key for HMAC verification - }, - /// ServerHello received, processing encrypted handshake messages - ProcessingHandshake { - client_handshake_traffic_secret: Vec, - server_handshake_traffic_secret: Vec, - master_secret: Vec, - cipher_suite: CipherSuite, - handshake_transcript_bytes: Vec, // Accumulated transcript for hash computation - auth_key: [u8; 32], // REALITY authentication key for HMAC verification - // State for handling multiple encrypted handshake records (separate mode) - handshake_seq: u64, // Sequence number for decrypting records - accumulated_plaintext: Vec, // Accumulated plaintext across records - parsed_plaintext: usize, - messages_found: u8, // Number of handshake messages found so far - certificate_verified: bool, // Whether Certificate HMAC was verified - ed25519_public_key: Option<[u8; 32]>, // Public key from Certificate for CV verification - cert_verify_offset: Option, // Offset of CertificateVerify in accumulated plaintext - }, - /// Handshake complete, ready for application data - Complete, -} - -/// REALITY client-side connection implementing rustls-compatible API pub struct RealityClientConnection { - // Configuration - config: RealityClientConfig, - - // Handshake state - handshake_state: HandshakeState, - - // TLS 1.3 application traffic encryption (post-handshake) - // Keys are cached as AeadKey to avoid per-record key setup overhead - app_read_key: Option, - app_read_iv: Option>, - app_write_key: Option, - app_write_iv: Option>, - read_seq: u64, - write_seq: u64, - cipher_suite: Option, - negotiated_group: Option, - - // Pre-allocated buffer for TLS read operations (reused across calls) - tls_read_buffer: Box<[u8]>, - - // Buffers for I/O - using SlideBuffer for efficient zero-alloc operations - ciphertext_read_buf: SlideBuffer, // Incoming encrypted TLS records - ciphertext_write_buf: Vec, // Outgoing encrypted TLS records - plaintext_read_buf: SlideBuffer, // Decrypted application data - plaintext_write_buf: Vec, // Application data to encrypt - - // Connection state flags (mirrors rustls patterns) - received_close_notify: bool, // Peer sent close_notify alert - fatal_error: Option, // Fatal error occurred, connection unusable + pub(super) transport: RealityTransport, } impl RealityClientConnection { - /// Create a new REALITY client connection and generate ClientHello pub fn new(config: RealityClientConfig) -> io::Result { - let mut conn = RealityClientConnection { - config, - handshake_state: HandshakeState::AwaitingServerHello { - client_hello_bytes: Vec::new(), - client_private_key: [0u8; 32], - mlkem_private: None, - auth_key: [0u8; 32], - }, - app_read_key: None, - app_read_iv: None, - app_write_key: None, - app_write_iv: None, - read_seq: 0, - write_seq: 0, - cipher_suite: None, - negotiated_group: None, - tls_read_buffer: allocate_vec(TLS_MAX_RECORD_SIZE).into_boxed_slice(), - ciphertext_read_buf: SlideBuffer::new(CIPHERTEXT_READ_BUF_CAPACITY), - ciphertext_write_buf: Vec::new(), - plaintext_read_buf: SlideBuffer::new(PLAINTEXT_READ_BUF_CAPACITY), - plaintext_write_buf: Vec::new(), - received_close_notify: false, - fatal_error: None, - }; - - conn.generate_client_hello()?; - - Ok(conn) + let crypto = provider(&config.cipher_suites); + let schemes = crypto.signature_verification_algorithms.supported_schemes(); + Self::with_options(config, crypto, schemes, Arc::new(rustls::NoKeyLog {})) } - /// Generate and buffer ClientHello - fn generate_client_hello(&mut self) -> io::Result<()> { - let mut rng = rand::rng(); - - let mut our_private_bytes = [0u8; 32]; - rng.fill_bytes(&mut our_private_bytes); - - let our_private_key = - agreement::PrivateKey::from_private_key(&agreement::X25519, &our_private_bytes) - .map_err(|_| io::Error::other("Failed to create X25519 key"))?; - let our_public_key_bytes = our_private_key - .compute_public_key() - .map_err(|_| io::Error::other("Failed to compute public key"))?; - - let (mlkem_private, mut hybrid_share) = generate_mlkem()?; - hybrid_share.extend_from_slice(our_public_key_bytes.as_ref()); - let key_shares = [ - KeyShareRef { - group: RealityGroup::X25519MlKem768, - data: &hybrid_share, - }, - KeyShareRef { - group: RealityGroup::X25519, - data: our_public_key_bytes.as_ref(), - }, - ]; - - let mut client_random = [0u8; 32]; - rng.fill_bytes(&mut client_random); - - // Perform ECDH with server's public key to derive auth key - let shared_secret = perform_ecdh(&our_private_bytes, &self.config.public_key) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; - - // Use slice directly from client_random to avoid copying - let auth_key = derive_auth_key(&shared_secret, &client_random[0..20], b"REALITY") - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; - - // Create session ID with REALITY metadata - let timestamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_err(|_| io::Error::other("System time error"))? - .as_secs(); - - let mut session_id_plaintext = [0u8; 16]; - session_id_plaintext[0] = 1; // Protocol version major - session_id_plaintext[1] = 8; // Protocol version minor - session_id_plaintext[2] = 0; // Protocol version patch - session_id_plaintext[3] = 0; // Padding byte - // Timestamp (4 bytes as uint32, in seconds) - session_id_plaintext[4..8].copy_from_slice(&(timestamp as u32).to_be_bytes()); - // Short ID (8 bytes) - session_id_plaintext[8..16].copy_from_slice(&self.config.short_id); - - // Create a 32-byte SessionId (16 bytes plaintext + 16 bytes zeros for padding) - let mut session_id_for_hello = [0u8; 32]; - session_id_for_hello[0..16].copy_from_slice(&session_id_plaintext); - - // Build ClientHello with plaintext SessionId first - // Use configured cipher suites or defaults if none specified - let cipher_suites = if self.config.cipher_suites.is_empty() { - DEFAULT_CIPHER_SUITES.to_vec() - } else { - self.config.cipher_suites.clone() - }; - let cipher_suite_ids: Vec = cipher_suites.iter().map(|cs| cs.id()).collect(); - let mut client_hello = construct_client_hello( - &client_random, - &session_id_for_hello, - &key_shares, - &self.config.server_name, - &cipher_suite_ids, - DEFAULT_ALPN_PROTOCOLS, - )?; - - // Now encrypt the SessionId using the ClientHello with zeroed SessionId as AAD - // Use slice directly from client_random to avoid copying - let nonce = &client_random[20..32]; - - // Zero out the SessionId in ClientHello to create AAD (matches what server will use) - // SessionId is at offset 39 in ClientHello handshake - client_hello[39..71].fill(0); - - log::debug!("REALITY CLIENT: Encrypting SessionId"); - log::debug!( - " aad_len={} (ClientHello with zero SessionId)", - client_hello.len() - ); - log::debug!(" aad[0..4]={:02x?}", &client_hello[0..4]); - - let encrypted_session_id = - encrypt_session_id(&session_id_plaintext, &auth_key, nonce, &client_hello) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; - - log::debug!( - "REALITY CLIENT: Encrypted SessionId={:02x?}", - encrypted_session_id - ); - - // Restore the encrypted SessionId before writing or storing ClientHello. - // REALITY transcripts use the wire ClientHello, not the zeroed AAD form. - client_hello[39..71].copy_from_slice(&encrypted_session_id); - - let mut record = write_record_header(CONTENT_TYPE_HANDSHAKE, client_hello.len() as u16); - record.extend_from_slice(&client_hello); - self.ciphertext_write_buf.extend_from_slice(&record); - - // Store the wire ClientHello bytes for transcript hashing after ServerHello. - // At this point client_hello contains the encrypted SessionId. - self.handshake_state = HandshakeState::AwaitingServerHello { - client_hello_bytes: client_hello, // Save the actual ClientHello bytes - client_private_key: our_private_bytes, - mlkem_private: Some(mlkem_private), - auth_key, // Save auth_key for HMAC certificate verification - }; - - log::debug!( - "REALITY: ClientHello generated and buffered ({} bytes)", - record.len() - ); - - Ok(()) - } - - /// Read TLS messages from the provided reader into internal buffer - /// - /// Uses pre-allocated buffer to avoid allocation on every call. - pub fn read_tls(&mut self, rd: &mut dyn Read) -> io::Result { - if self.ciphertext_read_buf.remaining_capacity() < TLS_MAX_RECORD_SIZE { - self.ciphertext_read_buf.compact(); - } - - let n = rd.read(&mut self.tls_read_buffer[..])?; - if n > 0 { - self.ciphertext_read_buf - .extend_from_slice(&self.tls_read_buffer[..n]); - } - Ok(n) - } - - /// Process buffered packets and advance state machine - /// - /// Like rustls, this loops until no more progress can be made, ensuring - /// that piggybacked application data is processed in the same call. - pub fn process_new_packets(&mut self) -> io::Result { - if let Some(error_kind) = self.fatal_error { - return Err(io::Error::new(error_kind, "connection previously failed")); - } - - // RFC 8446: don't process data after close_notify - if self.received_close_notify { - return Ok(RealityIoState::new(self.plaintext_read_buf.len())); - } - - let result = self.process_new_packets_inner(); - - if let Err(ref e) = result { - match e.kind() { - io::ErrorKind::InvalidData - | io::ErrorKind::PermissionDenied - | io::ErrorKind::ConnectionAborted => { - self.fatal_error = Some(e.kind()); - } - _ => {} - } - } - - result - } - - /// Inner implementation of process_new_packets - fn process_new_packets_inner(&mut self) -> io::Result { - loop { - match &self.handshake_state { - HandshakeState::AwaitingServerHello { .. } => { - if !self.process_server_hello()? { - break; - } - } - HandshakeState::ProcessingHandshake { .. } => { - if !self.process_encrypted_handshake()? { - break; - } - } - HandshakeState::Complete => { - self.process_application_data()?; - break; - } - } - } - - Ok(RealityIoState::new(self.plaintext_read_buf.len())) - } - - /// Process ServerHello - /// Returns true if a complete record was processed, false if more data needed - #[inline] - fn process_server_hello(&mut self) -> io::Result { - let HandshakeState::AwaitingServerHello { - client_hello_bytes, - client_private_key, - mlkem_private, - auth_key, - } = &self.handshake_state - else { - unreachable!() - }; - - if self.ciphertext_read_buf.len() < TLS_RECORD_HEADER_SIZE { - return Ok(false); - } - - let record_len = self - .ciphertext_read_buf - .get_u16_be(3) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Buffer too short"))? - as usize; - - let total_record_len = super::common::checked_record_size(record_len)?; - if self.ciphertext_read_buf.len() < total_record_len { - return Ok(false); - } - - // Clone fields before consuming buffer - let client_hello_bytes = client_hello_bytes.clone(); - - let record: Vec = self.ciphertext_read_buf[..total_record_len].to_vec(); - self.ciphertext_read_buf.consume(total_record_len); - let server_hello = &record[TLS_RECORD_HEADER_SIZE..]; // Skip TLS record header (includes handshake header) - - log::debug!( - "REALITY CLIENT: ServerHello for transcript: len={}, bytes={:02x?}", - server_hello.len(), - server_hello - ); - - let server_share = extract_server_key_share(&record)?; - if super::reality_util::extract_session_id_slice(&record)? != &client_hello_bytes[39..71] { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "ServerHello session ID mismatch", - )); - } - let cipher_suite_id = extract_server_cipher_suite(&record)?; - let cipher_suite = CipherSuite::from_id(cipher_suite_id).ok_or_else(|| { - io::Error::new( - io::ErrorKind::InvalidData, - format!( - "Server selected unsupported cipher suite: 0x{:04x}", - cipher_suite_id - ), - ) + pub(super) fn with_options( + config: RealityClientConfig, + crypto: rustls::crypto::CryptoProvider, + schemes: Vec, + key_log: Arc, + ) -> io::Result { + let (hooks, verifier) = client_authentication(&config, schemes); + let mut tls = rustls::ClientConfig::builder_with_provider(Arc::new(crypto)) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(io_error)? + .dangerous() + .with_custom_certificate_verifier(Arc::new(verifier)) + .with_no_client_auth(); + tls.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; + tls.cert_decompressors.clear(); + tls.key_log = key_log; + let name = config.server_name.try_into().map_err(|_| { + io::Error::new(io::ErrorKind::InvalidInput, "Invalid REALITY server name") })?; - if !self.config.cipher_suites.is_empty() - && !self.config.cipher_suites.contains(&cipher_suite) - { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Server selected unoffered cipher suite", - )); - } - log::debug!( - "REALITY CLIENT: Server selected cipher suite 0x{:04x}", - cipher_suite_id - ); - - // Compute transcript hash using negotiated cipher suite's algorithm - let mut full_transcript = digest::Context::new(cipher_suite.digest_algorithm()); - log::debug!( - "REALITY CLIENT: Transcript includes ClientHello ({} bytes), first bytes: {:02x?}", - client_hello_bytes.len(), - &client_hello_bytes[..client_hello_bytes.len().min(20)] - ); - log::debug!( - "REALITY CLIENT: Transcript includes ServerHello ({} bytes), first bytes: {:02x?}", - server_hello.len(), - &server_hello[..server_hello.len().min(20)] - ); - full_transcript.update(&client_hello_bytes); // Use actual ClientHello bytes, not hash! - full_transcript.update(server_hello); // ServerHello already includes handshake header - let server_hello_hash = full_transcript.finish(); - let server_hello_hash_vec: Vec = server_hello_hash.as_ref().to_vec(); - - let client_hello_hash_vec: Vec = { - let mut ctx = digest::Context::new(cipher_suite.digest_algorithm()); - ctx.update(&client_hello_bytes); - ctx.finish().as_ref().to_vec() - }; - - let tls_shared_secret = complete_client_exchange( - client_private_key, - mlkem_private.as_ref().expect("ClientHello generated"), - &server_share, - )?; - self.negotiated_group = Some(server_share.group); - - let hs_keys = derive_handshake_keys( - server_share.group, - cipher_suite, - &tls_shared_secret, - &client_hello_hash_vec, - &server_hello_hash_vec, - )?; - - log::debug!("REALITY: ServerHello processed, handshake keys derived"); - - // Use actual bytes (not hashes) for transcript - let mut transcript_bytes = Vec::new(); - transcript_bytes.extend_from_slice(&client_hello_bytes); - transcript_bytes.extend_from_slice(server_hello); - - self.handshake_state = HandshakeState::ProcessingHandshake { - client_handshake_traffic_secret: hs_keys.client_handshake_traffic_secret.clone(), - server_handshake_traffic_secret: hs_keys.server_handshake_traffic_secret.clone(), - master_secret: hs_keys.master_secret.clone(), - cipher_suite, - handshake_transcript_bytes: transcript_bytes, - auth_key: *auth_key, // Pass auth_key for certificate HMAC verification - // Initialize state for handling multiple encrypted handshake records - handshake_seq: 0, - accumulated_plaintext: Vec::new(), - parsed_plaintext: 0, - messages_found: 0, - certificate_verified: false, - ed25519_public_key: None, - cert_verify_offset: None, - }; - - Ok(true) - } - - /// Process encrypted handshake messages (EncryptedExtensions, Certificate, CertificateVerify, Finished) - /// Handles both combined (1 record) and separate (multiple records) modes. - /// Returns true if a complete record was processed, false if more data needed - #[inline] - fn process_encrypted_handshake(&mut self) -> io::Result { - let HandshakeState::ProcessingHandshake { - client_handshake_traffic_secret, - server_handshake_traffic_secret, - master_secret, - cipher_suite, - handshake_transcript_bytes, - auth_key, - handshake_seq, - accumulated_plaintext, - parsed_plaintext, - messages_found, - certificate_verified, - ed25519_public_key, - cert_verify_offset, - } = &self.handshake_state - else { - unreachable!() - }; - - let (server_hs_key, server_hs_iv) = - derive_traffic_keys(server_handshake_traffic_secret, *cipher_suite)?; - - if self.ciphertext_read_buf.len() < TLS_RECORD_HEADER_SIZE { - return Ok(false); - } - - let record_type = self.ciphertext_read_buf[0]; - let tls_version = self - .ciphertext_read_buf - .get_u16_be(1) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Buffer too short"))?; - let record_len = self - .ciphertext_read_buf - .get_u16_be(3) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Buffer too short"))? - as usize; - - log::debug!( - "REALITY CLIENT: TLS record header: type=0x{:02x}, version=0x{:04x}, len={}", - record_type, - tls_version, - record_len - ); - - let total_record_len = super::common::checked_record_size(record_len)?; - if self.ciphertext_read_buf.len() < total_record_len { - return Ok(false); - } - - // Skip ChangeCipherSpec (dummy in TLS 1.3) - if record_type == CONTENT_TYPE_CHANGE_CIPHER_SPEC { - log::debug!( - "REALITY CLIENT: Skipping ChangeCipherSpec record ({} bytes)", - record_len - ); - self.ciphertext_read_buf.consume(total_record_len); - return self.process_encrypted_handshake(); - } - - if record_type != CONTENT_TYPE_APPLICATION_DATA { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!( - "Expected Application Data record, got 0x{:02x}", - record_type - ), - )); - } - - // NOW we're committed to processing - clone/copy fields we need to modify - let client_hs_secret = client_handshake_traffic_secret.clone(); - let server_hs_secret = server_handshake_traffic_secret.clone(); - let master_secret = master_secret.clone(); - let transcript_bytes = handshake_transcript_bytes.clone(); - let mut accumulated_plaintext = accumulated_plaintext.clone(); - let cipher_suite = *cipher_suite; - let auth_key = *auth_key; - let mut handshake_seq = *handshake_seq; - let mut messages_found = *messages_found; - let mut certificate_verified = *certificate_verified; - let mut ed25519_public_key = *ed25519_public_key; - let mut cert_verify_offset = *cert_verify_offset; - - // Copy and extract the encrypted handshake record - let ciphertext: Vec = - self.ciphertext_read_buf[TLS_RECORD_HEADER_SIZE..total_record_len].to_vec(); - self.ciphertext_read_buf.consume(total_record_len); - - log::debug!( - "REALITY CLIENT: Decrypting handshake record #{} - record_len={}", - handshake_seq, - record_len - ); - - // Decrypt using current sequence number - let plaintext = decrypt_handshake_message( - cipher_suite, - &server_hs_key, - &server_hs_iv, - handshake_seq, - &ciphertext, - record_len as u16, - )?; - - log::debug!( - "REALITY CLIENT: Decrypted record #{} ({} bytes plaintext)", - handshake_seq, - plaintext.len() - ); - - handshake_seq += 1; - - append_handshake_plaintext(&mut accumulated_plaintext, &plaintext)?; - // Resumes at the last complete message, including across TLS record boundaries. - let mut offset = *parsed_plaintext; - while offset < accumulated_plaintext.len() && messages_found < 4 { - // Each handshake message has: type (1 byte) + length (3 bytes) + data - if offset + 4 > accumulated_plaintext.len() { - break; // Incomplete message header, need more data - } - - let msg_type = accumulated_plaintext[offset]; - let msg_len = u32::from_be_bytes([ - 0, - accumulated_plaintext[offset + 1], - accumulated_plaintext[offset + 2], - accumulated_plaintext[offset + 3], - ]) as usize; - - if offset + 4 + msg_len > accumulated_plaintext.len() { - break; // Incomplete message body, need more data - } - - let expected = [ - HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS, - HANDSHAKE_TYPE_CERTIFICATE, - HANDSHAKE_TYPE_CERTIFICATE_VERIFY, - HANDSHAKE_TYPE_FINISHED, - ][messages_found as usize]; - if msg_type != expected { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Unexpected REALITY handshake message", - )); - } - if msg_type == HANDSHAKE_TYPE_FINISHED { - let mut transcript = digest::Context::new(cipher_suite.digest_algorithm()); - transcript.update(&transcript_bytes); - transcript.update(&accumulated_plaintext[..offset]); - let expected = compute_finished_verify_data( - cipher_suite, - &server_hs_secret, - transcript.finish().as_ref(), - )?; - let received = &accumulated_plaintext[offset + 4..offset + 4 + msg_len]; - if expected.as_slice().ct_eq(received).unwrap_u8() != 1 { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "REALITY server Finished verification failed", - )); - } - } - - let msg_name = match msg_type { - HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS => "EncryptedExtensions", - HANDSHAKE_TYPE_CERTIFICATE => "Certificate", - HANDSHAKE_TYPE_CERTIFICATE_VERIFY => "CertificateVerify", - HANDSHAKE_TYPE_FINISHED => "Finished", - _ => "Unknown", - }; - - log::debug!( - "REALITY CLIENT: Found {} message (type={}, len={})", - msg_name, - msg_type, - msg_len - ); - - // Verify HMAC signature when we encounter the Certificate message - if msg_type == HANDSHAKE_TYPE_CERTIFICATE { - let cert_der = - extract_certificate_der(&accumulated_plaintext[offset..offset + 4 + msg_len])?; - verify_certificate_hmac(cert_der, &auth_key)?; - if let Some(key) = &self.config.mldsa65_verify { - super::reality_client_verify::verify_certificate_mldsa( - cert_der, - &auth_key, - &transcript_bytes, - key, - )?; - } - ed25519_public_key = Some(extract_ed25519_public_key(cert_der)?); - certificate_verified = true; - } - - // Record CertificateVerify offset for later verification - if msg_type == HANDSHAKE_TYPE_CERTIFICATE_VERIFY { - cert_verify_offset = Some(offset); - } - - messages_found += 1; - offset += 4 + msg_len; - } - - if messages_found < 4 { - log::debug!( - "REALITY CLIENT: Received {} of 4 handshake messages, waiting for more records", - messages_found - ); - self.handshake_state = HandshakeState::ProcessingHandshake { - client_handshake_traffic_secret: client_hs_secret, - server_handshake_traffic_secret: server_hs_secret, - master_secret, - cipher_suite, - handshake_transcript_bytes: transcript_bytes, - auth_key, - handshake_seq, - accumulated_plaintext, - parsed_plaintext: offset, - messages_found, - certificate_verified, - ed25519_public_key, - cert_verify_offset, - }; - return Ok(true); // Processed a record, but need more - } - - if offset != accumulated_plaintext.len() { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Trailing handshake plaintext", - )); - } - - log::debug!( - "REALITY CLIENT: All 4 handshake messages received ({} bytes total)", - accumulated_plaintext.len() - ); - - // Ensure the Certificate message was present and HMAC verified - if !certificate_verified { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "REALITY handshake failed: Certificate message not received or not verified", - )); - } - - // Verify CertificateVerify signature - let mut cert_verify_verified = false; - if let (Some(public_key), Some(cv_offset)) = (ed25519_public_key, cert_verify_offset) { - // Transcript up to (not including) CertificateVerify - let mut cv_transcript = digest::Context::new(cipher_suite.digest_algorithm()); - cv_transcript.update(&transcript_bytes); - cv_transcript.update(&accumulated_plaintext[..cv_offset]); - let cv_transcript_hash = cv_transcript.finish(); - - let cv_msg_len = u32::from_be_bytes([ - 0, - accumulated_plaintext[cv_offset + 1], - accumulated_plaintext[cv_offset + 2], - accumulated_plaintext[cv_offset + 3], - ]) as usize; - let cv_message = &accumulated_plaintext[cv_offset..cv_offset + 4 + cv_msg_len]; - let signature = extract_certificate_verify_signature(cv_message)?; - - verify_certificate_verify_signature( - &public_key, - &signature, - cv_transcript_hash.as_ref(), - )?; - cert_verify_verified = true; - } - - if !cert_verify_verified { - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "REALITY handshake failed: CertificateVerify not verified", - )); - } - - let mut handshake_transcript = digest::Context::new(cipher_suite.digest_algorithm()); - handshake_transcript.update(&transcript_bytes); - handshake_transcript.update(&accumulated_plaintext); - - let handshake_hash = handshake_transcript.finish(); - let handshake_hash_vec: Vec = handshake_hash.as_ref().to_vec(); - - log::debug!( - "REALITY CLIENT: Handshake hash for client Finished: {:02x?}", - handshake_hash_vec - ); - log::debug!( - "REALITY CLIENT: Transcript bytes len={}, accumulated_plaintext len={}", - transcript_bytes.len(), - accumulated_plaintext.len() - ); - - let client_verify_data = - compute_finished_verify_data(cipher_suite, &client_hs_secret, &handshake_hash_vec)?; - log::debug!( - "REALITY CLIENT: Client verify data: {:02x?}", - client_verify_data - ); - let client_finished = construct_finished(&client_verify_data)?; - - let (client_hs_key, client_hs_iv) = derive_traffic_keys(&client_hs_secret, cipher_suite)?; - - let mut client_hs_seq = 0u64; - let buf_len_before = self.ciphertext_write_buf.len(); - let hs_aead_key = AeadKey::new(cipher_suite, &client_hs_key)?; - { - let mut encryptor = - RecordEncryptor::new(&hs_aead_key, &client_hs_iv, &mut client_hs_seq); - encryptor.encrypt_handshake(&client_finished, &mut self.ciphertext_write_buf)?; - } - - log::debug!( - "REALITY CLIENT: Client Finished message generated and buffered ({} bytes)", - self.ciphertext_write_buf.len() - buf_len_before - ); - - let (client_app_secret, server_app_secret) = - derive_application_secrets(cipher_suite, &master_secret, &handshake_hash_vec)?; - - let (client_app_key_bytes, client_app_iv) = - derive_traffic_keys(&client_app_secret, cipher_suite)?; - let (server_app_key_bytes, server_app_iv) = - derive_traffic_keys(&server_app_secret, cipher_suite)?; - - // Cache AeadKey objects to avoid per-record key setup - let client_app_key = AeadKey::new(cipher_suite, &client_app_key_bytes)?; - let server_app_key = AeadKey::new(cipher_suite, &server_app_key_bytes)?; - - self.app_read_key = Some(server_app_key); - self.app_read_iv = Some(server_app_iv); - self.app_write_key = Some(client_app_key); - self.app_write_iv = Some(client_app_iv); - self.read_seq = 0; - self.write_seq = 0; - self.cipher_suite = Some(cipher_suite); - self.handshake_state = HandshakeState::Complete; - log::debug!( - "REALITY: negotiated_group={}", - self.negotiated_group() - .map(RealityGroup::name) - .unwrap_or("unknown") - ); - log::debug!("REALITY CLIENT: Handshake complete, application keys derived"); - - Ok(true) - } - - /// Decrypt application data using TLS 1.3 keys - /// Processes all complete TLS records in the buffer - #[inline] - fn process_application_data(&mut self) -> io::Result<()> { - let (app_read_key, app_read_iv) = match (&self.app_read_key, &self.app_read_iv) { - (Some(key), Some(iv)) => (key, iv), - _ => unreachable!(), // Wrong state - }; - - while self.ciphertext_read_buf.len() >= TLS_RECORD_HEADER_SIZE { - let record_len = self - .ciphertext_read_buf - .get_u16_be(3) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Buffer too short"))? - as usize; - - let total_record_len = super::common::checked_record_size(record_len)?; - if self.ciphertext_read_buf.len() < total_record_len { - break; - } - - // Decrypt in-place: get mutable slice of ciphertext, decrypt, copy plaintext out - let ciphertext_slice = self - .ciphertext_read_buf - .slice_mut(TLS_RECORD_HEADER_SIZE..total_record_len); - let mut decryptor = RecordDecryptor::new(app_read_key, app_read_iv, &mut self.read_seq); - let (content_type, plaintext) = - decryptor.decrypt_record_in_place(ciphertext_slice, record_len as u16)?; - - match content_type { - CONTENT_TYPE_APPLICATION_DATA => { - // Compact plaintext buffer if needed before extending - self.plaintext_read_buf.maybe_compact(4096); - self.plaintext_read_buf.extend_from_slice(plaintext); - } - CONTENT_TYPE_ALERT => { - // Parse alert: level (1 byte) + description (1 byte) - if plaintext.len() >= 2 { - let alert_level = plaintext[0]; - let alert_desc = plaintext[1]; - - if alert_desc == ALERT_DESC_CLOSE_NOTIFY { - log::debug!("REALITY CLIENT: Received close_notify alert"); - self.received_close_notify = true; - // Per RFC 8446: "Any data received after a closure alert - // has been received MUST be ignored." - return Ok(()); - } else if alert_level != ALERT_LEVEL_WARNING { - // Fatal alert - connection must be terminated - log::warn!( - "REALITY CLIENT: Received fatal alert: level={}, desc={}", - alert_level, - alert_desc - ); - return Err(io::Error::new( - io::ErrorKind::ConnectionAborted, - format!("received fatal alert: {}", alert_desc), - )); - } else { - log::debug!( - "REALITY CLIENT: Received warning alert: desc={}", - alert_desc - ); - } - } - } - // CONTENT_TYPE_HANDSHAKE is invalid after handshake complete - // strip_content_type() validates and returns error for invalid types - _ => unreachable!( - "strip_content_type validates content type; unexpected: 0x{:02x}", - content_type - ), - } - - // Consume the processed record from the buffer (after plaintext borrow ends) - self.ciphertext_read_buf.consume(total_record_len); - } - - Ok(()) - } - - /// Get a reader for accessing decrypted plaintext - pub fn reader(&mut self) -> RealityReader<'_> { - // SlideBuffer handles compaction internally via maybe_compact() - // Compact before returning reader if we've consumed significant data - self.plaintext_read_buf.maybe_compact(4096); - RealityReader::new(&mut self.plaintext_read_buf, self.received_close_notify) - } - - /// Get a writer for buffering plaintext to be encrypted - pub fn writer(&mut self) -> RealityWriter<'_> { - RealityWriter::new( - &mut self.plaintext_write_buf, - self.ciphertext_write_buf.len(), - ) - } - - /// Write buffered TLS messages to the provided writer - /// - /// Large plaintext is automatically fragmented into multiple TLS records - /// to comply with the TLS 1.3 record size limit. - pub fn write_tls(&mut self, wr: &mut dyn Write) -> io::Result { - // If handshake not complete, just write buffered handshake data - if !matches!(self.handshake_state, HandshakeState::Complete) { - let n = wr.write(&self.ciphertext_write_buf)?; - self.ciphertext_write_buf.drain(..n); - return Ok(n); - } - - // Encrypt any pending plaintext (with automatic fragmentation for large data) - if !self.plaintext_write_buf.is_empty() { - let (app_write_key, app_write_iv) = match (&self.app_write_key, &self.app_write_iv) { - (Some(key), Some(iv)) => (key, iv), - _ => { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Application keys not available", - )); - } - }; - - let mut encryptor = - RecordEncryptor::new(app_write_key, app_write_iv, &mut self.write_seq); - encryptor.encrypt_app_data( - &mut self.plaintext_write_buf, - &mut self.ciphertext_write_buf, - )?; - } - - let n = wr.write(&self.ciphertext_write_buf)?; - self.ciphertext_write_buf.drain(..n); - Ok(n) - } - - /// Check if the connection wants to write data - pub fn wants_write(&self) -> bool { - !self.ciphertext_write_buf.is_empty() || !self.plaintext_write_buf.is_empty() - } - - /// Check if handshake is still in progress - pub fn is_handshaking(&self) -> bool { - !matches!(self.handshake_state, HandshakeState::Complete) - } - - pub fn negotiated_group(&self) -> Option { - if self.is_handshaking() { - None - } else { - self.negotiated_group - } - } - - /// Check if the connection wants to read more TLS data - /// - /// Returns true if we need more data to make progress (handshake or decryption). - /// This mirrors rustls::Connection::wants_read(). - pub fn wants_read(&self) -> bool { - // Don't read more after receiving close_notify (RFC 8446) - if self.received_close_notify { - return false; - } - - // Don't read more if we're in a fatal error state - if self.fatal_error.is_some() { - return false; - } - - // During handshake, we always want to read - if self.is_handshaking() { - return true; - } - - // After handshake, we want to read if: - // 1. Plaintext buffer is empty (need more application data), OR - // 2. Ciphertext buffer has incomplete records that need more data - // - // Note: If plaintext buffer has data, the caller should consume it first. - // If ciphertext buffer has complete records, process_new_packets should be called. - self.plaintext_read_buf.is_empty() - } - - /// Queue a close notification alert - pub fn send_close_notify(&mut self) { - // In TLS 1.3, alerts must be encrypted like application data - if !matches!(self.handshake_state, HandshakeState::Complete) { - log::debug!("REALITY CLIENT: Cannot send close_notify - handshake not complete"); - return; - } - - // Get application keys - let (app_write_key, app_write_iv) = match (&self.app_write_key, &self.app_write_iv) { - (Some(key), Some(iv)) => (key, iv), - _ => { - log::debug!( - "REALITY CLIENT: Cannot send close_notify - application keys not available" - ); - return; - } - }; - - // Encrypt close_notify alert using RecordEncryptor - let mut encryptor = RecordEncryptor::new(app_write_key, app_write_iv, &mut self.write_seq); - match encryptor.encrypt_close_notify(&mut self.ciphertext_write_buf) { - Ok(()) => { - log::debug!("REALITY CLIENT: Encrypted close_notify alert queued"); - } - Err(e) => { - log::error!("REALITY CLIENT: Failed to encrypt close_notify: {}", e); - } - } - } -} - -#[inline] -pub fn feed_reality_client_connection( - client_connection: &mut RealityClientConnection, - data: &[u8], -) -> std::io::Result<()> { - let mut cursor = std::io::Cursor::new(data); - let mut i = 0; - while i < data.len() { - let n = client_connection.read_tls(&mut cursor).map_err(|e| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("failed to feed TLS connection: {e}"), - ) - })?; - i += n; - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - fn fragmented_server_flight( - mutate: impl FnOnce(&mut Vec), - record_fragment: usize, - ) -> io::Result<()> { - use crate::reality::{ - RealityServerConnection, decode_mldsa65_verify, generate_mldsa65_keypair, - mldsa65_signing_key, - }; - let cipher = CipherSuite::AES_128_GCM_SHA256; - let (mut cc, mut sc) = super::super::reality_pq_tests::configs(cipher); - let (seed, verify) = generate_mldsa65_keypair().unwrap(); - sc.mldsa65_key = Some(mldsa65_signing_key(&seed).unwrap()); - cc.mldsa65_verify = Some(decode_mldsa65_verify(&verify).unwrap()); - let mut client = RealityClientConnection::new(cc)?; - let mut server = RealityServerConnection::new(sc)?; - let mut hello = Vec::new(); - client.write_tls(&mut hello)?; - server.validate_client_hello(&hello)?; - server.build_server_response(&crate::reality::default_target_records(&hello[44..76]))?; - let mut flight = Vec::new(); - server.write_tls(&mut flight)?; - let hello_len = 5 + u16::from_be_bytes([flight[3], flight[4]]) as usize; - client.read_tls(&mut &flight[..hello_len])?; - client.process_new_packets()?; - let HandshakeState::ProcessingHandshake { - server_handshake_traffic_secret, - .. - } = &client.handshake_state - else { - panic!("expected ServerHello") - }; - let (key, iv) = derive_traffic_keys(server_handshake_traffic_secret, cipher)?; - let encrypted_start = hello_len + 6; - let encrypted = &flight[encrypted_start..]; - let len = u16::from_be_bytes([encrypted[3], encrypted[4]]); - let mut plaintext = decrypt_handshake_message(cipher, &key, &iv, 0, &encrypted[5..], len)?; - mutate(&mut plaintext); - let aead = AeadKey::new(cipher, &key)?; - let mut seq = 0; - let mut encryptor = RecordEncryptor::new(&aead, &iv, &mut seq); - let mut fragmented = Vec::new(); - for chunk in plaintext.chunks(record_fragment) { - encryptor.encrypt_handshake(chunk, &mut fragmented)?; - } - for chunk in fragmented.chunks(31) { - client.read_tls(&mut &chunk[..])?; - if let Err(error) = client.process_new_packets() { - assert!(client.is_handshaking()); - assert_eq!(client.negotiated_group(), None); - assert!(client.app_read_key.is_none()); - assert!(client.app_write_key.is_none()); - let mut output = Vec::new(); - client.write_tls(&mut output).unwrap(); - assert!(output.is_empty()); - return Err(error); - } - } - assert!(!client.is_handshaking()); - Ok(()) - } - - #[test] - fn mldsa_certificate_across_tls_records() { - fragmented_server_flight(|_| {}, 47).unwrap(); - } - - #[test] - fn server_finished_must_verify() { - let error = fragmented_server_flight(|plaintext| *plaintext.last_mut().unwrap() ^= 1, 47) - .unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::PermissionDenied); - assert!(error.to_string().contains("Finished")); - } - - #[test] - fn out_of_order_server_handshake_messages_are_rejected() { - for message_index in 0..4 { - let error = fragmented_server_flight( - |plaintext| { - let mut offset = 0; - for _ in 0..message_index { - let len = u32::from_be_bytes([ - 0, - plaintext[offset + 1], - plaintext[offset + 2], - plaintext[offset + 3], - ]) as usize; - offset += 4 + len; - } - plaintext[offset] = if message_index == 0 { - HANDSHAKE_TYPE_CERTIFICATE - } else { - HANDSHAKE_TYPE_ENCRYPTED_EXTENSIONS - }; - }, - 47, - ) - .unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::InvalidData); - assert_eq!(error.to_string(), "Unexpected REALITY handshake message"); - } - } - - #[test] - fn trailing_server_handshake_plaintext_is_rejected() { - let error = - fragmented_server_flight(|plaintext| plaintext.push(0), usize::MAX).unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::InvalidData); - assert_eq!(error.to_string(), "Trailing handshake plaintext"); - } - - #[test] - fn server_hello_must_echo_session_and_select_offered_cipher() { - use super::super::reality_pq_tests::{configs, target_records}; - - for mismatch_session in [false, true] { - let (cc, _) = configs(CipherSuite::AES_128_GCM_SHA256); - let mut client = RealityClientConnection::new(cc).unwrap(); - let mut hello = Vec::new(); - client.write_tls(&mut hello).unwrap(); - let mut session = hello[44..76].to_vec(); - let cipher = if mismatch_session { - session[0] ^= 1; - CipherSuite::AES_128_GCM_SHA256 - } else { - CipherSuite::AES_256_GCM_SHA384 - }; - let records = target_records(RealityGroup::X25519MlKem768, cipher, &session); - client.read_tls(&mut records[0].as_ref()).unwrap(); - let error = client.process_new_packets().unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::InvalidData); - assert_eq!( - error.to_string(), - if mismatch_session { - "ServerHello session ID mismatch" - } else { - "Server selected unoffered cipher suite" - } - ); - assert!(client.is_handshaking()); - assert_eq!(client.negotiated_group(), None); - assert!(client.app_read_key.is_none()); - assert!(client.app_write_key.is_none()); - } - } - - #[test] - fn default_client_offers_hybrid_before_x25519() { - use crate::buf_reader::BufReader; - - let (cc, _) = super::super::reality_pq_tests::configs(CipherSuite::AES_128_GCM_SHA256); - let mut client = RealityClientConnection::new(cc).unwrap(); - let mut hello = Vec::new(); - client.write_tls(&mut hello).unwrap(); - let mut reader = BufReader::new(&hello); - reader.skip(43).unwrap(); - let session_len = reader.read_u8().unwrap() as usize; - reader.skip(session_len).unwrap(); - let cipher_len = reader.read_u16_be().unwrap() as usize; - reader.skip(cipher_len).unwrap(); - let compression_len = reader.read_u8().unwrap() as usize; - reader.skip(compression_len).unwrap(); - let extensions_len = reader.read_u16_be().unwrap() as usize; - assert_eq!(extensions_len, reader.remaining()); - let mut groups = None; - let mut shares = None; - while !reader.is_consumed() { - let id = reader.read_u16_be().unwrap(); - let len = reader.read_u16_be().unwrap() as usize; - let data = reader.read_slice(len).unwrap(); - match id { - 10 => groups = Some(data), - 51 => shares = Some(data), - _ => {} - } - } - assert_eq!(groups.unwrap(), &[0, 4, 0x11, 0xec, 0, 0x1d]); - let mut shares = BufReader::new(shares.unwrap()); - let len = shares.read_u16_be().unwrap() as usize; - assert_eq!(len, shares.remaining()); - for (group, size) in [(0x11ec, 1216), (0x001d, 32)] { - assert_eq!(shares.read_u16_be().unwrap(), group); - assert_eq!(shares.read_u16_be().unwrap(), size); - shares.skip(size as usize).unwrap(); - } - assert!(shares.is_consumed()); - } - - #[test] - fn single_share_and_distinct_auth_keys_complete_handshake() { - use super::super::RealityServerConnection; - use super::super::reality_pq_tests::{configs, target_records}; - - for (group, distinct_auth_key) in [ - (RealityGroup::X25519, false), - (RealityGroup::X25519MlKem768, false), - (RealityGroup::X25519MlKem768, true), - ] { - let cipher = CipherSuite::AES_128_GCM_SHA256; - let (cc, sc) = configs(cipher); - let mut client = RealityClientConnection::new(cc.clone()).unwrap(); - let HandshakeState::AwaitingServerHello { - client_hello_bytes, - client_private_key, - mlkem_private, - auth_key, - } = &mut client.handshake_state - else { - unreachable!(); - }; - let public = - agreement::PrivateKey::from_private_key(&agreement::X25519, client_private_key) - .unwrap() - .compute_public_key() - .unwrap(); - let mut hybrid = mlkem_private - .as_ref() - .unwrap() - .encapsulation_key() - .unwrap() - .key_bytes() - .unwrap() - .as_ref() - .to_vec(); - hybrid.extend_from_slice(public.as_ref()); - let auth_private = [8; 32]; - let auth_public = - agreement::PrivateKey::from_private_key(&agreement::X25519, &auth_private) - .unwrap() - .compute_public_key() - .unwrap(); - let mut shares = vec![KeyShareRef { - group, - data: if group == RealityGroup::X25519 { - public.as_ref() - } else { - &hybrid - }, - }]; - let random: [u8; 32] = client_hello_bytes[6..38].try_into().unwrap(); - if distinct_auth_key { - shares.push(KeyShareRef { - group: RealityGroup::X25519, - data: auth_public.as_ref(), - }); - let shared = perform_ecdh(&auth_private, &cc.public_key).unwrap(); - *auth_key = derive_auth_key(&shared, &random[..20], b"REALITY").unwrap(); - } - let mut hello = construct_client_hello( - &random, - &[0; 32], - &shares, - &cc.server_name, - &[cipher.id()], - DEFAULT_ALPN_PROTOCOLS, - ) - .unwrap(); - let mut metadata = [0; 16]; - metadata[..4].copy_from_slice(&[1, 8, 0, 0]); - metadata[8..].copy_from_slice(&cc.short_id); - let session = encrypt_session_id(&metadata, auth_key, &random[20..], &hello).unwrap(); - hello[39..71].copy_from_slice(&session); - *client_hello_bytes = hello.clone(); - client.ciphertext_write_buf = - write_record_header(CONTENT_TYPE_HANDSHAKE, hello.len() as u16); - client.ciphertext_write_buf.extend_from_slice(&hello); - - let mut server = RealityServerConnection::new(sc).unwrap(); - let mut wire = Vec::new(); - client.write_tls(&mut wire).unwrap(); - server.validate_client_hello(&wire).unwrap(); - server - .build_server_response(&target_records(group, cipher, &session)) - .unwrap(); - wire.clear(); - server.write_tls(&mut wire).unwrap(); - client.read_tls(&mut wire.as_slice()).unwrap(); - client.process_new_packets().unwrap(); - wire.clear(); - client.write_tls(&mut wire).unwrap(); - server.read_tls(&mut wire.as_slice()).unwrap(); - server.process_new_packets().unwrap(); - assert_eq!(client.negotiated_group(), Some(group)); - assert_eq!(server.negotiated_group(), Some(group)); - - client.writer().write_all(b"request").unwrap(); - wire.clear(); - client.write_tls(&mut wire).unwrap(); - server.read_tls(&mut wire.as_slice()).unwrap(); - server.process_new_packets().unwrap(); - let mut request = [0; 7]; - server.reader().read_exact(&mut request).unwrap(); - assert_eq!(&request, b"request"); - } - } - - #[test] - fn handshake_key_material_is_not_logged() { - let private = - agreement::PrivateKey::from_private_key(&agreement::X25519, &[1; 32]).unwrap(); - let mut client = RealityClientConnection::new(RealityClientConfig { - mldsa65_verify: None, - public_key: private - .compute_public_key() - .unwrap() - .as_ref() - .try_into() - .unwrap(), - short_id: [2; 8], - server_name: "localhost".into(), - cipher_suites: vec![], + let connection = + rustls::ClientConnection::new_reality(Arc::new(tls), name, Box::new(hooks)) + .map_err(io_error)?; + Ok(Self { + transport: RealityTransport::new(connection.into()), }) - .unwrap(); - let cipher = CipherSuite::AES_128_GCM_SHA256; - let secret = vec![0xab; 32]; - let (key, iv) = derive_traffic_keys(&secret, cipher).unwrap(); - client.handshake_state = HandshakeState::ProcessingHandshake { - client_handshake_traffic_secret: vec![3; 32], - server_handshake_traffic_secret: secret, - master_secret: vec![4; 32], - cipher_suite: cipher, - handshake_transcript_bytes: vec![], - auth_key: [5; 32], - handshake_seq: 0, - accumulated_plaintext: vec![], - parsed_plaintext: 0, - messages_found: 0, - certificate_verified: false, - ed25519_public_key: None, - cert_verify_offset: None, - }; - let capture = crate::logging::test_capture::Capture::new(); - assert!(!client.process_encrypted_handshake().unwrap()); - let logs = capture.finish(); - assert!(!logs.contains(&format!("{:02x?}", key))); - assert!(!logs.contains(&format!("{:02x?}", iv))); } - #[test] - fn handshake_plaintext_is_bounded() { - let mut accumulated = vec![0; MAX_HANDSHAKE_PLAINTEXT]; - - let error = append_handshake_plaintext(&mut accumulated, &[0]).unwrap_err(); - - assert_eq!(error.kind(), io::ErrorKind::InvalidData); - assert_eq!(accumulated.len(), MAX_HANDSHAKE_PLAINTEXT); - } - - #[test] - fn client_hello_transcript_bytes_use_encrypted_session_id() { - let server_private = [0x42u8; 32]; - let server_private_key = - agreement::PrivateKey::from_private_key(&agreement::X25519, &server_private).unwrap(); - let server_public_key = server_private_key.compute_public_key().unwrap(); - let mut server_public = [0u8; 32]; - server_public.copy_from_slice(server_public_key.as_ref()); - - let config = RealityClientConfig { - mldsa65_verify: None, - public_key: server_public, - short_id: [1, 2, 3, 4, 5, 6, 7, 8], - server_name: "example.com".to_string(), - cipher_suites: vec![], - }; - - let mut conn = RealityClientConnection::new(config).unwrap(); - let stored_client_hello = match &conn.handshake_state { - HandshakeState::AwaitingServerHello { - client_hello_bytes, .. - } => client_hello_bytes.clone(), - _ => panic!("new client must be awaiting ServerHello"), - }; - - let mut wire = Vec::new(); - conn.write_tls(&mut wire).unwrap(); - - assert_eq!(&wire[5..], stored_client_hello.as_slice()); - assert_ne!( - &stored_client_hello[39..71], - &[0u8; 32], - "transcript ClientHello must retain encrypted wire SessionId" - ); - } + delegate_tls!(); +} + +pub fn feed_reality_client_connection( + connection: &mut RealityClientConnection, + data: &[u8], +) -> io::Result<()> { + connection.transport.feed(data) } diff --git a/src/reality/reality_client_verify.rs b/src/reality/reality_client_verify.rs index 01452a4b..0216684e 100644 --- a/src/reality/reality_client_verify.rs +++ b/src/reality/reality_client_verify.rs @@ -3,6 +3,7 @@ use std::io; use aws_lc_rs::hmac; +#[cfg(test)] use aws_lc_rs::signature::{ED25519, UnparsedPublicKey}; use subtle::ConstantTimeEq; use x509_parser::certificate::X509Certificate; @@ -56,6 +57,7 @@ pub fn verify_certificate_mldsa( /// - extensions data /// #[inline] +#[cfg(test)] pub fn extract_certificate_der(certificate_message: &[u8]) -> io::Result<&[u8]> { // Skip handshake header (type + 3-byte length) if certificate_message.len() < 4 { @@ -125,13 +127,19 @@ pub fn extract_certificate_der(certificate_message: &[u8]) -> io::Result<&[u8]> /// Uses x509-parser for robust extraction. #[inline] pub fn verify_certificate_hmac(cert_der: &[u8], auth_key: &[u8; 32]) -> io::Result<()> { - let (_, cert) = X509Certificate::from_der(cert_der).map_err(|e| { + let (remaining, cert) = X509Certificate::from_der(cert_der).map_err(|e| { io::Error::new( io::ErrorKind::InvalidData, format!("Failed to parse X.509 certificate: {}", e), ) })?; + if !remaining.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "Trailing certificate bytes", + )); + } let spki = cert.public_key(); let pubkey_data: &[u8] = &spki.subject_public_key.data; let signature: &[u8] = &cert.signature_value.data; @@ -243,6 +251,7 @@ pub fn extract_ed25519_public_key(cert_der: &[u8]) -> io::Result<[u8; 32]> { /// /// Returns the signature bytes. #[inline] +#[cfg(test)] pub fn extract_certificate_verify_signature(cert_verify_message: &[u8]) -> io::Result> { // Minimum: 1 (type) + 3 (len) + 2 (alg) + 2 (sig len) + 64 (ed25519 sig) = 72 if cert_verify_message.len() < 72 { @@ -317,6 +326,7 @@ pub fn extract_certificate_verify_signature(cert_verify_message: &[u8]) -> io::R /// * `signature` - The signature from CertificateVerify message (64 bytes) /// * `transcript_hash` - Hash of handshake messages up to (but not including) CertificateVerify #[inline] +#[cfg(test)] pub fn verify_certificate_verify_signature( public_key: &[u8; 32], signature: &[u8], diff --git a/src/reality/reality_connection.rs b/src/reality/reality_connection.rs new file mode 100644 index 00000000..12339fb9 --- /dev/null +++ b/src/reality/reality_connection.rs @@ -0,0 +1,177 @@ +use std::io::{self, Read, Write}; + +use super::reality_io_state::RealityIoState; +#[cfg(test)] +use super::reality_key_exchange::RealityGroup; +use super::reality_reader_writer::{RealityReader, RealityWriter}; +#[cfg(test)] +use super::reality_rustls::group; +use super::reality_rustls::io_error; + +#[derive(Default)] +pub(super) struct RealityTransport { + pub(super) inner: Option, + pub(super) prefix: bytes::Bytes, + failed: Option, +} + +impl RealityTransport { + pub(super) fn new(mut connection: rustls::Connection) -> Self { + connection.set_buffer_limit(Some(super::common::OUTGOING_BUFFER_LIMIT)); + Self { + inner: Some(connection), + prefix: bytes::Bytes::new(), + failed: None, + } + } + + pub(super) fn read_tls(&mut self, rd: &mut dyn Read) -> io::Result { + if let Some(kind) = self.failed { + return Err(kind.into()); + } + self.inner + .as_mut() + .ok_or(io::ErrorKind::WouldBlock)? + .read_tls(rd) + } + + pub(super) fn process_new_packets(&mut self) -> io::Result { + if let Some(kind) = self.failed { + return Err(kind.into()); + } + let Some(connection) = &mut self.inner else { + return Ok(RealityIoState::new(0)); + }; + match connection.process_new_packets() { + Ok(state) => Ok(RealityIoState::new(state.plaintext_bytes_to_read())), + Err(error) => { + let error = io_error(error); + self.failed = Some(error.kind()); + // Never expose queued plaintext or a TLS alert after failed REALITY authentication. + self.inner = None; + self.prefix = bytes::Bytes::new(); + Err(error) + } + } + } + + pub(super) fn feed(&mut self, mut data: &[u8]) -> io::Result<()> { + while !data.is_empty() { + if self.read_tls(&mut data)? == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "REALITY TLS input made no progress", + )); + } + self.process_new_packets()?; + } + Ok(()) + } + + pub(super) fn write_tls(&mut self, wr: &mut dyn Write) -> io::Result { + if !self.prefix.is_empty() { + let written = wr.write(&self.prefix)?; + let _ = self.prefix.split_to(written); + return Ok(written); + } + self.inner + .as_mut() + .map_or(Ok(0), |connection| connection.write_tls(wr)) + } + + pub(super) fn reader(&mut self) -> RealityReader<'_> { + let available = self + .inner + .as_mut() + .filter(|connection| !connection.is_handshaking()); + RealityReader::new(available.map(|connection| connection.reader()), self.failed) + } + + pub(super) fn writer(&mut self) -> RealityWriter<'_> { + let available = self + .inner + .as_mut() + .filter(|connection| !connection.is_handshaking()); + RealityWriter::new(available.map(|connection| connection.writer()), self.failed) + } + + pub(super) fn wants_write(&self) -> bool { + !self.prefix.is_empty() + || self + .inner + .as_ref() + .is_some_and(|connection| connection.wants_write()) + } + pub(super) fn wants_read(&self) -> bool { + self.failed.is_none() + && self + .inner + .as_ref() + .is_none_or(|connection| connection.wants_read()) + } + pub(super) fn is_handshaking(&self) -> bool { + self.inner + .as_ref() + .is_none_or(|connection| connection.is_handshaking()) + } + #[cfg(test)] + pub(super) fn negotiated_group(&self) -> Option { + self.inner + .as_ref()? + .negotiated_key_exchange_group() + .and_then(|kx| group(kx.name())) + } + pub(super) fn send_close_notify(&mut self) { + if let Some(connection) = &mut self.inner { + connection.send_close_notify(); + } + } + + #[cfg(test)] + pub(super) fn refresh_traffic_keys(&mut self) -> io::Result<()> { + self.inner + .as_mut() + .ok_or(io::ErrorKind::NotConnected)? + .refresh_traffic_keys() + .map_err(io_error) + } +} + +macro_rules! delegate_tls { + () => { + pub fn read_tls(&mut self, reader: &mut dyn std::io::Read) -> std::io::Result { + self.transport.read_tls(reader) + } + pub fn write_tls(&mut self, writer: &mut dyn std::io::Write) -> std::io::Result { + self.transport.write_tls(writer) + } + pub fn process_new_packets( + &mut self, + ) -> std::io::Result { + self.transport.process_new_packets() + } + pub fn reader(&mut self) -> super::reality_reader_writer::RealityReader<'_> { + self.transport.reader() + } + pub fn writer(&mut self) -> super::reality_reader_writer::RealityWriter<'_> { + self.transport.writer() + } + pub fn wants_write(&self) -> bool { + self.transport.wants_write() + } + pub fn wants_read(&self) -> bool { + self.transport.wants_read() + } + pub fn is_handshaking(&self) -> bool { + self.transport.is_handshaking() + } + #[cfg(test)] + pub fn negotiated_group(&self) -> Option { + self.transport.negotiated_group() + } + pub fn send_close_notify(&mut self) { + self.transport.send_close_notify(); + } + }; +} +pub(super) use delegate_tls; diff --git a/src/reality/reality_key_exchange.rs b/src/reality/reality_key_exchange.rs index f937dbf0..764ccb63 100644 --- a/src/reality/reality_key_exchange.rs +++ b/src/reality/reality_key_exchange.rs @@ -1,8 +1,12 @@ use std::io; -use aws_lc_rs::{agreement, kem}; +#[cfg(test)] +use aws_lc_rs::agreement; +use aws_lc_rs::kem; +#[cfg(test)] use rand::Rng; +#[cfg(test)] use super::reality_auth::perform_ecdh; use crate::buf_reader::BufReader; @@ -25,13 +29,7 @@ pub enum RealityGroup { } impl RealityGroup { - pub fn name(self) -> &'static str { - match self { - Self::X25519 => "X25519", - Self::X25519MlKem768 => "X25519MLKEM768", - } - } - + #[cfg(test)] pub fn secret_len(self) -> usize { match self { Self::X25519 => 32, @@ -56,6 +54,7 @@ impl RealityGroup { } } +#[cfg(test)] pub struct KeyShareRef<'a> { pub group: RealityGroup, pub data: &'a [u8], @@ -78,6 +77,7 @@ impl ClientKeyShares { .ok_or_else(|| invalid("Missing REALITY authentication key share")) } + #[cfg(test)] pub fn get(&self, group: RealityGroup) -> io::Result<&[u8]> { match group { RealityGroup::X25519 => self.x25519.as_ref().map(|k| k.as_slice()), @@ -194,16 +194,16 @@ fn parse_client_shares(data: &[u8]) -> io::Result { Ok(shares) } -pub fn extract_server_key_share(record: &[u8]) -> io::Result> { +pub fn extract_server_key_share(record: &[u8]) -> io::Result<()> { let mut reader = BufReader::new(key_share_extension(record, false)?); let group = RealityGroup::from_id(reader.read_u16_be()?) .ok_or_else(|| invalid("Unsupported REALITY server key share"))?; let len = reader.read_u16_be()? as usize; - let data = reader.read_slice(len)?; + reader.skip(len)?; if !reader.is_consumed() || len != group.share_len(false) { return Err(invalid("Invalid server key share length")); } - Ok(KeyShareRef { group, data }) + Ok(()) } pub fn generate_mlkem() -> io::Result<(kem::DecapsulationKey, Vec)> { @@ -216,6 +216,7 @@ pub fn generate_mlkem() -> io::Result<(kem::DecapsulationKey, Vec)> { Ok((private, public.as_ref().to_vec())) } +#[cfg(test)] pub fn complete_client_exchange( private: &[u8; 32], mlkem: &kem::DecapsulationKey, @@ -243,6 +244,7 @@ pub fn complete_client_exchange( Ok(secret) } +#[cfg(test)] pub fn server_exchange( group: RealityGroup, shares: &ClientKeyShares, diff --git a/src/reality/reality_pq_tests.rs b/src/reality/reality_pq_tests.rs index bd4d712e..3ed65b00 100644 --- a/src/reality/reality_pq_tests.rs +++ b/src/reality/reality_pq_tests.rs @@ -114,15 +114,15 @@ fn handshake( for (actual, expected) in records.iter().zip(&target) { assert_eq!(actual.len(), expected.len()); } + let share_start = target[0].len() - group.share_len(false); + assert_eq!(&records[0][..share_start], &target[0][..share_start]); for chunk in response.chunks(fragment) { - client.read_tls(&mut &chunk[..]).unwrap(); - client.process_new_packets().unwrap(); + feed_reality_client_connection(&mut client, chunk).unwrap(); } let mut finished = Vec::new(); client.write_tls(&mut finished).unwrap(); for chunk in finished.chunks(fragment) { - server.read_tls(&mut &chunk[..]).unwrap(); - server.process_new_packets().unwrap(); + feed_reality_server_connection(&mut server, chunk).unwrap(); } assert!(!client.is_handshaking()); assert!(!server.is_handshaking()); @@ -131,6 +131,41 @@ fn handshake( (client, server) } +pub(crate) fn established_pair() -> (RealityClientConnection, RealityServerConnection) { + let (client, server) = configs(CipherSuite::AES_128_GCM_SHA256); + handshake( + client, + server, + RealityGroup::X25519MlKem768, + target_records, + 37, + ) +} + +#[test] +fn reality_separate_and_observed_trailing_record_without_mldsa() { + for &cipher in DEFAULT_CIPHER_SUITES { + for group in [RealityGroup::X25519, RealityGroup::X25519MlKem768] { + let (cc, sc) = configs(cipher); + handshake(cc, sc, group, separate_target_records, 1); + let (cc, sc) = configs(cipher); + handshake( + cc, + sc, + group, + |group, cipher, session| { + let mut records = separate_target_records(group, cipher, session); + let mut trailing = write_record_header(23, 59); + trailing.resize(64, 0); + records.push(trailing.into()); + records + }, + 17, + ); + } + } +} + #[test] fn reality_pq_handshake_and_data_all_suites() { for &cipher in DEFAULT_CIPHER_SUITES { @@ -147,8 +182,7 @@ fn reality_pq_handshake_and_data_all_suites() { } let mut actual = Vec::new(); for chunk in wire.chunks(1024) { - server.read_tls(&mut &chunk[..]).unwrap(); - server.process_new_packets().unwrap(); + feed_reality_server_connection(&mut server, chunk).unwrap(); let mut buffer = [0; 16384]; loop { match server.reader().read(&mut buffer) { @@ -163,16 +197,14 @@ fn reality_pq_handshake_and_data_all_suites() { server.writer().write_all(b"response").unwrap(); wire.clear(); server.write_tls(&mut wire).unwrap(); - client.read_tls(&mut wire.as_slice()).unwrap(); - client.process_new_packets().unwrap(); + feed_reality_client_connection(&mut client, &wire).unwrap(); let mut response = [0; 8]; client.reader().read_exact(&mut response).unwrap(); assert_eq!(&response, b"response"); client.send_close_notify(); wire.clear(); client.write_tls(&mut wire).unwrap(); - server.read_tls(&mut wire.as_slice()).unwrap(); - server.process_new_packets().unwrap(); + feed_reality_server_connection(&mut server, &wire).unwrap(); assert_eq!(server.reader().read(&mut response).unwrap(), 0); } } @@ -215,9 +247,10 @@ fn reality_pq_mldsa_required_fails_closed() { .unwrap(); let mut flight = Vec::new(); server.write_tls(&mut flight).unwrap(); - client.read_tls(&mut flight.as_slice()).unwrap(); assert_eq!( - client.process_new_packets().unwrap_err().kind(), + feed_reality_client_connection(&mut client, &flight) + .unwrap_err() + .kind(), std::io::ErrorKind::PermissionDenied ); assert!(client.is_handshaking()); diff --git a/src/reality/reality_reader_writer.rs b/src/reality/reality_reader_writer.rs index d3c0e211..6ad71a95 100644 --- a/src/reality/reality_reader_writer.rs +++ b/src/reality/reality_reader_writer.rs @@ -1,174 +1,63 @@ -use std::io::{BufRead, Read, Write}; +use std::io::{self, BufRead, Read, Write}; -use super::common::OUTGOING_BUFFER_LIMIT; -use crate::slide_buffer::SlideBuffer; - -/// Reader for accessing decrypted plaintext from REALITY connections -/// -/// This reader provides a view over a SlideBuffer and consumes data from it -/// as it is read. The SlideBuffer handles efficient memory management. -/// -/// Mirrors rustls::Reader behavior for fill_buf(): -/// - Ok(data) when data is available -/// - Ok(&[]) when close_notify received (clean EOF) -/// - Err(WouldBlock) when no data and connection still active pub struct RealityReader<'a> { - buffer: &'a mut SlideBuffer, - received_close_notify: bool, + inner: Option>, + failed: Option, } impl<'a> RealityReader<'a> { - pub fn new(buffer: &'a mut SlideBuffer, received_close_notify: bool) -> Self { - RealityReader { - buffer, - received_close_notify, + pub(super) fn new(inner: Option>, failed: Option) -> Self { + Self { inner, failed } + } +} + +impl Read for RealityReader<'_> { + fn read(&mut self, buffer: &mut [u8]) -> io::Result { + self.inner + .as_mut() + .ok_or(self.failed.unwrap_or(io::ErrorKind::WouldBlock))? + .read(buffer) + } +} + +impl BufRead for RealityReader<'_> { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + self.inner + .as_mut() + .ok_or(self.failed.unwrap_or(io::ErrorKind::WouldBlock))? + .fill_buf() + } + + fn consume(&mut self, amount: usize) { + if let Some(reader) = &mut self.inner { + reader.consume(amount); } } } -impl<'a> Read for RealityReader<'a> { - fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - let available = self.buffer.len(); - let to_read = buf.len().min(available); - if to_read > 0 { - buf[..to_read].copy_from_slice(&self.buffer[..to_read]); - self.buffer.consume(to_read); - } - Ok(to_read) - } -} - -impl<'a> BufRead for RealityReader<'a> { - fn fill_buf(&mut self) -> std::io::Result<&[u8]> { - if !self.buffer.is_empty() { - // Data available - Ok(self.buffer.as_slice()) - } else if self.received_close_notify { - // Clean EOF - close_notify received (mirrors rustls behavior) - Ok(&[]) - } else { - // No data, connection still active - Err(std::io::ErrorKind::WouldBlock.into()) - } - } - - fn consume(&mut self, amt: usize) { - let actual = amt.min(self.buffer.len()); - self.buffer.consume(actual); - } -} - -/// Writer for buffering plaintext to be encrypted in REALITY connections pub struct RealityWriter<'a> { - buffer: &'a mut Vec, - pending_tls_bytes: usize, + inner: Option>, + failed: Option, } impl<'a> RealityWriter<'a> { - pub fn new(buffer: &'a mut Vec, pending_tls_bytes: usize) -> Self { - RealityWriter { - buffer, - pending_tls_bytes, - } + pub(super) fn new(inner: Option>, failed: Option) -> Self { + Self { inner, failed } } } -impl<'a> Write for RealityWriter<'a> { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - let pending_bytes = self.pending_tls_bytes.saturating_add(self.buffer.len()); - let accepted = buf - .len() - .min(OUTGOING_BUFFER_LIMIT.saturating_sub(pending_bytes)); - self.buffer.extend_from_slice(&buf[..accepted]); - Ok(accepted) +impl Write for RealityWriter<'_> { + fn write(&mut self, buffer: &[u8]) -> io::Result { + self.inner + .as_mut() + .ok_or(self.failed.unwrap_or(io::ErrorKind::WouldBlock))? + .write(buffer) } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_reality_crypto_reader() { - let mut buffer = SlideBuffer::new(1024); - buffer.extend_from_slice(b"hello world"); - - { - let mut reader = RealityReader::new(&mut buffer, false); - let mut buf = [0u8; 5]; - assert_eq!(reader.read(&mut buf).unwrap(), 5); - assert_eq!(&buf, b"hello"); + fn flush(&mut self) -> io::Result<()> { + if let Some(kind) = self.failed { + return Err(kind.into()); } - - // Buffer should have consumed 5 bytes - assert_eq!(buffer.len(), 6); // " world" remaining - - { - let mut reader = RealityReader::new(&mut buffer, false); - let mut buf = [0u8; 5]; - assert_eq!(reader.read(&mut buf).unwrap(), 5); - assert_eq!(&buf[..5], b" worl"); - } - - assert_eq!(buffer.len(), 1); // "d" remaining - } - - #[test] - fn test_reality_crypto_reader_bufread() { - let mut buffer = SlideBuffer::new(1024); - buffer.extend_from_slice(b"test data"); - - let mut reader = RealityReader::new(&mut buffer, false); - - let buf = reader.fill_buf().unwrap(); - assert_eq!(buf, b"test data"); - - reader.consume(5); - let buf = reader.fill_buf().unwrap(); - assert_eq!(buf, b"data"); - } - - #[test] - fn test_reality_crypto_reader_empty_would_block() { - let mut buffer = SlideBuffer::new(1024); - // Empty buffer, no close_notify -> WouldBlock - let mut reader = RealityReader::new(&mut buffer, false); - let result = reader.fill_buf(); - assert!(result.is_err()); - assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::WouldBlock); - } - - #[test] - fn test_reality_crypto_reader_close_notify_eof() { - let mut buffer = SlideBuffer::new(1024); - // Empty buffer, close_notify received -> Ok(&[]) (EOF) - let mut reader = RealityReader::new(&mut buffer, true); - let result = reader.fill_buf(); - assert!(result.is_ok()); - assert!(result.unwrap().is_empty()); - } - - #[test] - fn test_reality_crypto_writer() { - let mut buffer = Vec::new(); - let mut writer = RealityWriter::new(&mut buffer, 0); - - assert_eq!(writer.write(b"hello").unwrap(), 5); - assert_eq!(writer.write(b" world").unwrap(), 6); - assert_eq!(buffer.as_slice(), b"hello world"); - } - - #[test] - fn test_reality_crypto_writer_counts_pending_tls_output() { - let mut buffer = Vec::new(); - let mut writer = RealityWriter::new(&mut buffer, OUTGOING_BUFFER_LIMIT - 3); - - assert_eq!(writer.write(b"hello").unwrap(), 3); - assert_eq!(writer.write(b"world").unwrap(), 0); - assert_eq!(buffer.as_slice(), b"hel"); + self.inner.as_mut().map_or(Ok(()), Write::flush) } } diff --git a/src/reality/reality_records.rs b/src/reality/reality_records.rs deleted file mode 100644 index f57e35f6..00000000 --- a/src/reality/reality_records.rs +++ /dev/null @@ -1,1020 +0,0 @@ -// TLS 1.3 record layer encryption/decryption. -// -// Handles framing plaintext into TLS records, including: -// - Adding/stripping ContentType trailer byte -// - Fragmenting large data into multiple records (max 16KB plaintext each) -// - Building TLS record headers -// - Managing sequence numbers - -use std::io::{self, Error, ErrorKind}; - -use super::common::{ - CONTENT_TYPE_ALERT, CONTENT_TYPE_APPLICATION_DATA, CONTENT_TYPE_HANDSHAKE, - MAX_TLS_CIPHERTEXT_LEN, MAX_TLS_PLAINTEXT_LEN, TLS_RECORD_HEADER_SIZE, -}; -use super::reality_aead::AeadKey; -#[cfg(test)] -use super::reality_cipher_suite::CipherSuite; - -/// Encrypts plaintext into TLS 1.3 records. -/// -/// Manages the write-side sequence number and handles record framing. -pub struct RecordEncryptor<'a> { - key: &'a AeadKey, - iv: &'a [u8], - seq: &'a mut u64, -} - -impl<'a> RecordEncryptor<'a> { - #[inline] - pub fn new(key: &'a AeadKey, iv: &'a [u8], seq: &'a mut u64) -> Self { - Self { key, iv, seq } - } - - /// Encrypt application data into TLS 1.3 records. - /// - /// For data <= 16KB: encrypts in-place in the plaintext buffer (zero-copy). - /// For data > 16KB: fragments into multiple records. - /// - /// Clears the plaintext buffer after encryption. - #[inline] - pub fn encrypt_app_data( - &mut self, - plaintext: &mut Vec, - out: &mut Vec, - ) -> io::Result<()> { - if plaintext.is_empty() { - return Ok(()); - } - - if plaintext.len() <= MAX_TLS_PLAINTEXT_LEN { - // Fast path: single record, encrypt in-place - self.encrypt_record_in_place(plaintext, out, CONTENT_TYPE_APPLICATION_DATA)?; - } else { - // Slow path: fragment into multiple records - self.encrypt_fragmented(plaintext, out, CONTENT_TYPE_APPLICATION_DATA)?; - } - - plaintext.clear(); - Ok(()) - } - - /// Encrypt handshake data into TLS 1.3 records. - #[inline] - pub fn encrypt_handshake(&mut self, data: &[u8], out: &mut Vec) -> io::Result<()> { - if data.is_empty() { - return Ok(()); - } - - if data.len() <= MAX_TLS_PLAINTEXT_LEN { - let mut buf = data.to_vec(); - self.encrypt_record_in_place(&mut buf, out, CONTENT_TYPE_HANDSHAKE)?; - } else { - for chunk in data.chunks(MAX_TLS_PLAINTEXT_LEN) { - let mut buf = chunk.to_vec(); - self.encrypt_record_in_place(&mut buf, out, CONTENT_TYPE_HANDSHAKE)?; - } - } - - Ok(()) - } - - /// Encrypt handshake data with padding to match a target record size. - /// - /// Uses TLS 1.3 inner padding (zeros after content type byte) to pad - /// the encrypted record to match the target size from the destination server. - /// - /// If target_size is 0 or smaller than our minimum, no padding is added. - #[inline] - pub fn encrypt_handshake_with_padding( - &mut self, - data: &[u8], - out: &mut Vec, - target_record_size: usize, - ) -> io::Result<()> { - if data.is_empty() { - return Ok(()); - } - - // For very large data, fragment without padding - if data.len() > MAX_TLS_PLAINTEXT_LEN { - // Fragment into multiple records - only pad the last one if needed - let chunks: Vec<_> = data.chunks(MAX_TLS_PLAINTEXT_LEN).collect(); - for (i, chunk) in chunks.iter().enumerate() { - let mut buf = chunk.to_vec(); - if i == chunks.len() - 1 && target_record_size > 0 { - // Last chunk - apply padding - self.encrypt_record_with_padding( - &mut buf, - out, - CONTENT_TYPE_HANDSHAKE, - target_record_size, - )?; - } else { - self.encrypt_record_in_place(&mut buf, out, CONTENT_TYPE_HANDSHAKE)?; - } - } - return Ok(()); - } - - let mut buf = data.to_vec(); - if target_record_size > 0 { - self.encrypt_record_with_padding( - &mut buf, - out, - CONTENT_TYPE_HANDSHAKE, - target_record_size, - )?; - } else { - self.encrypt_record_in_place(&mut buf, out, CONTENT_TYPE_HANDSHAKE)?; - } - - Ok(()) - } - - /// Encrypt a close_notify alert. - #[inline] - pub fn encrypt_close_notify(&mut self, out: &mut Vec) -> io::Result<()> { - let mut buf = vec![0x01, 0x00]; // level=warning, desc=close_notify - self.encrypt_record_in_place(&mut buf, out, CONTENT_TYPE_ALERT) - } - - /// Encrypt a single record in-place. - /// - /// 1. Appends content type byte to buffer - /// 2. Encrypts in-place (appends 16-byte tag) - /// 3. Writes TLS record header + ciphertext to output - /// 4. Increments sequence number - #[inline] - fn encrypt_record_in_place( - &mut self, - buf: &mut Vec, - out: &mut Vec, - content_type: u8, - ) -> io::Result<()> { - // Prevents a full plaintext record from doubling its retained Vec capacity. - buf.reserve_exact(1 + 16); - - // Append inner content type - buf.push(content_type); - - // Build header (need ciphertext length = plaintext + content_type + tag) - let ciphertext_len = buf.len() + 16; - - debug_assert!( - ciphertext_len <= MAX_TLS_CIPHERTEXT_LEN, - "BUG: ciphertext_len {} exceeds MAX_TLS_CIPHERTEXT_LEN {}", - ciphertext_len, - MAX_TLS_CIPHERTEXT_LEN - ); - - let header = make_record_header(ciphertext_len); - - // Encrypt in-place - self.key.seal_in_place(buf, self.iv, *self.seq, &header)?; - *self.seq = self - .seq - .checked_add(1) - .ok_or_else(|| Error::other("TLS sequence number exhausted"))?; - - // Write to output - out.reserve(TLS_RECORD_HEADER_SIZE + buf.len()); - out.extend_from_slice(&header); - out.extend_from_slice(buf); - - Ok(()) - } - - /// Encrypt a single record with padding to match a target size. - /// - /// TLS 1.3 inner plaintext format: [content] [content_type] [zero_padding...] - /// The padding is added after the content type byte and before encryption. - #[inline] - fn encrypt_record_with_padding( - &mut self, - buf: &mut Vec, - out: &mut Vec, - content_type: u8, - target_record_size: usize, - ) -> io::Result<()> { - // Append inner content type - buf.push(content_type); - - // Calculate padding needed to match target record size - // target_record_size = header(5) + inner_plaintext_with_padding + tag(16) - // So: inner_plaintext_with_padding = target_record_size - 5 - 16 = target_record_size - 21 - // Padding = inner_plaintext_with_padding - buf.len() - let current_inner_len = buf.len(); - let target_inner_len = target_record_size.saturating_sub(TLS_RECORD_HEADER_SIZE + 16); - - if target_inner_len > current_inner_len && target_inner_len <= MAX_TLS_PLAINTEXT_LEN + 1 { - let padding = target_inner_len - current_inner_len; - buf.resize(buf.len() + padding, 0); - log::trace!( - "REALITY: Added {} bytes of TLS 1.3 inner padding (target={}, current={})", - padding, - target_record_size, - TLS_RECORD_HEADER_SIZE + current_inner_len + 16 - ); - } - - // Build header with actual ciphertext length - let ciphertext_len = buf.len() + 16; - - debug_assert!( - ciphertext_len <= MAX_TLS_CIPHERTEXT_LEN, - "BUG: ciphertext_len {} exceeds MAX_TLS_CIPHERTEXT_LEN {}", - ciphertext_len, - MAX_TLS_CIPHERTEXT_LEN - ); - - let header = make_record_header(ciphertext_len); - - // Encrypt in-place - self.key.seal_in_place(buf, self.iv, *self.seq, &header)?; - *self.seq = self - .seq - .checked_add(1) - .ok_or_else(|| Error::other("TLS sequence number exhausted"))?; - - // Write to output - out.reserve(TLS_RECORD_HEADER_SIZE + buf.len()); - out.extend_from_slice(&header); - out.extend_from_slice(buf); - - Ok(()) - } - - /// Encrypt data larger than 16KB by fragmenting into multiple records. - #[inline] - fn encrypt_fragmented( - &mut self, - data: &[u8], - out: &mut Vec, - content_type: u8, - ) -> io::Result<()> { - for chunk in data.chunks(MAX_TLS_PLAINTEXT_LEN) { - let mut buf = chunk.to_vec(); - self.encrypt_record_in_place(&mut buf, out, content_type)?; - } - Ok(()) - } -} - -/// Decrypts TLS 1.3 records into plaintext. -/// -/// Manages the read-side sequence number and handles content type extraction. -pub struct RecordDecryptor<'a> { - key: &'a AeadKey, - iv: &'a [u8], - seq: &'a mut u64, -} - -impl<'a> RecordDecryptor<'a> { - #[inline] - pub fn new(key: &'a AeadKey, iv: &'a [u8], seq: &'a mut u64) -> Self { - Self { key, iv, seq } - } - - /// Decrypt a TLS 1.3 record in-place, returning (content_type, plaintext_slice). - /// - /// Zero-allocation decryption: decrypts directly in the provided buffer - /// and returns a slice to the plaintext within that buffer. - /// - /// # Arguments - /// * `ciphertext` - Mutable slice containing ciphertext + auth tag (will be decrypted in-place) - /// * `record_len` - Length from TLS record header (ciphertext + tag length) - /// - /// # Returns - /// Tuple of (content_type, plaintext_slice) where plaintext_slice borrows from ciphertext - #[inline] - pub fn decrypt_record_in_place<'b>( - &mut self, - ciphertext: &'b mut [u8], - record_len: u16, - ) -> io::Result<(u8, &'b [u8])> { - let aad = make_record_header(record_len as usize); - - let plaintext = self - .key - .open_in_place_slice(ciphertext, self.iv, *self.seq, &aad)?; - *self.seq = self - .seq - .checked_add(1) - .ok_or_else(|| Error::other("TLS sequence number exhausted"))?; - - // TLSInnerPlaintext is content || ContentType || zeros*. - // Reference REALITY implementations may add trailing zero padding. - let mut valid_end = plaintext.len(); - while valid_end > 0 && plaintext[valid_end - 1] == 0 { - valid_end -= 1; - } - if valid_end == 0 { - return Err(Error::new(ErrorKind::InvalidData, "Plaintext is all zeros")); - } - - let content_type = plaintext[valid_end - 1]; - valid_end -= 1; - - if content_type != CONTENT_TYPE_HANDSHAKE - && content_type != CONTENT_TYPE_APPLICATION_DATA - && content_type != CONTENT_TYPE_ALERT - { - return Err(Error::new( - ErrorKind::InvalidData, - format!("Invalid content type: 0x{:02x}", content_type), - )); - } - - Ok((content_type, &plaintext[..valid_end])) - } -} - -/// Build a TLS record header for the given ciphertext length. -#[inline] -fn make_record_header(ciphertext_len: usize) -> [u8; TLS_RECORD_HEADER_SIZE] { - [ - CONTENT_TYPE_APPLICATION_DATA, // Outer type is always ApplicationData in TLS 1.3 - 0x03, - 0x03, // TLS 1.2 version (for compatibility) - (ciphertext_len >> 8) as u8, - (ciphertext_len & 0xff) as u8, - ] -} - -#[cfg(test)] -mod tests { - use super::*; - - const CS: CipherSuite = CipherSuite::AES_128_GCM_SHA256; - - fn encrypt_plaintext_to_records( - cipher_suite: CipherSuite, - plaintext: &mut Vec, - key: &[u8], - iv: &[u8], - write_seq: &mut u64, - ciphertext_buf: &mut Vec, - ) -> io::Result<()> { - let aead_key = AeadKey::new(cipher_suite, key)?; - let mut encryptor = RecordEncryptor::new(&aead_key, iv, write_seq); - encryptor.encrypt_app_data(plaintext, ciphertext_buf) - } - - fn encrypt_handshake_to_records( - cipher_suite: CipherSuite, - handshake_data: &[u8], - key: &[u8], - iv: &[u8], - write_seq: &mut u64, - ciphertext_buf: &mut Vec, - ) -> io::Result<()> { - let aead_key = AeadKey::new(cipher_suite, key)?; - let mut encryptor = RecordEncryptor::new(&aead_key, iv, write_seq); - encryptor.encrypt_handshake(handshake_data, ciphertext_buf) - } - - /// Test helper: decrypt a record by allocating and calling decrypt_record_in_place - fn decrypt_record( - decryptor: &mut RecordDecryptor<'_>, - ciphertext: &[u8], - record_len: u16, - ) -> io::Result<(u8, Vec)> { - let mut buf = ciphertext.to_vec(); - let (content_type, plaintext) = decryptor.decrypt_record_in_place(&mut buf, record_len)?; - Ok((content_type, plaintext.to_vec())) - } - - #[test] - fn test_encrypt_empty_plaintext() { - let mut plaintext = Vec::new(); - let key = [0u8; 16]; - let iv = [0u8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_plaintext_to_records( - CS, - &mut plaintext, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert!(ciphertext_buf.is_empty()); - assert_eq!(seq, 0); // No records encrypted - } - - #[test] - fn test_encrypt_small_plaintext_single_record() { - let mut plaintext = vec![0x41u8; 100]; // 100 bytes of 'A' - let key = [0x01u8; 16]; - let iv = [0x02u8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_plaintext_to_records( - CS, - &mut plaintext, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert!(plaintext.is_empty()); // Should be cleared - - // Should have one record: header(5) + plaintext(100) + content_type(1) + tag(16) - let expected_len = TLS_RECORD_HEADER_SIZE + 100 + 1 + 16; - assert_eq!(ciphertext_buf.len(), expected_len); - assert_eq!(seq, 1); // One record encrypted - - // Verify TLS header - assert_eq!(ciphertext_buf[0], CONTENT_TYPE_APPLICATION_DATA); - assert_eq!(ciphertext_buf[1], 0x03); - assert_eq!(ciphertext_buf[2], 0x03); - let record_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]) as usize; - assert_eq!(record_len, 100 + 1 + 16); - } - - #[test] - fn test_encrypt_max_single_record() { - // Test exactly at the boundary - should still be single record - let mut plaintext = vec![0x42u8; MAX_TLS_PLAINTEXT_LEN]; - let key = [0x03u8; 16]; - let iv = [0x04u8; 12]; - let mut seq = 5u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_plaintext_to_records( - CS, - &mut plaintext, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert!(plaintext.is_empty()); - assert!( - plaintext.capacity() <= MAX_TLS_CIPHERTEXT_LEN, - "plaintext staging buffer retained {} bytes", - plaintext.capacity() - ); - - // Should have one record - let expected_len = TLS_RECORD_HEADER_SIZE + MAX_TLS_PLAINTEXT_LEN + 1 + 16; - assert_eq!(ciphertext_buf.len(), expected_len); - assert_eq!(seq, 6); // One record encrypted - } - - #[test] - fn test_encrypt_fragmentation_two_records() { - // One byte over the limit - should produce two records - let mut plaintext = vec![0x43u8; MAX_TLS_PLAINTEXT_LEN + 1]; - let key = [0x05u8; 16]; - let iv = [0x06u8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_plaintext_to_records( - CS, - &mut plaintext, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert!(plaintext.is_empty()); - assert_eq!(seq, 2); // Two records encrypted - - // First record: full MAX_TLS_PLAINTEXT_LEN - let first_record_len = TLS_RECORD_HEADER_SIZE + MAX_TLS_PLAINTEXT_LEN + 1 + 16; - // Second record: 1 byte - let second_record_len = TLS_RECORD_HEADER_SIZE + 1 + 1 + 16; - assert_eq!(ciphertext_buf.len(), first_record_len + second_record_len); - - // Verify first record header - assert_eq!(ciphertext_buf[0], CONTENT_TYPE_APPLICATION_DATA); - let first_payload_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]) as usize; - assert_eq!(first_payload_len, MAX_TLS_PLAINTEXT_LEN + 1 + 16); - - // Verify second record header - let second_header_offset = first_record_len; - assert_eq!( - ciphertext_buf[second_header_offset], - CONTENT_TYPE_APPLICATION_DATA - ); - let second_payload_len = u16::from_be_bytes([ - ciphertext_buf[second_header_offset + 3], - ciphertext_buf[second_header_offset + 4], - ]) as usize; - assert_eq!(second_payload_len, 1 + 1 + 16); - } - - #[test] - fn test_encrypt_fragmentation_multiple_records() { - // Test 3x the max size - should produce 3 records - let size = MAX_TLS_PLAINTEXT_LEN * 3; - let mut plaintext = vec![0x44u8; size]; - let key = [0x07u8; 16]; - let iv = [0x08u8; 12]; - let mut seq = 10u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_plaintext_to_records( - CS, - &mut plaintext, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert!(plaintext.is_empty()); - assert_eq!(seq, 13); // Three records encrypted - - // Each record: header(5) + MAX_TLS_PLAINTEXT_LEN + content_type(1) + tag(16) - let record_len = TLS_RECORD_HEADER_SIZE + MAX_TLS_PLAINTEXT_LEN + 1 + 16; - assert_eq!(ciphertext_buf.len(), record_len * 3); - } - - #[test] - fn test_sequence_number_increments() { - let key = [0x0Bu8; 16]; - let iv = [0x0Cu8; 12]; - let mut seq = 100u64; - let mut ciphertext_buf = Vec::new(); - - // First call with small data - let mut plaintext1 = vec![0x46u8; 50]; - encrypt_plaintext_to_records( - CS, - &mut plaintext1, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ) - .unwrap(); - assert_eq!(seq, 101); - - // Second call with data requiring fragmentation - let mut plaintext2 = vec![0x47u8; MAX_TLS_PLAINTEXT_LEN + 500]; - encrypt_plaintext_to_records( - CS, - &mut plaintext2, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ) - .unwrap(); - assert_eq!(seq, 103); // Two more records - } - - #[test] - fn test_ciphertext_buf_appends() { - let key = [0x0Du8; 16]; - let iv = [0x0Eu8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - // Pre-populate buffer - ciphertext_buf.extend_from_slice(b"existing data"); - let initial_len = ciphertext_buf.len(); - - let mut plaintext = vec![0x48u8; 100]; - encrypt_plaintext_to_records(CS, &mut plaintext, &key, &iv, &mut seq, &mut ciphertext_buf) - .unwrap(); - - // Should append, not overwrite - assert!(ciphertext_buf.len() > initial_len); - assert_eq!(&ciphertext_buf[..initial_len], b"existing data"); - } - - #[test] - fn test_encrypt_single_byte() { - // Minimum non-empty plaintext - let mut plaintext = vec![0x42u8; 1]; - let key = [0x0Fu8; 16]; - let iv = [0x10u8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_plaintext_to_records( - CS, - &mut plaintext, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert!(plaintext.is_empty()); - assert_eq!(seq, 1); - - // header(5) + plaintext(1) + content_type(1) + tag(16) = 23 - assert_eq!(ciphertext_buf.len(), 23); - } - - #[test] - fn test_handshake_encrypt_empty() { - let handshake_data: &[u8] = &[]; - let key = [0u8; 16]; - let iv = [0u8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_handshake_to_records( - CS, - handshake_data, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert!(ciphertext_buf.is_empty()); - assert_eq!(seq, 0); // No records encrypted - } - - #[test] - fn test_handshake_encrypt_small_single_record() { - // Typical small handshake (EncryptedExtensions + small cert + CV + Finished) - let handshake_data = vec![0x16u8; 500]; - let key = [0x01u8; 16]; - let iv = [0x02u8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_handshake_to_records( - CS, - &handshake_data, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert_eq!(seq, 1); // One record encrypted - - // Should have one record: header(5) + handshake(500) + content_type(1) + tag(16) - let expected_len = TLS_RECORD_HEADER_SIZE + 500 + 1 + 16; - assert_eq!(ciphertext_buf.len(), expected_len); - - // Verify TLS header - outer type is ApplicationData (0x17) - assert_eq!(ciphertext_buf[0], CONTENT_TYPE_APPLICATION_DATA); - assert_eq!(ciphertext_buf[1], 0x03); - assert_eq!(ciphertext_buf[2], 0x03); - let record_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]) as usize; - assert_eq!(record_len, 500 + 1 + 16); - } - - #[test] - fn test_handshake_encrypt_max_single_record() { - // Exactly at the boundary - should still be single record - let handshake_data = vec![0x16u8; MAX_TLS_PLAINTEXT_LEN]; - let key = [0x03u8; 16]; - let iv = [0x04u8; 12]; - let mut seq = 5u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_handshake_to_records( - CS, - &handshake_data, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert_eq!(seq, 6); // One record encrypted - - let expected_len = TLS_RECORD_HEADER_SIZE + MAX_TLS_PLAINTEXT_LEN + 1 + 16; - assert_eq!(ciphertext_buf.len(), expected_len); - } - - #[test] - fn test_handshake_encrypt_fragmentation_two_records() { - // One byte over the limit - should produce two records - let handshake_data = vec![0x16u8; MAX_TLS_PLAINTEXT_LEN + 1]; - let key = [0x05u8; 16]; - let iv = [0x06u8; 12]; - let mut seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let result = encrypt_handshake_to_records( - CS, - &handshake_data, - &key, - &iv, - &mut seq, - &mut ciphertext_buf, - ); - assert!(result.is_ok()); - assert_eq!(seq, 2); // Two records encrypted - - // First record: full MAX_TLS_PLAINTEXT_LEN - let first_record_len = TLS_RECORD_HEADER_SIZE + MAX_TLS_PLAINTEXT_LEN + 1 + 16; - // Second record: 1 byte - let second_record_len = TLS_RECORD_HEADER_SIZE + 1 + 1 + 16; - assert_eq!(ciphertext_buf.len(), first_record_len + second_record_len); - } - - #[test] - fn test_record_encryptor_app_data() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let mut seq = 0u64; - let mut out = Vec::new(); - - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut seq); - - let mut plaintext = vec![0xAAu8; 100]; - encryptor - .encrypt_app_data(&mut plaintext, &mut out) - .unwrap(); - - assert!(plaintext.is_empty()); - assert_eq!(seq, 1); - assert_eq!(out.len(), 5 + 100 + 1 + 16); - } - - #[test] - fn test_record_encryptor_handshake() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let mut seq = 0u64; - let mut out = Vec::new(); - - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut seq); - - let handshake = vec![0xBBu8; 200]; - encryptor.encrypt_handshake(&handshake, &mut out).unwrap(); - - assert_eq!(seq, 1); - assert_eq!(out.len(), 5 + 200 + 1 + 16); - } - - #[test] - fn test_record_encryptor_close_notify() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let mut seq = 0u64; - let mut out = Vec::new(); - - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut seq); - encryptor.encrypt_close_notify(&mut out).unwrap(); - - assert_eq!(seq, 1); - // header(5) + alert(2) + content_type(1) + tag(16) = 24 - assert_eq!(out.len(), 24); - } - - #[test] - fn test_record_decryptor_roundtrip() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let mut enc_seq = 0u64; - let mut dec_seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - // Encrypt - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut enc_seq); - let mut plaintext = vec![0xCCu8; 100]; - let original = plaintext.clone(); - encryptor - .encrypt_app_data(&mut plaintext, &mut ciphertext_buf) - .unwrap(); - - // Decrypt - extract ciphertext from record - let record_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]); - let ciphertext = &ciphertext_buf[5..]; - - let mut decryptor = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let (content_type, decrypted) = - decrypt_record(&mut decryptor, ciphertext, record_len).unwrap(); - - assert_eq!(content_type, CONTENT_TYPE_APPLICATION_DATA); - assert_eq!(decrypted, original); - assert_eq!(dec_seq, 1); - } - - #[test] - fn test_record_decryptor_handshake_roundtrip() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let mut enc_seq = 0u64; - let mut dec_seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - // Encrypt handshake - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut enc_seq); - let handshake = vec![0xDDu8; 150]; - encryptor - .encrypt_handshake(&handshake, &mut ciphertext_buf) - .unwrap(); - - // Decrypt - let record_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]); - let ciphertext = &ciphertext_buf[5..]; - - let mut decryptor = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let (content_type, decrypted) = - decrypt_record(&mut decryptor, ciphertext, record_len).unwrap(); - - assert_eq!(content_type, CONTENT_TYPE_HANDSHAKE); - assert_eq!(decrypted, handshake); - } - - #[test] - fn test_roundtrip_single_byte() { - let key_bytes = [0x11u8; 16]; - let iv = [0x22u8; 12]; - let mut enc_seq = 0u64; - let mut dec_seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let aead_key = AeadKey::new(CS, &key_bytes).unwrap(); - - // Encrypt single byte - let mut plaintext = vec![0x42u8]; - let original = plaintext.clone(); - { - let mut enc = RecordEncryptor::new(&aead_key, &iv, &mut enc_seq); - enc.encrypt_app_data(&mut plaintext, &mut ciphertext_buf) - .unwrap(); - } - - // Decrypt - let record_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]); - let ciphertext = &ciphertext_buf[5..]; - - let mut dec = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let (ct, decrypted) = decrypt_record(&mut dec, ciphertext, record_len).unwrap(); - - assert_eq!(ct, CONTENT_TYPE_APPLICATION_DATA); - assert_eq!(decrypted, original); - } - - #[test] - fn test_roundtrip_large_64kb() { - let key_bytes = [0x33u8; 16]; - let iv = [0x44u8; 12]; - let mut enc_seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - let aead_key = AeadKey::new(CS, &key_bytes).unwrap(); - - // 64KB will be fragmented into 4 records - let mut plaintext = vec![0x55u8; 65536]; - let original = plaintext.clone(); - { - let mut enc = RecordEncryptor::new(&aead_key, &iv, &mut enc_seq); - enc.encrypt_app_data(&mut plaintext, &mut ciphertext_buf) - .unwrap(); - } - - assert_eq!(enc_seq, 4); // 64KB / 16KB = 4 records - - // Decrypt all records and reassemble - let mut dec_seq = 0u64; - let mut dec = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let mut reassembled = Vec::new(); - let mut offset = 0; - - while offset < ciphertext_buf.len() { - let record_len = - u16::from_be_bytes([ciphertext_buf[offset + 3], ciphertext_buf[offset + 4]]); - let ciphertext = &ciphertext_buf[offset + 5..offset + 5 + record_len as usize]; - - let (ct, decrypted) = decrypt_record(&mut dec, ciphertext, record_len).unwrap(); - assert_eq!(ct, CONTENT_TYPE_APPLICATION_DATA); - reassembled.extend_from_slice(&decrypted); - - offset += 5 + record_len as usize; - } - - assert_eq!(reassembled, original); - } - - #[test] - fn test_encryptor_sequence_exhaustion() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let mut seq = u64::MAX; // Start at max - let mut out = Vec::new(); - - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut seq); - let mut plaintext = vec![0xAAu8; 10]; - - // First encryption should succeed (uses seq = MAX) - let result = encryptor.encrypt_app_data(&mut plaintext, &mut out); - assert!(result.is_err()); // Should fail because MAX + 1 would overflow - assert!(result.unwrap_err().to_string().contains("exhausted")); - } - - #[test] - fn test_decryptor_sequence_exhaustion() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - - // First encrypt with seq=0 to get valid ciphertext - let mut enc_seq = 0u64; - let mut ciphertext_buf = Vec::new(); - { - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut enc_seq); - let mut plaintext = vec![0xBBu8; 10]; - encryptor - .encrypt_app_data(&mut plaintext, &mut ciphertext_buf) - .unwrap(); - } - - // Try to decrypt with seq at MAX - decryption will fail due to wrong nonce, - // but even if it succeeded, seq increment would fail - let mut dec_seq = u64::MAX; - let record_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]); - let ciphertext = &ciphertext_buf[5..]; - - let mut decryptor = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let result = decrypt_record(&mut decryptor, ciphertext, record_len); - // Will fail either due to decryption (wrong nonce) or seq exhaustion - assert!(result.is_err()); - } - - #[test] - fn test_decrypt_record_with_zero_padding() { - let key = [0x01u8; 16]; - let iv = [0x02u8; 12]; - let aead_key = AeadKey::new(CS, &key).unwrap(); - - let content = vec![0xAAu8; 50]; - let mut padded = content.clone(); - padded.push(CONTENT_TYPE_HANDSHAKE); - padded.extend_from_slice(&[0x00u8; 5]); - - let ciphertext_len = padded.len() + 16; - let aad = make_record_header(ciphertext_len); - let ciphertext = aead_key.seal(&padded, &iv, 0, &aad).unwrap(); - - let mut dec_seq = 0u64; - let mut decryptor = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let (content_type, plaintext) = - decrypt_record(&mut decryptor, &ciphertext, ciphertext_len as u16).unwrap(); - - assert_eq!(content_type, CONTENT_TYPE_HANDSHAKE); - assert_eq!(plaintext, content); - } - - #[test] - fn test_decrypt_all_zeros_plaintext_fails() { - let key = [0x03u8; 16]; - let iv = [0x04u8; 12]; - let aead_key = AeadKey::new(CS, &key).unwrap(); - - let all_zeros = vec![0x00u8; 16]; - let ciphertext_len = all_zeros.len() + 16; - let aad = make_record_header(ciphertext_len); - let ciphertext = aead_key.seal(&all_zeros, &iv, 0, &aad).unwrap(); - - let mut dec_seq = 0u64; - let mut decryptor = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let result = decrypt_record(&mut decryptor, &ciphertext, ciphertext_len as u16); - - assert!(result.is_err()); - assert!(result.unwrap_err().to_string().contains("all zeros")); - } - - #[test] - fn test_alert_roundtrip() { - let aead_key = AeadKey::new(CS, &[0x42u8; 16]).unwrap(); - let iv = [0x99u8; 12]; - let mut enc_seq = 0u64; - let mut dec_seq = 0u64; - let mut ciphertext_buf = Vec::new(); - - // Encrypt close_notify alert - { - let mut encryptor = RecordEncryptor::new(&aead_key, &iv, &mut enc_seq); - encryptor.encrypt_close_notify(&mut ciphertext_buf).unwrap(); - } - - assert_eq!(enc_seq, 1); - - // Decrypt and verify - let record_len = u16::from_be_bytes([ciphertext_buf[3], ciphertext_buf[4]]); - let ciphertext = &ciphertext_buf[5..]; - - let mut decryptor = RecordDecryptor::new(&aead_key, &iv, &mut dec_seq); - let (content_type, plaintext) = - decrypt_record(&mut decryptor, ciphertext, record_len).unwrap(); - - assert_eq!(content_type, CONTENT_TYPE_ALERT); - assert_eq!(plaintext.len(), 2); - assert_eq!(plaintext[0], 0x01); // level = warning - assert_eq!(plaintext[1], 0x00); // desc = close_notify - } -} diff --git a/src/reality/reality_rustls.rs b/src/reality/reality_rustls.rs new file mode 100644 index 00000000..5dbe8413 --- /dev/null +++ b/src/reality/reality_rustls.rs @@ -0,0 +1,352 @@ +use std::fmt; +use std::io; +use std::sync::Arc; + +use aws_lc_rs::{agreement, kem, signature}; +use parking_lot::Mutex; +use rand::Rng; +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::crypto::{ActiveKeyExchange, CryptoProvider, SharedSecret, SupportedKxGroup}; +use rustls::pki_types::{CertificateDer, ServerName, UnixTime}; +use rustls::{CertificateError, DigitallySignedStruct, Error, NamedGroup, SignatureScheme}; +use zeroize::Zeroizing; + +use super::reality_auth::{derive_auth_key, encrypt_session_id, perform_ecdh}; +use super::reality_client_verify::{ + extract_ed25519_public_key, verify_certificate_hmac, verify_certificate_mldsa, +}; +#[cfg(test)] +use super::reality_key_exchange::RealityGroup; +use super::reality_key_exchange::generate_mlkem; +use super::{CipherSuite, DEFAULT_CIPHER_SUITES, RealityClientConfig}; + +pub(super) fn provider(suites: &[CipherSuite]) -> CryptoProvider { + let mut provider = rustls::crypto::aws_lc_rs::default_provider(); + let supported = provider.cipher_suites.clone(); + provider.cipher_suites = if suites.is_empty() { + DEFAULT_CIPHER_SUITES + } else { + suites + } + .iter() + .filter_map(|suite| { + supported + .iter() + .find(|s| u16::from(s.suite()) == suite.id()) + .copied() + }) + .collect(); + provider.kx_groups = vec![ + rustls::crypto::aws_lc_rs::kx_group::X25519MLKEM768, + rustls::crypto::aws_lc_rs::kx_group::X25519, + ]; + provider +} + +pub(super) fn io_error(error: Error) -> io::Error { + let kind = match &error { + Error::InvalidCertificate(_) => io::ErrorKind::PermissionDenied, + Error::PeerIncompatible(rustls::PeerIncompatible::RealityUnsupported) => { + io::ErrorKind::Unsupported + } + Error::FailedToGetCurrentTime | Error::FailedToGetRandomBytes | Error::General(_) => { + io::ErrorKind::Other + } + _ => io::ErrorKind::InvalidData, + }; + io::Error::new(kind, error) +} + +fn crypto_error(_: impl fmt::Display) -> Error { + Error::General("REALITY key exchange failed".into()) +} + +fn verification_error(_: impl fmt::Display) -> Error { + Error::InvalidCertificate(CertificateError::ApplicationVerificationFailure) +} + +#[cfg(test)] +pub(super) fn group(group: NamedGroup) -> Option { + match group { + NamedGroup::X25519 => Some(RealityGroup::X25519), + NamedGroup::X25519MLKEM768 => Some(RealityGroup::X25519MlKem768), + _ => None, + } +} + +#[derive(Default)] +struct VerificationContext { + auth: Option>, + hellos: Vec, + public_key: Option<[u8; 32]>, +} + +pub(super) struct ClientAuthentication { + server_key: [u8; 32], + short_id: [u8; 8], + shared: Option>, + context: Arc>, +} + +impl fmt::Debug for ClientAuthentication { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ClientAuthentication") + .finish_non_exhaustive() + } +} + +pub(super) struct RealityVerifier { + context: Arc>, + mldsa: Option, + schemes: Vec, +} + +impl fmt::Debug for RealityVerifier { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RealityVerifier").finish_non_exhaustive() + } +} + +pub(super) fn client_authentication( + config: &RealityClientConfig, + schemes: Vec, +) -> (ClientAuthentication, RealityVerifier) { + let context = Arc::new(Mutex::new(VerificationContext::default())); + ( + ClientAuthentication { + server_key: config.public_key, + short_id: config.short_id, + shared: None, + context: context.clone(), + }, + RealityVerifier { + context, + mldsa: config.mldsa65_verify.clone(), + schemes, + }, + ) +} + +struct ClientExchange { + private: Zeroizing<[u8; 32]>, + mlkem: Option, + public: Vec, + group: NamedGroup, +} + +impl ActiveKeyExchange for ClientExchange { + fn complete(self: Box, peer: &[u8]) -> Result { + let offset = if self.group == NamedGroup::X25519MLKEM768 { + 1088 + } else { + 0 + }; + let x25519_peer = + peer.get(offset..) + .and_then(|p| p.try_into().ok()) + .ok_or(Error::PeerMisbehaved( + rustls::PeerMisbehaved::InvalidKeyShare, + ))?; + let x25519 = + Zeroizing::new(perform_ecdh(&self.private, x25519_peer).map_err(crypto_error)?); + let mut shared = Zeroizing::new(Vec::with_capacity(64)); + if offset != 0 { + let kem = self + .mlkem + .as_ref() + .ok_or_else(|| crypto_error("missing KEM"))?; + let secret = kem + .decapsulate(kem::Ciphertext::from(&peer[..offset])) + .map_err(crypto_error)?; + shared.extend_from_slice(secret.as_ref()); + } + shared.extend_from_slice(x25519.as_ref()); + Ok(SharedSecret::from(shared.as_slice())) + } + + fn pub_key(&self) -> &[u8] { + &self.public + } + + fn group(&self) -> NamedGroup { + self.group + } + + fn hybrid_component(&self) -> Option<(NamedGroup, &[u8])> { + (self.group == NamedGroup::X25519MLKEM768) + .then(|| (NamedGroup::X25519, &self.public[self.public.len() - 32..])) + } + + fn complete_hybrid_component(self: Box, peer: &[u8]) -> Result { + let peer = peer.try_into().map_err(crypto_error)?; + let shared = Zeroizing::new(perform_ecdh(&self.private, peer).map_err(crypto_error)?); + Ok(SharedSecret::from(shared.as_ref())) + } +} + +impl rustls::reality::ClientHooks for ClientAuthentication { + fn start_key_exchange( + &mut self, + kx: &'static dyn SupportedKxGroup, + ) -> Result, Error> { + if !matches!(kx.name(), NamedGroup::X25519 | NamedGroup::X25519MLKEM768) { + return Err(crypto_error("unsupported group")); + } + let mut private = Zeroizing::new([0; 32]); + rand::rng().fill_bytes(private.as_mut()); + let key = agreement::PrivateKey::from_private_key(&agreement::X25519, private.as_ref()) + .map_err(crypto_error)?; + let public = key.compute_public_key().map_err(crypto_error)?; + self.shared = Some(Zeroizing::new( + perform_ecdh(&private, &self.server_key).map_err(crypto_error)?, + )); + let (mlkem, mut share) = if kx.name() == NamedGroup::X25519MLKEM768 { + let (key, public) = generate_mlkem().map_err(crypto_error)?; + (Some(key), public) + } else { + (None, Vec::new()) + }; + share.extend_from_slice(public.as_ref()); + Ok(Box::new(ClientExchange { + private, + mlkem, + public: share, + group: kx.name(), + })) + } + + fn session_id(&mut self, hello: &[u8]) -> Result<[u8; 32], Error> { + let shared = self + .shared + .take() + .ok_or_else(|| crypto_error("missing authentication exchange"))?; + let random = hello + .get(6..38) + .ok_or_else(|| crypto_error("short hello"))?; + let auth = Zeroizing::new( + derive_auth_key(&shared, &random[..20], b"REALITY").map_err(crypto_error)?, + ); + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_err(|_| Error::FailedToGetCurrentTime)? + .as_secs() as u32; + let mut plaintext = Zeroizing::new([0; 16]); + plaintext[..3].copy_from_slice(&[1, 8, 0]); + plaintext[4..8].copy_from_slice(×tamp.to_be_bytes()); + plaintext[8..].copy_from_slice(&self.short_id); + let mut aad = hello.to_vec(); + aad.get_mut(39..71) + .ok_or_else(|| crypto_error("short session ID"))? + .fill(0); + let id = + encrypt_session_id(&plaintext, &auth, &random[20..], &aad).map_err(crypto_error)?; + self.context.lock().auth = Some(auth); + Ok(id) + } + + fn server_hello(&mut self, client: &[u8], server: &[u8]) -> Result<(), Error> { + let mut context = self.context.lock(); + context.hellos.extend_from_slice(client); + context.hellos.extend_from_slice(server); + Ok(()) + } +} + +impl ServerCertVerifier for RealityVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp: &[u8], + _now: UnixTime, + ) -> Result { + let mut context = self.context.lock(); + let auth = context + .auth + .take() + .ok_or_else(|| verification_error("missing authentication"))?; + if !intermediates.is_empty() || context.hellos.is_empty() { + return Err(verification_error( + "unexpected certificate chain or missing hellos", + )); + } + verify_certificate_hmac(end_entity, &auth).map_err(verification_error)?; + if let Some(key) = &self.mldsa { + verify_certificate_mldsa(end_entity, &auth, &context.hellos, key) + .map_err(verification_error)?; + } + context.public_key = + Some(extract_ed25519_public_key(end_entity).map_err(verification_error)?); + context.hellos.clear(); + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + _: &[u8], + _: &CertificateDer<'_>, + _: &DigitallySignedStruct, + ) -> Result { + Err(verification_error("TLS 1.2 is not REALITY")) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + signature: &DigitallySignedStruct, + ) -> Result { + let context = self.context.lock(); + let public = context + .public_key + .ok_or_else(|| verification_error("unauthenticated certificate"))?; + if signature.scheme != SignatureScheme::ED25519 + || extract_ed25519_public_key(cert).map_err(verification_error)? != public + { + return Err(verification_error("unexpected signing key")); + } + signature::UnparsedPublicKey::new(&signature::ED25519, public) + .verify(message, signature.signature()) + .map_err(verification_error)?; + Ok(HandshakeSignatureValid::assertion()) + } + + fn supported_verify_schemes(&self) -> Vec { + self.schemes.clone() + } +} + +pub(super) struct RealitySigningKey(Arc); + +impl RealitySigningKey { + pub(super) fn new(key: signature::Ed25519KeyPair) -> Self { + Self(Arc::new(key)) + } +} + +impl fmt::Debug for RealitySigningKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("RealitySigningKey") + } +} + +impl rustls::sign::SigningKey for RealitySigningKey { + fn choose_scheme(&self, _: &[SignatureScheme]) -> Option> { + Some(Box::new(Self(self.0.clone()))) + } + + fn algorithm(&self) -> rustls::SignatureAlgorithm { + rustls::SignatureAlgorithm::ED25519 + } +} + +impl rustls::sign::Signer for RealitySigningKey { + fn sign(&self, message: &[u8]) -> Result, Error> { + Ok(self.0.sign(message).as_ref().to_vec()) + } + + fn scheme(&self) -> SignatureScheme { + SignatureScheme::ED25519 + } +} diff --git a/src/reality/reality_rustls_tests.rs b/src/reality/reality_rustls_tests.rs new file mode 100644 index 00000000..691b2528 --- /dev/null +++ b/src/reality/reality_rustls_tests.rs @@ -0,0 +1,467 @@ +use std::io::{self, BufRead, Read, Write}; +use std::sync::Arc; + +use bytes::Bytes; +use parking_lot::Mutex; + +use super::reality_key_exchange::RealityGroup; +use super::reality_pq_tests::{configs, separate_target_records, target_records}; +use super::*; + +#[derive(Debug, Default)] +struct Secrets(Mutex>>); + +#[test] +fn interleaved_connections_do_not_share_authentication_state() { + let pending: Vec<_> = (0..4).map(|_| pending_pair(Arc::default(), true)).collect(); + for (mut client, mut server, flight) in pending { + feed_reality_client_connection(&mut client, &flight.concat()).unwrap(); + let mut wire = Vec::new(); + client.write_tls(&mut wire).unwrap(); + feed_reality_server_connection(&mut server, &wire).unwrap(); + assert!(!client.is_handshaking() && !server.is_handshaking()); + } +} + +#[test] +fn real_target_certificate_never_authenticates_reality() { + let (cc, _) = configs(CipherSuite::AES_128_GCM_SHA256); + let cert = rcgen::generate_simple_self_signed(vec!["cover.test".into()]).unwrap(); + let config = rustls::ServerConfig::builder_with_protocol_versions(&[&rustls::version::TLS13]) + .with_no_client_auth() + .with_single_cert( + vec![cert.cert.der().clone()], + rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()).into(), + ) + .unwrap(); + let mut server = rustls::ServerConnection::new(Arc::new(config)).unwrap(); + let mut client = RealityClientConnection::new(cc).unwrap(); + let mut wire = Vec::new(); + client.write_tls(&mut wire).unwrap(); + let mut input = wire.as_slice(); + while !input.is_empty() { + server.read_tls(&mut input).unwrap(); + server.process_new_packets().unwrap(); + } + wire.clear(); + server.write_tls(&mut wire).unwrap(); + assert_eq!( + feed_reality_client_connection(&mut client, &wire) + .unwrap_err() + .kind(), + io::ErrorKind::PermissionDenied + ); + assert!(client.is_handshaking() && !client.wants_write()); +} + +impl rustls::KeyLog for Secrets { + fn log(&self, label: &str, _: &[u8], secret: &[u8]) { + self.0.lock().insert(label.into(), secret.to_vec()); + } +} + +fn records(wire: &[u8]) -> Vec { + let mut deframer = crate::crypto::tls_deframer::TlsDeframer::new(); + deframer.feed(wire); + let records = deframer.next_records().unwrap(); + assert_eq!(deframer.pending_bytes(), 0); + records +} + +fn pending_pair( + secrets: Arc, + omit_ed25519: bool, +) -> (RealityClientConnection, RealityServerConnection, Vec) { + let (cc, sc) = configs(CipherSuite::AES_128_GCM_SHA256); + let crypto = reality_rustls::provider(&cc.cipher_suites); + let mut schemes = crypto.signature_verification_algorithms.supported_schemes(); + if omit_ed25519 { + schemes.retain(|scheme| *scheme != rustls::SignatureScheme::ED25519); + } + let mut client = RealityClientConnection::with_options(cc, crypto, schemes, secrets).unwrap(); + let mut server = RealityServerConnection::new(sc).unwrap(); + let mut hello = Vec::new(); + client.write_tls(&mut hello).unwrap(); + server.validate_client_hello(&hello).unwrap(); + let target = separate_target_records( + RealityGroup::X25519MlKem768, + CipherSuite::AES_128_GCM_SHA256, + &hello[44..76], + ); + server.build_server_response(&target).unwrap(); + let mut wire = Vec::new(); + server.write_tls(&mut wire).unwrap(); + (client, server, records(&wire)) +} + +fn mutate_record( + record: &Bytes, + secret: &[u8], + seq: u64, + change: impl FnOnce(&mut Vec), +) -> Vec { + use aws_lc_rs::{aead, hkdf}; + struct Length(usize); + impl hkdf::KeyType for Length { + fn len(&self) -> usize { + self.0 + } + } + let expand = |label: &[u8], len: usize| { + let mut info = (len as u16).to_be_bytes().to_vec(); + info.push((6 + label.len()) as u8); + info.extend_from_slice(b"tls13 "); + info.extend_from_slice(label); + info.push(0); + let prk = hkdf::Prk::new_less_safe(hkdf::HKDF_SHA256, secret); + let mut output = vec![0; len]; + prk.expand(&[&info], Length(len)) + .unwrap() + .fill(&mut output) + .unwrap(); + output + }; + let key = aead::LessSafeKey::new( + aead::UnboundKey::new(&aead::AES_128_GCM, &expand(b"key", 16)).unwrap(), + ); + let mut nonce: [u8; 12] = expand(b"iv", 12).try_into().unwrap(); + for (byte, sequence) in nonce[4..].iter_mut().zip(seq.to_be_bytes()) { + *byte ^= sequence; + } + let mut plaintext = record[5..].to_vec(); + let len = key + .open_in_place( + aead::Nonce::assume_unique_for_key(nonce), + aead::Aad::from(&record[..5]), + &mut plaintext, + ) + .unwrap() + .len(); + plaintext.truncate(len); + let original_len = plaintext.len(); + change(&mut plaintext); + assert_eq!(plaintext.len(), original_len); + let mut output = record[..5].to_vec(); + key.seal_in_place_append_tag( + aead::Nonce::assume_unique_for_key(nonce), + aead::Aad::from(&record[..5]), + &mut plaintext, + ) + .unwrap(); + output.extend_from_slice(&plaintext); + output +} + +#[test] +fn authenticated_unadvertised_ed25519_and_key_updates() { + let (mut client, mut server, flight) = pending_pair(Arc::default(), true); + feed_reality_client_connection(&mut client, &flight.concat()).unwrap(); + let mut wire = Vec::new(); + client.write_tls(&mut wire).unwrap(); + feed_reality_server_connection(&mut server, &wire).unwrap(); + assert!(!client.is_handshaking() && !server.is_handshaking()); + for _ in 0..3 { + client.transport.refresh_traffic_keys().unwrap(); + client.writer().write_all(b"updated client").unwrap(); + wire.clear(); + client.write_tls(&mut wire).unwrap(); + feed_reality_server_connection(&mut server, &wire).unwrap(); + let mut data = [0; 14]; + server.reader().read_exact(&mut data).unwrap(); + assert_eq!(&data, b"updated client"); + server.transport.refresh_traffic_keys().unwrap(); + server.writer().write_all(b"updated server").unwrap(); + wire.clear(); + server.write_tls(&mut wire).unwrap(); + feed_reality_client_connection(&mut client, &wire).unwrap(); + client.reader().read_exact(&mut data).unwrap(); + assert_eq!(&data, b"updated server"); + } +} + +#[test] +fn certificate_verify_and_server_finished_must_verify() { + // Re-encrypt corrupted plaintext with valid AEAD tags: this tests signature/Finished validation. + for (index, kind) in [ + (3, io::ErrorKind::PermissionDenied), + (4, io::ErrorKind::PermissionDenied), + (5, io::ErrorKind::InvalidData), + ] { + let secrets = Arc::new(Secrets::default()); + let (mut client, _, flight) = pending_pair(secrets.clone(), true); + for record in &flight[..index] { + feed_reality_client_connection(&mut client, record).unwrap(); + } + let secret = secrets.0.lock()["SERVER_HANDSHAKE_TRAFFIC_SECRET"].clone(); + let bad = mutate_record(&flight[index], &secret, (index - 2) as u64, |plaintext| { + let offset = if index == 3 { + let len = + u32::from_be_bytes([0, plaintext[8], plaintext[9], plaintext[10]]) as usize; + 11 + len - 1 + } else { + 8 + }; + plaintext[offset] ^= 1; + }); + let mutated_flight = [bad, flight[index + 1..].concat()].concat(); + let error = feed_reality_client_connection(&mut client, &mutated_flight).unwrap_err(); + assert_eq!(error.kind(), kind); + assert!(client.is_handshaking()); + assert!(client.reader().fill_buf().is_err()); + assert!(client.writer().write(b"forbidden").is_err()); + let mut output = Vec::new(); + assert_eq!(client.write_tls(&mut output).unwrap(), 0); + assert!(output.is_empty()); + assert!(client.process_new_packets().is_err()); + } +} + +#[test] +fn authentication_policy_and_client_share_variants() { + for case in [ + "valid", + "plain-only", + "hybrid-only", + "short-id", + "static-key", + "minimum", + "maximum", + "timestamp", + "tampered-hello", + ] { + let (mut cc, mut sc) = configs(CipherSuite::AES_128_GCM_SHA256); + match case { + "short-id" => cc.short_id = [2; 8], + "static-key" => sc.private_key = [43; 32], + "minimum" => sc.min_client_version = Some([1, 8, 1]), + "maximum" => sc.max_client_version = Some([1, 7, 9]), + _ => {} + } + let mut crypto = reality_rustls::provider(&cc.cipher_suites); + if case == "plain-only" { + crypto.kx_groups.remove(0); + } + if case == "hybrid-only" { + crypto.kx_groups.pop(); + } + let schemes = crypto.signature_verification_algorithms.supported_schemes(); + let mut client = RealityClientConnection::with_options( + cc, + crypto, + schemes, + Arc::new(rustls::NoKeyLog {}), + ) + .unwrap(); + let mut hello = Vec::new(); + client.write_tls(&mut hello).unwrap(); + if case == "tampered-hello" { + hello[11] ^= 1; + } + if case == "timestamp" { + use super::reality_auth::{derive_auth_key, encrypt_session_id, perform_ecdh}; + let shares = super::reality_key_exchange::extract_client_key_shares(&hello).unwrap(); + let shared = + perform_ecdh(&sc.private_key, shares.authentication_public_key().unwrap()).unwrap(); + let auth = derive_auth_key(&shared, &hello[11..31], b"REALITY").unwrap(); + let mut aad = hello[5..].to_vec(); + aad[39..71].fill(0); + let mut payload = [0; 16]; + payload[..3].copy_from_slice(&[1, 8, 0]); + payload[8..].fill(1); + let session = encrypt_session_id(&payload, &auth, &hello[31..43], &aad).unwrap(); + hello[44..76].copy_from_slice(&session); + sc.max_time_diff = Some(60_000); + } + let mut server = RealityServerConnection::new(sc).unwrap(); + let result = server.validate_client_hello(&hello); + if matches!(case, "valid" | "plain-only" | "hybrid-only") { + result.unwrap(); + let group = if case == "plain-only" { + RealityGroup::X25519 + } else { + RealityGroup::X25519MlKem768 + }; + server + .build_server_response(&target_records( + group, + CipherSuite::AES_128_GCM_SHA256, + &hello[44..76], + )) + .unwrap(); + let mut flight = Vec::new(); + server.write_tls(&mut flight).unwrap(); + feed_reality_client_connection(&mut client, &flight).unwrap(); + flight.clear(); + client.write_tls(&mut flight).unwrap(); + feed_reality_server_connection(&mut server, &flight).unwrap(); + assert!(!server.is_handshaking()); + } else { + assert_eq!( + result.unwrap_err().kind(), + io::ErrorKind::PermissionDenied, + "{case}" + ); + assert!(!server.wants_write()); + } + } +} + +#[test] +fn rejected_client_finished_never_completes_handshake() { + let secrets = Arc::new(Secrets::default()); + let (mut client, mut server, flight) = pending_pair(secrets.clone(), false); + feed_reality_client_connection(&mut client, &flight.concat()).unwrap(); + let mut wire = Vec::new(); + client.write_tls(&mut wire).unwrap(); + let secret = secrets.0.lock()["CLIENT_HANDSHAKE_TRAFFIC_SECRET"].clone(); + for record in records(&wire) { + if record[0] == 20 { + feed_reality_server_connection(&mut server, &record).unwrap(); + continue; + } + let bad = mutate_record(&record, &secret, 0, |plaintext| plaintext[4] ^= 1); + let error = feed_reality_server_connection(&mut server, &bad).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!(server.is_handshaking()); + assert!(server.reader().fill_buf().is_err()); + assert!(server.writer().write(b"forbidden").is_err()); + assert!(!server.wants_write()); + } +} + +#[test] +fn server_hello_must_echo_session_and_select_offered_cipher() { + for offset in [44, 76] { + let (mut client, _, flight) = pending_pair(Arc::default(), false); + let mut hello = flight[0].to_vec(); + hello[offset] ^= 1; + assert!(feed_reality_client_connection(&mut client, &hello).is_err()); + assert!(client.is_handshaking()); + assert!(!client.wants_write()); + } +} + +#[test] +fn target_selection_is_an_allowlist_not_local_preference() { + for allowed in [false, true] { + let (mut cc, mut sc) = configs(CipherSuite::AES_128_GCM_SHA256); + cc.cipher_suites = DEFAULT_CIPHER_SUITES.to_vec(); + if allowed { + sc.cipher_suites = cc.cipher_suites.clone(); + } + let mut client = RealityClientConnection::new(cc).unwrap(); + let mut server = RealityServerConnection::new(sc).unwrap(); + let mut hello = Vec::new(); + client.write_tls(&mut hello).unwrap(); + server.validate_client_hello(&hello).unwrap(); + let target = target_records( + RealityGroup::X25519, + CipherSuite::AES_256_GCM_SHA384, + &hello[44..76], + ); + let result = server.build_server_response(&target); + if allowed { + result.unwrap(); + let mut wire = Vec::new(); + server.write_tls(&mut wire).unwrap(); + // This fixture has supported_versions before key_share; preserve every byte preceding the share. + assert_eq!(&wire[..90], &target[0][..90]); + feed_reality_client_connection(&mut client, &wire).unwrap(); + assert!(!client.is_handshaking()); + } else { + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Unsupported); + assert!(!server.wants_write()); + } + } +} + +#[test] +fn rejected_templates_never_queue_synthetic_output() { + for case in [ + "ccs", + "version", + "type", + "length", + "short", + "extra", + "session", + "unknown-extension", + ] { + let (cc, sc) = configs(CipherSuite::AES_128_GCM_SHA256); + let mut client = RealityClientConnection::new(cc).unwrap(); + let mut server = RealityServerConnection::new(sc).unwrap(); + let mut hello = Vec::new(); + client.write_tls(&mut hello).unwrap(); + server.validate_client_hello(&hello).unwrap(); + let mut target = separate_target_records( + RealityGroup::X25519, + CipherSuite::AES_128_GCM_SHA256, + &hello[44..76], + ); + let (index, offset) = match case { + "ccs" => (1, 5), + "version" => (2, 2), + "type" => (2, 0), + "length" => (3, 4), + "session" => (0, 44), + "unknown-extension" => (0, 81), + "short" => { + target[3] = Bytes::from_static(&[ + 23, 3, 3, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + ]); + (3, 5) + } + "extra" => { + target.extend([target[5].clone(), target[5].clone()]); + (7, 5) + } + _ => unreachable!(), + }; + let mut bad = target[index].to_vec(); + bad[offset] ^= 1; + target[index] = bad.into(); + assert_eq!( + server.build_server_response(&target).unwrap_err().kind(), + io::ErrorKind::Unsupported, + "{case}" + ); + let mut output = Vec::new(); + server.write_tls(&mut output).unwrap(); + assert!(output.is_empty(), "{case}"); + } +} + +#[test] +fn authenticated_non_contributory_tls_share_forwards_before_commit() { + use super::reality_auth::{derive_auth_key, encrypt_session_id, perform_ecdh}; + let (cc, sc) = configs(CipherSuite::AES_128_GCM_SHA256); + let mut client = RealityClientConnection::new(cc).unwrap(); + let mut hello = Vec::new(); + client.write_tls(&mut hello).unwrap(); + let shares = super::reality_key_exchange::extract_client_key_shares(&hello).unwrap(); + let shared = + perform_ecdh(&sc.private_key, shares.authentication_public_key().unwrap()).unwrap(); + let auth = derive_auth_key(&shared, &hello[11..31], b"REALITY").unwrap(); + let hybrid = shares.hybrid.unwrap(); + let position = hello + .windows(hybrid.len()) + .position(|bytes| bytes == hybrid.as_slice()) + .unwrap(); + hello[position + 1184..position + 1216].fill(0); + let mut aad = hello[5..].to_vec(); + aad[39..71].fill(0); + let mut payload = [0; 16]; + payload[..3].copy_from_slice(&[1, 8, 0]); + payload[8..].fill(1); + let session = encrypt_session_id(&payload, &auth, &hello[31..43], &aad).unwrap(); + hello[44..76].copy_from_slice(&session); + let mut server = RealityServerConnection::new(sc).unwrap(); + server.validate_client_hello(&hello).unwrap(); + let result = server.build_server_response(&target_records( + RealityGroup::X25519MlKem768, + CipherSuite::AES_128_GCM_SHA256, + &session, + )); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Unsupported); + assert!(!server.wants_write()); +} diff --git a/src/reality/reality_server_connection.rs b/src/reality/reality_server_connection.rs index 7b609e02..0232b250 100644 --- a/src/reality/reality_server_connection.rs +++ b/src/reality/reality_server_connection.rs @@ -1,564 +1,138 @@ -// REALITY server-side connection -// -// This implements a rustls-compatible API for REALITY protocol server connections, -// allowing REALITY to be used as a drop-in replacement for rustls. +use std::io; +use std::sync::Arc; -use super::reality_key_exchange::{ - ClientKeyShares, RealityGroup, extract_client_key_shares, extract_server_key_share, - server_exchange, -}; -use aws_lc_rs::digest; -use rand::Rng; -use std::io::{self, Read, Write}; +use bytes::Bytes; use subtle::ConstantTimeEq; +use zeroize::Zeroizing; -use super::common::{ - ALERT_DESC_CLOSE_NOTIFY, ALERT_LEVEL_WARNING, CIPHERTEXT_READ_BUF_CAPACITY, CONTENT_TYPE_ALERT, - CONTENT_TYPE_APPLICATION_DATA, CONTENT_TYPE_CHANGE_CIPHER_SPEC, CONTENT_TYPE_HANDSHAKE, - HANDSHAKE_TYPE_FINISHED, PLAINTEXT_READ_BUF_CAPACITY, TLS_MAX_RECORD_SIZE, - TLS_RECORD_HEADER_SIZE, -}; -use super::reality_aead::{AeadKey, decrypt_handshake_message}; +use super::CipherSuite; use super::reality_auth::{decrypt_session_id, derive_auth_key, perform_ecdh}; use super::reality_certificate::generate_hmac_certificate; -use super::reality_cipher_suite::{CipherSuite, DEFAULT_CIPHER_SUITES}; -use super::reality_io_state::RealityIoState; -use super::reality_reader_writer::{RealityReader, RealityWriter}; -use super::reality_records::{RecordDecryptor, RecordEncryptor}; -use super::reality_tls13_keys::{ - compute_finished_verify_data, derive_application_secrets, derive_handshake_keys, - derive_traffic_keys, -}; -use super::reality_tls13_messages::{ - construct_certificate, construct_certificate_verify, construct_encrypted_extensions, - construct_finished, construct_server_hello, write_record_header, -}; -use super::reality_util::{ - extract_client_cipher_suites, extract_client_random, extract_session_id_slice, - negotiate_cipher_suite, -}; +use super::reality_connection::{RealityTransport, delegate_tls}; +use super::reality_key_exchange::extract_client_key_shares; +use super::reality_rustls::{RealitySigningKey, io_error, provider}; +use super::reality_target_template::flight_plan; +use super::reality_util::{extract_client_random, extract_session_id_slice}; use crate::address::{Address, NetLocation}; -use crate::slide_buffer::SlideBuffer; -use crate::util::allocate_vec; -/// Configuration for REALITY server connections #[derive(Clone)] pub struct RealityServerConfig { - pub mldsa65_key: Option>, - /// Server's X25519 private key (32 bytes) + pub mldsa65_key: Option>, pub private_key: [u8; 32], - /// List of valid short IDs for authentication (8 bytes each) pub short_ids: Vec<[u8; 8]>, - /// Destination server for certificate generation pub dest: NetLocation, - /// Maximum allowed time difference in milliseconds (None = no check) pub max_time_diff: Option, - /// Minimum accepted client version (3 bytes: major.minor.patch) pub min_client_version: Option<[u8; 3]>, - /// Maximum accepted client version (3 bytes: major.minor.patch) pub max_client_version: Option<[u8; 3]>, - /// Supported TLS 1.3 cipher suites (empty = use defaults) pub cipher_suites: Vec, } -/// Handshake state machine for REALITY server -enum HandshakeState { - /// Initial state, waiting for ClientHello - Initial, - /// ClientHello validated, waiting to build response with dest structure - ClientHelloValidated { info: ClientHelloInfo }, - /// ServerHello and encrypted handshake messages sent, waiting for client Finished - ServerHelloSent { - handshake_hash_with_server_finished: Vec, // Hash including server Finished (for verifying client Finished) - client_handshake_traffic_secret: Vec, - master_secret: Vec, - cipher_suite: CipherSuite, - }, - /// Handshake complete, ready for application data - Complete, +struct AuthenticatedHello { + record: Vec, + auth_key: Zeroizing<[u8; 32]>, } -/// Information extracted from ClientHello during validation phase -/// This is passed to build_server_response() to construct the reply -#[derive(Clone)] -pub struct ClientHelloInfo { - /// Session ID from ClientHello (echoed back in ServerHello) - pub session_id: Vec, - /// Keeps authentication and negotiated TLS shares separate for Chrome clients. - pub key_shares: ClientKeyShares, - /// Derived auth key for HMAC certificate - pub auth_key: [u8; 32], - /// Negotiated cipher suite - pub cipher_suite: CipherSuite, - /// Raw ClientHello handshake bytes (for transcript hash) - pub client_hello_handshake: Vec, -} - -/// REALITY server-side connection implementing rustls-compatible API pub struct RealityServerConnection { - // Configuration config: RealityServerConfig, - - // Handshake state - handshake_state: HandshakeState, - - // TLS 1.3 application traffic encryption (post-handshake) - // Keys are cached as AeadKey to avoid per-record key setup overhead - app_read_key: Option, - app_read_iv: Option>, - app_write_key: Option, - app_write_iv: Option>, - read_seq: u64, - write_seq: u64, - cipher_suite: Option, - negotiated_group: Option, - - // Pre-allocated buffer for TLS read operations (reused across calls) - tls_read_buffer: Box<[u8]>, - - // Buffers for I/O - using SlideBuffer for efficient zero-alloc operations - ciphertext_read_buf: SlideBuffer, // Incoming encrypted TLS records - ciphertext_write_buf: Vec, // Outgoing encrypted TLS records - plaintext_read_buf: SlideBuffer, // Decrypted application data - plaintext_write_buf: Vec, // Application data to encrypt - - // Connection state flags (mirrors rustls patterns) - received_close_notify: bool, // Peer sent close_notify alert - fatal_error: Option, // Fatal error occurred, connection unusable + validated: Option, + started: bool, + pub(super) transport: RealityTransport, } impl RealityServerConnection { - /// Create a new REALITY server connection pub fn new(config: RealityServerConfig) -> io::Result { - Ok(RealityServerConnection { + Ok(Self { config, - handshake_state: HandshakeState::Initial, - app_read_key: None, - app_read_iv: None, - app_write_key: None, - app_write_iv: None, - read_seq: 0, - write_seq: 0, - cipher_suite: None, - negotiated_group: None, - tls_read_buffer: allocate_vec(TLS_MAX_RECORD_SIZE).into_boxed_slice(), - ciphertext_read_buf: SlideBuffer::new(CIPHERTEXT_READ_BUF_CAPACITY), - ciphertext_write_buf: Vec::new(), - plaintext_read_buf: SlideBuffer::new(PLAINTEXT_READ_BUF_CAPACITY), - plaintext_write_buf: Vec::new(), - received_close_notify: false, - fatal_error: None, + validated: None, + started: false, + transport: RealityTransport::default(), }) } - #[cfg(test)] - pub(crate) fn complete_for_test(mut self) -> io::Result { - let cipher_suite = CipherSuite::AES_128_GCM_SHA256; - let key = vec![0; cipher_suite.key_len()]; - let iv = vec![0; cipher_suite.nonce_len()]; - - self.handshake_state = HandshakeState::Complete; - self.app_read_key = Some(AeadKey::new(cipher_suite, &key)?); - self.app_read_iv = Some(iv.clone()); - self.app_write_key = Some(AeadKey::new(cipher_suite, &key)?); - self.app_write_iv = Some(iv); - self.cipher_suite = Some(cipher_suite); - Ok(self) - } - - /// Read TLS messages from the provided reader into internal buffer - /// - /// This does NOT decrypt - call process_new_packets() for that. - /// Uses pre-allocated buffer to avoid allocation on every call. - pub fn read_tls(&mut self, rd: &mut dyn Read) -> io::Result { - // Compact if remaining capacity is insufficient for a full TLS record - if self.ciphertext_read_buf.remaining_capacity() < TLS_MAX_RECORD_SIZE { - self.ciphertext_read_buf.compact(); - } - - // Read into pre-allocated buffer - let n = rd.read(&mut self.tls_read_buffer[..])?; - if n > 0 { - self.ciphertext_read_buf - .extend_from_slice(&self.tls_read_buffer[..n]); - } - Ok(n) - } - - /// Process buffered TLS messages and advance handshake/decrypt data - /// - /// Returns I/O state with available plaintext bytes and write status. - /// Like rustls, this loops until no more progress can be made, ensuring - /// that piggybacked application data (e.g., VLESS request sent with TLS Finished) - /// is processed in the same call. - pub fn process_new_packets(&mut self) -> io::Result { - // Return persisted error if connection is in fatal error state (rustls pattern) - if let Some(error_kind) = self.fatal_error { - return Err(io::Error::new(error_kind, "connection previously failed")); - } - - // Don't process more data after receiving close_notify (RFC 8446) - if self.received_close_notify { - return Ok(RealityIoState::new(self.plaintext_read_buf.len())); - } - - let result = self.process_new_packets_inner(); - - // Persist fatal errors - if let Err(ref e) = result { - // Persist error for certain error kinds that indicate fatal connection failure - match e.kind() { - io::ErrorKind::InvalidData - | io::ErrorKind::PermissionDenied - | io::ErrorKind::ConnectionAborted => { - self.fatal_error = Some(e.kind()); - } - _ => {} - } - } - - result - } - - /// Inner implementation of process_new_packets - fn process_new_packets_inner(&mut self) -> io::Result { - loop { - match &self.handshake_state { - HandshakeState::Initial | HandshakeState::ClientHelloValidated { .. } => { - // Initial: ClientHello must be passed via validate_client_hello() - // ClientHelloValidated: Response must be built via build_server_response() - // Neither should be reached during process_new_packets - break; - } - HandshakeState::ServerHelloSent { .. } => { - if !self.process_client_finished()? { - break; - } - } - HandshakeState::Complete => { - self.process_application_data()?; - break; - } - } - } - - Ok(RealityIoState::new(self.plaintext_read_buf.len())) - } - - /// Public API: Validate ClientHello - /// - /// This performs authentication (ECDH, decrypt session_id, validate short_id/timestamp/version) - /// but does NOT build the server response. Call build_server_response() after to complete. - /// - /// Returns Ok(()) on success, Err(PermissionDenied) on auth failure. - pub fn validate_client_hello(&mut self, client_hello: &[u8]) -> io::Result<()> { - // Return persisted error if connection is in fatal error state - if let Some(error_kind) = self.fatal_error { - return Err(io::Error::new(error_kind, "connection previously failed")); - } - - // Must be in Initial state - if !matches!(self.handshake_state, HandshakeState::Initial) { + pub fn validate_client_hello(&mut self, hello: &[u8]) -> io::Result<()> { + if self.started { return Err(io::Error::new( io::ErrorKind::InvalidInput, - "validate_client_hello called in wrong state", + "REALITY authentication already attempted", )); } - - // Process ClientHello validation - let result = self.process_client_hello_validation(client_hello); - - // Persist fatal errors - if let Err(ref e) = result { - match e.kind() { - io::ErrorKind::InvalidData - | io::ErrorKind::PermissionDenied - | io::ErrorKind::ConnectionAborted => { - self.fatal_error = Some(e.kind()); - } - _ => {} - } - } - - result - } - - /// Public API: Build server response using dest's record structure as template - /// - /// Call this after validate_client_hello() succeeds. Pass the TLS records - /// received from the destination server to match their structure. - /// - /// dest_records should contain: [ServerHello, CCS, encrypted_handshake..., NewSessionTicket...] - /// Unsupported indicates an incompatible target or peer share; other errors are fatal. - pub fn build_server_response(&mut self, dest_records: &[bytes::Bytes]) -> io::Result<()> { - // Must be in ClientHelloValidated state - if !matches!( - self.handshake_state, - HandshakeState::ClientHelloValidated { .. } - ) { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "build_server_response called in wrong state", - )); - } - - self.build_server_response_internal(dest_records) - } - - /// Phase 1: Validate ClientHello and extract info for later response building - #[inline] - fn process_client_hello_validation(&mut self, client_hello: &[u8]) -> io::Result<()> { - // Validate minimum length (TLS record header + some content) - if client_hello.len() < TLS_RECORD_HEADER_SIZE + 4 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "ClientHello too short", - )); - } - - // Extract fields from ClientHello - let client_random = extract_client_random(client_hello)?; - let session_id = extract_session_id_slice(client_hello)?; - let key_shares = extract_client_key_shares(client_hello)?; - let client_public_key = key_shares.authentication_public_key()?; - - log::debug!( - "REALITY: ClientHello received, client_random: {:?}", - &client_random[..8] - ); - - // Perform ECDH to derive auth key - let shared_secret = perform_ecdh(&self.config.private_key, client_public_key) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; - - let salt = &client_random[0..20]; - let auth_key = derive_auth_key(&shared_secret, salt, b"REALITY") - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?; - - // Validate session ID (contains encrypted metadata) - if session_id.len() != 32 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Invalid session ID length", - )); - } - - let nonce = &client_random[20..32]; - let mut encrypted_session_id_arr = [0u8; 32]; - encrypted_session_id_arr.copy_from_slice(session_id); - - // Reconstruct AAD with zeros at SessionId location - let client_hello_handshake = &client_hello[TLS_RECORD_HEADER_SIZE..]; - let mut aad_for_decryption = client_hello_handshake.to_vec(); - if aad_for_decryption.len() >= 39 + 32 { - aad_for_decryption[39..39 + 32].fill(0); - } - - let decrypted_session_id = decrypt_session_id( - &encrypted_session_id_arr, - &auth_key, - nonce, - &aad_for_decryption, - ) - .map_err(|e| { - io::Error::new( - io::ErrorKind::PermissionDenied, - format!("Session ID decrypt failed: {:?}", e), - ) + self.started = true; + let random = extract_client_random(hello)?; + let session = extract_session_id_slice(hello)?; + let shares = extract_client_key_shares(hello)?; + let peer = shares.authentication_public_key()?; + let shared = Zeroizing::new(perform_ecdh(&self.config.private_key, peer)?); + let auth_key = Zeroizing::new(derive_auth_key(&shared, &random[..20], b"REALITY")?); + let session: &[u8; 32] = session.try_into().map_err(|_| { + io::Error::new(io::ErrorKind::InvalidData, "Invalid REALITY session ID") })?; - - // Validate session ID contents - let client_version = &decrypted_session_id[0..3]; - let client_timestamp = u32::from_be_bytes([ - decrypted_session_id[4], - decrypted_session_id[5], - decrypted_session_id[6], - decrypted_session_id[7], - ]) as u64; - let client_short_id = &decrypted_session_id[8..16]; - - log::debug!("REALITY: Client version: {:?}", client_version); - log::debug!("REALITY: Client timestamp: {}", client_timestamp); - - // Validate short ID using constant-time comparison - let mut client_short_id_arr = [0u8; 8]; - client_short_id_arr.copy_from_slice(client_short_id); - let short_id_ok = self.config.short_ids.iter().fold(false, |acc, valid_id| { - acc | (client_short_id_arr.ct_eq(valid_id).unwrap_u8() == 1) - }); - - if !short_id_ok { - log::warn!("REALITY: Client short_id not in configured list"); - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - "Invalid short_id", - )); + let mut aad = hello[5..].to_vec(); + aad[39..71].fill(0); + let metadata = Zeroizing::new( + decrypt_session_id(session, &auth_key, &random[20..], &aad) + .map_err(|_| denied("REALITY session authentication failed"))?, + ); + let version: [u8; 3] = metadata[..3].try_into().unwrap(); + let short_id: [u8; 8] = metadata[8..16].try_into().unwrap(); + if !self + .config + .short_ids + .iter() + .fold(false, |found, id| found | bool::from(short_id.ct_eq(id))) + { + return Err(denied("Invalid REALITY short ID")); } - - // Validate timestamp if max_time_diff is configured - if let Some(max_diff_ms) = self.config.max_time_diff { + if self + .config + .min_client_version + .is_some_and(|min| version < min) + || self + .config + .max_client_version + .is_some_and(|max| version > max) + { + return Err(denied("Unsupported REALITY client version")); + } + if let Some(max_ms) = self.config.max_time_diff { + let timestamp = u32::from_be_bytes(metadata[4..8].try_into().unwrap()) as u64; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_err(|_| io::Error::other("System time error"))? .as_secs(); - - let time_diff_secs = now.abs_diff(client_timestamp); - let max_diff_secs = max_diff_ms / 1000; - - if time_diff_secs > max_diff_secs { - log::warn!( - "REALITY: Client timestamp {} differs from server {} by {} seconds (max: {} seconds)", - client_timestamp, - now, - time_diff_secs, - max_diff_secs - ); - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - format!( - "Timestamp difference {} seconds exceeds maximum {} seconds", - time_diff_secs, max_diff_secs - ), - )); + if now.abs_diff(timestamp) > max_ms / 1000 { + return Err(denied("REALITY timestamp outside allowed window")); } } - - // Validate client version (min) - if let Some(min_ver) = &self.config.min_client_version - && client_version < &min_ver[..] - { - log::warn!( - "REALITY: Client version {:?} is below minimum {:?}", - client_version, - min_ver - ); - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - format!( - "Client version {:?} is below minimum {:?}", - client_version, min_ver - ), - )); - } - - // Validate client version (max) - if let Some(max_ver) = &self.config.max_client_version - && client_version > &max_ver[..] - { - log::warn!( - "REALITY: Client version {:?} is above maximum {:?}", - client_version, - max_ver - ); - return Err(io::Error::new( - io::ErrorKind::PermissionDenied, - format!( - "Client version {:?} is above maximum {:?}", - client_version, max_ver - ), - )); - } - - log::debug!( - "REALITY: Client authentication successful - version: {:?}, timestamp: {}", - client_version, - client_timestamp - ); - - // Negotiate cipher suite with client - let client_cipher_suites = extract_client_cipher_suites(client_hello)?; - let server_cipher_suites = if self.config.cipher_suites.is_empty() { - DEFAULT_CIPHER_SUITES.to_vec() - } else { - self.config.cipher_suites.clone() - }; - let cipher_suite = negotiate_cipher_suite(&server_cipher_suites, &client_cipher_suites) - .ok_or_else(|| { - io::Error::new( - io::ErrorKind::InvalidData, - "No common TLS 1.3 cipher suite found", - ) - })?; - log::debug!( - "REALITY: Negotiated cipher suite {:?} (client offered: {:04x?})", - cipher_suite, - client_cipher_suites - ); - - // Store validated info for response building - self.handshake_state = HandshakeState::ClientHelloValidated { - info: ClientHelloInfo { - session_id: session_id.to_vec(), - key_shares, - auth_key, - cipher_suite, - client_hello_handshake: client_hello_handshake.to_vec(), - }, - }; - + self.validated = Some(AuthenticatedHello { + record: hello.to_vec(), + auth_key, + }); Ok(()) } - /// Phase 2: Build server response using dest's record structure as template - fn build_server_response_internal(&mut self, dest_records: &[bytes::Bytes]) -> io::Result<()> { - // Take ownership of info from state (state already validated by caller) - let HandshakeState::ClientHelloValidated { info } = - std::mem::replace(&mut self.handshake_state, HandshakeState::Initial) - else { - unreachable!() - }; - - let cipher_suite = info.cipher_suite; - - let target_hello = dest_records.first().ok_or_else(|| { - io::Error::new(io::ErrorKind::Unsupported, "Missing target ServerHello") + pub fn build_server_response(&mut self, records: &[Bytes]) -> io::Result<()> { + let authenticated = self.validated.take().ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "REALITY ClientHello not authenticated", + ) })?; - let group = extract_server_key_share(target_hello) - .map_err(|e| io::Error::new(io::ErrorKind::Unsupported, e))? - .group; - let (server_share, tls_shared_secret) = server_exchange(group, &info.key_shares)?; - self.negotiated_group = Some(group); - let mut rng = rand::rng(); - - // Generate server random - let mut server_random = [0u8; 32]; - rng.fill_bytes(&mut server_random); - - // Build ServerHello - let server_hello = construct_server_hello( - &server_random, - &info.session_id, - cipher_suite.id(), - group, - &server_share, - )?; - - // Compute transcript hashes using cipher suite's digest algorithm - let digest_alg = cipher_suite.digest_algorithm(); - - let mut ch_transcript = digest::Context::new(digest_alg); - ch_transcript.update(&info.client_hello_handshake); - let client_hello_hash = ch_transcript.finish(); - - let mut ch_sh_transcript = digest::Context::new(digest_alg); - ch_sh_transcript.update(&info.client_hello_handshake); - ch_sh_transcript.update(&server_hello); - - let mut handshake_transcript = ch_sh_transcript.clone(); - let server_hello_hash = ch_sh_transcript.finish(); - - // Derive TLS 1.3 keys - let hs_keys = derive_handshake_keys( - group, - cipher_suite, - &tls_shared_secret, - client_hello_hash.as_ref(), - server_hello_hash.as_ref(), - )?; - - // Get destination hostname for certificate - let dest_hostname = match self.config.dest.address() { - Address::Hostname(h) => h.as_str(), + let plan = flight_plan(records)?; + let crypto = provider(&self.config.cipher_suites); + let hello = &authenticated.record[5..]; + let prepared = rustls::reality::PreparedServerHello::new(hello, &records[0][5..], &crypto) + .map_err(|error| match error { + rustls::Error::PeerMisbehaved(rustls::PeerMisbehaved::InvalidKeyShare) => { + io::Error::new( + io::ErrorKind::Unsupported, + "Unsupported REALITY peer key share", + ) + } + error => io_error(error), + })? + .with_flight_plan(plan); + let hostname = match self.config.dest.address() { + Address::Hostname(hostname) => hostname, _ => { return Err(io::Error::new( io::ErrorKind::InvalidInput, @@ -566,863 +140,59 @@ impl RealityServerConnection { )); } }; - - // Generate HMAC-signed certificate - let mldsa = self.config.mldsa65_key.as_deref().map(|key| { - ( - key, - info.client_hello_handshake.as_slice(), - server_hello.as_slice(), - ) - }); - let (cert, signing_key) = generate_hmac_certificate(&info.auth_key, dest_hostname, mldsa)?; - - // Build encrypted handshake messages - let encrypted_extensions = construct_encrypted_extensions()?; - handshake_transcript.update(&encrypted_extensions); - - let certificate = construct_certificate(cert)?; - handshake_transcript.update(&certificate); - - let cert_verify_hash = handshake_transcript.clone().finish(); - let certificate_verify = - construct_certificate_verify(&signing_key, cert_verify_hash.as_ref())?; - handshake_transcript.update(&certificate_verify); - - let handshake_hash_before_finished = handshake_transcript.clone().finish(); - - // Derive server handshake traffic keys for encryption - let (server_hs_key, server_hs_iv) = - derive_traffic_keys(&hs_keys.server_handshake_traffic_secret, cipher_suite)?; - - // Build server Finished message - let server_verify_data = compute_finished_verify_data( - cipher_suite, - &hs_keys.server_handshake_traffic_secret, - handshake_hash_before_finished.as_ref(), - )?; - let server_finished = construct_finished(&server_verify_data)?; - - // Analyze dest's record structure to determine how to encrypt - // dest_records: [0]=ServerHello, [1]=CCS, [2..]=encrypted handshake, possibly NewSessionTicket - let dest_encrypted_records: Vec<&bytes::Bytes> = if dest_records.len() > 2 { - dest_records[2..].iter().collect() - } else { - vec![] - }; - - // Build handshake messages array - let messages: [&[u8]; 4] = [ - &encrypted_extensions, - &certificate, - &certificate_verify, - &server_finished, - ]; - - // Encrypt handshake messages, matching dest's structure exactly - let mut handshake_ciphertext = Vec::new(); - let mut handshake_seq = 0u64; - let hs_aead_key = AeadKey::new(cipher_suite, &server_hs_key)?; - - // Determine if dest uses combined mode or separate mode using 512-byte heuristic - // Like XTLS/REALITY: if first encrypted record > 512 bytes, it's combined mode - let is_combined_mode = match dest_encrypted_records.first() { - Some(first_record) => first_record.len() > 512, - None => true, // No encrypted records = default to combined mode - }; - - if is_combined_mode { - // Combined mode: all messages in one record (with optional padding) - let mut combined_plaintext = Vec::new(); - for msg in &messages { - combined_plaintext.extend_from_slice(msg); - } - - let target_size = dest_encrypted_records.first().map(|r| r.len()).unwrap_or(0); - if self.config.mldsa65_key.is_some() { - check_mldsa_record_capacity(combined_plaintext.len(), target_size)?; - } - - log::debug!( - "REALITY SERVER: Combined mode - EE={}, Cert={}, CV={}, Fin={}, Total={}, target={}", - encrypted_extensions.len(), - certificate.len(), - certificate_verify.len(), - server_finished.len(), - combined_plaintext.len(), - target_size - ); - - let mut encryptor = - RecordEncryptor::new(&hs_aead_key, &server_hs_iv, &mut handshake_seq); - encryptor.encrypt_handshake_with_padding( - &combined_plaintext, - &mut handshake_ciphertext, - target_size, - )?; - } else { - // Separate mode: encrypt each message as its own record, matching dest's sizes - log::debug!( - "REALITY SERVER: Separate mode - {} dest records, encrypting {} messages separately", - dest_encrypted_records.len(), - messages.len() - ); - - let mut encryptor = - RecordEncryptor::new(&hs_aead_key, &server_hs_iv, &mut handshake_seq); - - for (i, msg) in messages.iter().enumerate() { - let target_size = dest_encrypted_records.get(i).map(|r| r.len()).unwrap_or(0); - if self.config.mldsa65_key.is_some() { - check_mldsa_record_capacity(msg.len(), target_size)?; - } - encryptor.encrypt_handshake_with_padding( - msg, - &mut handshake_ciphertext, - target_size, - )?; - } - } - - // Update transcript with server Finished - handshake_transcript.update(&server_finished); - let handshake_hash_with_server_finished = handshake_transcript.finish(); - - // Buffer all handshake messages to write buffer - // ServerHello (plaintext) - self.ciphertext_write_buf - .extend_from_slice(&write_record_header( - CONTENT_TYPE_HANDSHAKE, - server_hello.len() as u16, - )); - self.ciphertext_write_buf.extend_from_slice(&server_hello); - - // ChangeCipherSpec (for compatibility) - self.ciphertext_write_buf - .extend_from_slice(&write_record_header(CONTENT_TYPE_CHANGE_CIPHER_SPEC, 1)); - self.ciphertext_write_buf.push(0x01); - - // Encrypted handshake record(s) - self.ciphertext_write_buf - .extend_from_slice(&handshake_ciphertext); - - log::debug!( - "REALITY: ServerHello and encrypted handshake messages buffered ({} bytes)", - self.ciphertext_write_buf.len() + let mldsa = self + .config + .mldsa65_key + .as_deref() + .map(|key| (key, hello, prepared.server_hello())); + let (certificate, key) = + generate_hmac_certificate(&authenticated.auth_key, hostname, mldsa)?; + let key = rustls::sign::CertifiedKey::new( + vec![certificate.der().clone()], + Arc::new(RealitySigningKey::new(key)), ); - - // Update handshake state - self.handshake_state = HandshakeState::ServerHelloSent { - handshake_hash_with_server_finished: handshake_hash_with_server_finished - .as_ref() - .to_vec(), - client_handshake_traffic_secret: hs_keys.client_handshake_traffic_secret.clone(), - master_secret: hs_keys.master_secret, - cipher_suite, - }; - - Ok(()) - } - - /// Process client's Finished message and complete handshake - /// Returns true if a complete record was processed, false if more data needed - #[inline] - fn process_client_finished(&mut self) -> io::Result { - // Check if we have enough data for a TLS record header BEFORE extracting state - if self.ciphertext_read_buf.len() < TLS_RECORD_HEADER_SIZE { - return Ok(false); // Need more data - } - - // Check for ChangeCipherSpec (TLS 1.3 compatibility message) - if self.ciphertext_read_buf[0] == CONTENT_TYPE_CHANGE_CIPHER_SPEC { - // ChangeCipherSpec record - let ccs_len = self - .ciphertext_read_buf - .get_u16_be(3) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Buffer too short"))? - as usize; - - let record_size = super::common::checked_record_size(ccs_len)?; - if ccs_len != 1 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid ChangeCipherSpec length", - )); - } - if self.ciphertext_read_buf.len() < record_size { - return Ok(false); // Need more data - } - if self.ciphertext_read_buf[TLS_RECORD_HEADER_SIZE] != 1 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "invalid ChangeCipherSpec payload", - )); - } - - // Skip ChangeCipherSpec (compatibility message) - log::debug!("REALITY: Skipping ChangeCipherSpec (compatibility message)"); - self.ciphertext_read_buf.consume(record_size); - - // Check if we have the next record header - if self.ciphertext_read_buf.len() < TLS_RECORD_HEADER_SIZE { - return Ok(false); // Need more data - } - } - - // Parse TLS record length - let record_len = self - .ciphertext_read_buf - .get_u16_be(3) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Buffer too short"))? - as usize; - - // Check if we have the complete record - let total_record_len = super::common::checked_record_size(record_len)?; - if self.ciphertext_read_buf.len() < total_record_len { - return Ok(false); // Need more data - } - - // Verify it's ApplicationData (encrypted Finished) - if self.ciphertext_read_buf[0] != CONTENT_TYPE_APPLICATION_DATA { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - format!( - "Expected ApplicationData (0x17), got 0x{:02x}", - self.ciphertext_read_buf[0] - ), - )); - } - - // NOW we're committed to processing - take ownership of handshake state - // This avoids cloning Vec fields - let old_state = std::mem::replace(&mut self.handshake_state, HandshakeState::Initial); - let HandshakeState::ServerHelloSent { - client_handshake_traffic_secret, - master_secret, - cipher_suite, - handshake_hash_with_server_finished, - } = old_state - else { - unreachable!() - }; - - // Extract the encrypted Finished record (copy to Vec for decryption) - let record: Vec = self.ciphertext_read_buf[..total_record_len].to_vec(); - self.ciphertext_read_buf.consume(total_record_len); - let ciphertext = &record[TLS_RECORD_HEADER_SIZE..]; // Skip TLS record header - - // Derive client handshake traffic keys for decryption - let (client_hs_key, client_hs_iv) = - derive_traffic_keys(&client_handshake_traffic_secret, cipher_suite)?; - - // Decrypt the Finished message (sequence number = 0 for client's first encrypted record) - let plaintext = decrypt_handshake_message( - cipher_suite, - &client_hs_key, - &client_hs_iv, - 0, // Client's first encrypted record - ciphertext, - record_len as u16, - )?; - - // Verify it's a Finished message (type 0x14) - if plaintext.is_empty() || plaintext[0] != HANDSHAKE_TYPE_FINISHED { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Expected Finished message", - )); - } - - // Extract verify_data (skip type(1) + length(3) = 4 bytes) - if plaintext.len() < 4 { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Finished message too short", - )); - } - let client_verify_data = &plaintext[4..]; - - // Compute expected client Finished verify_data - // Use hash that includes server Finished (per TLS 1.3 RFC 8446) - let expected_verify_data = compute_finished_verify_data( - cipher_suite, - &client_handshake_traffic_secret, - &handshake_hash_with_server_finished, - )?; - - // Verify it matches using constant-time comparison to prevent timing attacks - if client_verify_data - .ct_eq(expected_verify_data.as_slice()) - .unwrap_u8() - == 0 - { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Client Finished verify_data mismatch", - )); - } - - log::debug!("REALITY: Client Finished verified successfully"); - - // Derive application secrets - // Use hash that includes server Finished (per TLS 1.3 RFC 8446) - let (client_app_secret, server_app_secret) = derive_application_secrets( - cipher_suite, - &master_secret, - &handshake_hash_with_server_finished, - )?; - - // Derive application traffic keys - let (client_app_key_bytes, client_app_iv) = - derive_traffic_keys(&client_app_secret, cipher_suite)?; - let (server_app_key_bytes, server_app_iv) = - derive_traffic_keys(&server_app_secret, cipher_suite)?; - - // Create cached AeadKey objects to avoid per-record key setup overhead - let client_app_key = AeadKey::new(cipher_suite, &client_app_key_bytes)?; - let server_app_key = AeadKey::new(cipher_suite, &server_app_key_bytes)?; - - // Store application traffic keys (as cached AeadKey) - self.app_read_key = Some(client_app_key); - self.app_read_iv = Some(client_app_iv); - self.app_write_key = Some(server_app_key); - self.app_write_iv = Some(server_app_iv); - self.read_seq = 0; - self.write_seq = 0; - self.cipher_suite = Some(cipher_suite); - - self.handshake_state = HandshakeState::Complete; - - log::debug!("REALITY: Handshake complete, application keys derived"); - log::debug!( - "REALITY: negotiated_group={}", - self.negotiated_group() - .map(RealityGroup::name) - .unwrap_or("unknown") - ); - - Ok(true) - } - - /// Decrypt application data using TLS 1.3 keys - /// Processes all complete TLS records in the buffer - #[inline] - fn process_application_data(&mut self) -> io::Result<()> { - // Check if we have application keys - let (app_read_key, app_read_iv) = match (&self.app_read_key, &self.app_read_iv) { - (Some(key), Some(iv)) => (key, iv), - _ => unreachable!(), // Wrong state - }; - - // Process all complete TLS records in the buffer - while self.ciphertext_read_buf.len() >= 5 { - // Parse TLS record header - let record_len = self - .ciphertext_read_buf - .get_u16_be(3) - .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Buffer too short"))? - as usize; - - // Check if we have the complete record - let total_record_len = super::common::checked_record_size(record_len)?; - if self.ciphertext_read_buf.len() < total_record_len { - break; // Need more data - } - - // Decrypt in-place: get mutable slice of ciphertext, decrypt, copy plaintext out - let ciphertext_slice = self - .ciphertext_read_buf - .slice_mut(TLS_RECORD_HEADER_SIZE..total_record_len); - let mut decryptor = RecordDecryptor::new(app_read_key, app_read_iv, &mut self.read_seq); - let (content_type, plaintext) = - decryptor.decrypt_record_in_place(ciphertext_slice, record_len as u16)?; - - match content_type { - CONTENT_TYPE_APPLICATION_DATA => { - // Compact plaintext buffer if needed before extending - self.plaintext_read_buf.maybe_compact(4096); - self.plaintext_read_buf.extend_from_slice(plaintext); - } - CONTENT_TYPE_ALERT => { - // Parse alert: level (1 byte) + description (1 byte) - if plaintext.len() >= 2 { - let alert_level = plaintext[0]; - let alert_desc = plaintext[1]; - - if alert_desc == ALERT_DESC_CLOSE_NOTIFY { - log::debug!("REALITY: Received close_notify alert"); - self.received_close_notify = true; - // Per RFC 8446: "Any data received after a closure alert - // has been received MUST be ignored." - return Ok(()); - } else if alert_level != ALERT_LEVEL_WARNING { - // Fatal alert - connection must be terminated - log::warn!( - "REALITY: Received fatal alert: level={}, desc={}", - alert_level, - alert_desc - ); - return Err(io::Error::new( - io::ErrorKind::ConnectionAborted, - format!("received fatal alert: {}", alert_desc), - )); - } else { - log::debug!("REALITY: Received warning alert: desc={}", alert_desc); - } - } - } - // CONTENT_TYPE_HANDSHAKE is invalid after handshake complete - // strip_content_type() validates and returns error for invalid types - _ => unreachable!( - "strip_content_type validates content type; unexpected: 0x{:02x}", - content_type - ), - } - - // Consume the processed record from the buffer (after plaintext borrow ends) - self.ciphertext_read_buf.consume(total_record_len); - } - - Ok(()) - } - - /// Get a reader for accessing decrypted plaintext - pub fn reader(&mut self) -> RealityReader<'_> { - // SlideBuffer handles compaction internally via maybe_compact() - // Compact before returning reader if we've consumed significant data - self.plaintext_read_buf.maybe_compact(4096); - RealityReader::new(&mut self.plaintext_read_buf, self.received_close_notify) - } - - /// Get a writer for buffering plaintext to be encrypted - pub fn writer(&mut self) -> RealityWriter<'_> { - RealityWriter::new( - &mut self.plaintext_write_buf, - self.ciphertext_write_buf.len(), - ) - } - - /// Write buffered TLS messages to the provided writer - /// - /// This encrypts any pending plaintext and writes ciphertext. - /// Large plaintext is automatically fragmented into multiple TLS records - /// to comply with the TLS 1.3 record size limit. - pub fn write_tls(&mut self, wr: &mut dyn Write) -> io::Result { - // If handshake not complete, just write buffered handshake data - if !matches!(self.handshake_state, HandshakeState::Complete) { - let n = wr.write(&self.ciphertext_write_buf)?; - self.ciphertext_write_buf.drain(..n); - return Ok(n); - } - - // Encrypt any pending plaintext (with automatic fragmentation for large data) - if !self.plaintext_write_buf.is_empty() { - let (app_write_key, app_write_iv) = match (&self.app_write_key, &self.app_write_iv) { - (Some(key), Some(iv)) => (key, iv), - _ => { - return Err(io::Error::new( - io::ErrorKind::InvalidData, - "Application keys not available", - )); - } - }; - - let mut encryptor = - RecordEncryptor::new(app_write_key, app_write_iv, &mut self.write_seq); - encryptor.encrypt_app_data( - &mut self.plaintext_write_buf, - &mut self.ciphertext_write_buf, - )?; - } - - // Write buffered ciphertext - let n = wr.write(&self.ciphertext_write_buf)?; - self.ciphertext_write_buf.drain(..n); - Ok(n) - } - - /// Check if the connection wants to write data - pub fn wants_write(&self) -> bool { - !self.ciphertext_write_buf.is_empty() || !self.plaintext_write_buf.is_empty() - } - - /// Check if handshake is still in progress - pub fn is_handshaking(&self) -> bool { - !matches!(self.handshake_state, HandshakeState::Complete) - } - - pub fn negotiated_group(&self) -> Option { - if self.is_handshaking() { - None - } else { - self.negotiated_group - } - } - - /// Check if the connection wants to read more TLS data - /// - /// Returns true if we need more data to make progress (handshake or decryption). - /// This mirrors rustls::Connection::wants_read(). - pub fn wants_read(&self) -> bool { - // Don't read more after receiving close_notify (RFC 8446) - if self.received_close_notify { - return false; - } - - // Don't read more if we're in a fatal error state - if self.fatal_error.is_some() { - return false; - } - - // During handshake, we always want to read - if self.is_handshaking() { - return true; - } - - // After handshake, we want to read if: - // 1. Plaintext buffer is empty (need more application data), OR - // 2. Ciphertext buffer has incomplete records that need more data - // - // Note: If plaintext buffer has data, the caller should consume it first. - // If ciphertext buffer has complete records, process_new_packets should be called. - self.plaintext_read_buf.is_empty() - } - - /// Queue a close notification alert - pub fn send_close_notify(&mut self) { - // In TLS 1.3, alerts must be encrypted like application data - if !matches!(self.handshake_state, HandshakeState::Complete) { - log::debug!("REALITY: Cannot send close_notify - handshake not complete"); - return; - } - - // Get application keys - let (app_write_key, app_write_iv) = match (&self.app_write_key, &self.app_write_iv) { - (Some(key), Some(iv)) => (key, iv), - _ => { - log::debug!("REALITY: Cannot send close_notify - application keys not available"); - return; - } - }; - - // Encrypt close_notify alert using RecordEncryptor - let mut encryptor = RecordEncryptor::new(app_write_key, app_write_iv, &mut self.write_seq); - match encryptor.encrypt_close_notify(&mut self.ciphertext_write_buf) { - Ok(()) => { - log::debug!("REALITY: Encrypted close_notify alert queued"); - } - Err(e) => { - log::error!("REALITY: Failed to encrypt close_notify: {}", e); - } - } - } -} - -fn check_mldsa_record_capacity(plaintext_len: usize, target_size: usize) -> io::Result<()> { - let overhead = TLS_RECORD_HEADER_SIZE + 1 + 16; - if plaintext_len > super::common::MAX_TLS_PLAINTEXT_LEN - || target_size < plaintext_len + overhead - || target_size > super::common::MAX_TLS_PLAINTEXT_LEN + overhead - { - return Err(io::Error::new( - io::ErrorKind::Unsupported, - "Camouflage target record has insufficient capacity for ML-DSA-65 handshake", - )); - } - Ok(()) -} - -#[inline] -pub fn feed_reality_server_connection( - server_connection: &mut RealityServerConnection, - data: &[u8], -) -> std::io::Result<()> { - let mut cursor = std::io::Cursor::new(data); - let mut i = 0; - while i < data.len() { - let n = server_connection.read_tls(&mut cursor).map_err(|e| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - format!("failed to feed TLS connection: {e}"), - ) - })?; - i += n; - } - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[track_caller] - fn complete_tls_records(flight: &[u8]) -> Vec { - let mut deframer = crate::crypto::tls_deframer::TlsDeframer::new(); - deframer.feed(flight); - let records = deframer.next_records().unwrap(); - assert!(deframer.into_remaining_data().is_empty()); - records - } - - #[test] - fn fragmented_tls_template_completes_separate_mode_handshake() { - use crate::reality::reality_client_connection::feed_reality_client_connection; - use crate::reality::{RealityClientConfig, RealityClientConnection}; - use crate::shadow_tls::parse_server_hello; - use aws_lc_rs::agreement; - use shoes_test_support::test_servers::reality_tls_template_config; - - let private_key = [1; 32]; - let public_key = agreement::PrivateKey::from_private_key(&agreement::X25519, &private_key) - .unwrap() - .compute_public_key() - .unwrap(); - let mut client = RealityClientConnection::new(RealityClientConfig { - mldsa65_verify: None, - public_key: public_key.as_ref().try_into().unwrap(), - short_id: [2; 8], - server_name: "localhost".into(), - cipher_suites: vec![CipherSuite::AES_128_GCM_SHA256], - }) - .unwrap(); - let mut client_hello = Vec::new(); - client.write_tls(&mut client_hello).unwrap(); - - let mut template = - rustls::ServerConnection::new(reality_tls_template_config().unwrap()).unwrap(); - assert_eq!( - template.read_tls(&mut &client_hello[..]).unwrap(), - client_hello.len() - ); - template.process_new_packets().unwrap(); - let mut template_flight = Vec::new(); - while template.wants_write() { - assert!(template.write_tls(&mut template_flight).unwrap() > 0); - } - assert!(template.is_handshaking()); - assert_eq!( - template.protocol_version(), - Some(rustls::ProtocolVersion::TLSv1_3) - ); - - let template_records = complete_tls_records(&template_flight); - assert!( - template_records.len() >= 6, - "template must emit its full flight before client Finished" - ); - let server_hello = &template_records[0]; - assert_eq!(server_hello[0], CONTENT_TYPE_HANDSHAKE); - assert_eq!(server_hello[5], 2); - let handshake_length = - u32::from_be_bytes([0, server_hello[6], server_hello[7], server_hello[8]]) as usize; - assert_eq!( - server_hello.len(), - TLS_RECORD_HEADER_SIZE + 4 + handshake_length - ); - assert!(parse_server_hello(server_hello).unwrap().is_tls13); - assert_eq!( - &template_records[1][..], - &[CONTENT_TYPE_CHANGE_CIPHER_SPEC, 3, 3, 0, 1, 1] - ); - for record in &template_records[2..] { - assert_eq!(record[0], CONTENT_TYPE_APPLICATION_DATA); - assert!(record.len() <= 512); - } - - let mut server = RealityServerConnection::new(RealityServerConfig { - mldsa65_key: None, - private_key, - short_ids: vec![[2; 8]], - dest: NetLocation::new(Address::Hostname("localhost".into()), 443), - max_time_diff: None, - min_client_version: None, - max_client_version: None, - cipher_suites: vec![CipherSuite::AES_128_GCM_SHA256], - }) - .unwrap(); - server.validate_client_hello(&client_hello).unwrap(); - server.build_server_response(&template_records).unwrap(); - let mut server_flight = Vec::new(); - server.write_tls(&mut server_flight).unwrap(); - let server_records = complete_tls_records(&server_flight); - assert_eq!(server_records.len(), 6); - assert!(parse_server_hello(&server_records[0]).unwrap().is_tls13); - assert_eq!( - &server_records[1][..], - &[CONTENT_TYPE_CHANGE_CIPHER_SPEC, 3, 3, 0, 1, 1] - ); - for record in &server_records[2..] { - assert_eq!(record[0], CONTENT_TYPE_APPLICATION_DATA); - } - - for (index, record) in server_records.iter().enumerate() { - feed_reality_client_connection(&mut client, record).unwrap(); - client.process_new_packets().unwrap(); - assert_eq!(client.is_handshaking(), index + 1 < server_records.len()); - } - let mut finished = Vec::new(); - client.write_tls(&mut finished).unwrap(); - feed_reality_server_connection(&mut server, &finished).unwrap(); - server.process_new_packets().unwrap(); - assert!(!server.is_handshaking()); - - client.writer().write_all(b"request").unwrap(); - let mut wire = Vec::new(); - client.write_tls(&mut wire).unwrap(); - feed_reality_server_connection(&mut server, &wire).unwrap(); - server.process_new_packets().unwrap(); - let mut request = [0; 7]; - server.reader().read_exact(&mut request).unwrap(); - assert_eq!(&request, b"request"); - - server.writer().write_all(b"response").unwrap(); - wire.clear(); - server.write_tls(&mut wire).unwrap(); - feed_reality_client_connection(&mut client, &wire).unwrap(); - client.process_new_packets().unwrap(); - let mut response = [0; 8]; - client.reader().read_exact(&mut response).unwrap(); - assert_eq!(&response, b"response"); - } - - #[test] - fn rejected_client_finished_never_completes_handshake() { - use crate::reality::RealityClientConnection; - use crate::reality::reality_pq_tests::{configs, default_target_records}; - - for corrupt_record in [false, true] { - let cipher = CipherSuite::AES_128_GCM_SHA256; - let (cc, sc) = configs(cipher); - let mut client = RealityClientConnection::new(cc).unwrap(); - let mut server = RealityServerConnection::new(sc).unwrap(); - let mut hello = Vec::new(); - client.write_tls(&mut hello).unwrap(); - server.validate_client_hello(&hello).unwrap(); - server - .build_server_response(&default_target_records(&hello[44..76])) - .unwrap(); - let mut response = Vec::new(); - server.write_tls(&mut response).unwrap(); - client.read_tls(&mut response.as_slice()).unwrap(); - client.process_new_packets().unwrap(); - let mut finished = Vec::new(); - client.write_tls(&mut finished).unwrap(); - if corrupt_record { - *finished.last_mut().unwrap() ^= 1; + let config = rustls::ServerConfig::builder_with_provider(Arc::new(crypto)) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(io_error)? + .with_no_client_auth() + .with_cert_resolver(Arc::new(rustls::sign::SingleCertAndKey::from(key))); + let expected_hello = prepared.server_hello().to_vec(); + let server = + rustls::ServerConnection::new_reality(Arc::new(config), prepared).map_err(io_error)?; + // Stage the complete flight without socket access. On failure even queued alerts are discarded. + let mut staged = RealityTransport::new(server.into()); + staged.feed(&authenticated.record).map_err(|error| { + if error.kind() == io::ErrorKind::Unsupported { + io::Error::new( + io::ErrorKind::Unsupported, + "Unsupported REALITY target or insufficient capacity", + ) } else { - let HandshakeState::ServerHelloSent { - client_handshake_traffic_secret, - .. - } = &server.handshake_state - else { - panic!("expected pending client Finished"); - }; - let (key, iv) = - derive_traffic_keys(client_handshake_traffic_secret, cipher).unwrap(); - let start = if finished[0] == CONTENT_TYPE_CHANGE_CIPHER_SPEC { - 6 - } else { - 0 - }; - let record = &finished[start..]; - let len = u16::from_be_bytes([record[3], record[4]]); - let mut plaintext = - decrypt_handshake_message(cipher, &key, &iv, 0, &record[5..], len).unwrap(); - *plaintext.last_mut().unwrap() ^= 1; - finished.truncate(start); - let aead = AeadKey::new(cipher, &key).unwrap(); - let mut seq = 0; - RecordEncryptor::new(&aead, &iv, &mut seq) - .encrypt_handshake(&plaintext, &mut finished) - .unwrap(); + error } - assert!(server.is_handshaking()); - assert_eq!(server.negotiated_group(), None); - server.read_tls(&mut finished.as_slice()).unwrap(); - let error = server.process_new_packets().unwrap_err(); - assert_eq!(error.kind(), io::ErrorKind::InvalidData); - if !corrupt_record { - assert_eq!(error.to_string(), "Client Finished verify_data mismatch"); + })?; + let mut wire = Vec::new(); + while staged.wants_write() { + if staged.write_tls(&mut wire)? == 0 { + return Err(io::ErrorKind::WriteZero.into()); } - assert!(server.is_handshaking()); - assert_eq!(server.negotiated_group(), None); - assert!(server.app_read_key.is_none()); - assert!(server.app_write_key.is_none()); - assert!(server.plaintext_read_buf.is_empty()); - assert!(server.process_new_packets().is_err()); } + super::reality_target_template::verify_staged_flight(&wire, records, &expected_hello)?; + staged.prefix = wire.into(); + self.transport = staged; + Ok(()) } - #[test] - fn fragmented_change_cipher_spec_rejects_invalid_length_before_buffering_payload() { - for length in [0u16, 2, 65535] { - let mut connection = RealityServerConnection::new(RealityServerConfig { - mldsa65_key: None, - private_key: [0; 32], - short_ids: vec![[0; 8]], - dest: NetLocation::new(Address::UNSPECIFIED, 443), - max_time_diff: None, - min_client_version: None, - max_client_version: None, - cipher_suites: vec![], - }) - .unwrap(); - let header = [ - CONTENT_TYPE_CHANGE_CIPHER_SPEC, - 3, - 3, - (length >> 8) as u8, - length as u8, - ]; - for byte in &header[..4] { - connection.read_tls(&mut &[*byte][..]).unwrap(); - assert!(!connection.process_client_finished().unwrap()); - } - connection.read_tls(&mut &header[4..]).unwrap(); - assert_eq!( - connection.process_client_finished().unwrap_err().kind(), - io::ErrorKind::InvalidData - ); - } - } - - #[test] - fn test_reality_server_connection_creation() { - let config = RealityServerConfig { - mldsa65_key: None, - private_key: [0u8; 32], - short_ids: vec![[0u8; 8]], - dest: NetLocation::new(Address::UNSPECIFIED, 443), - max_time_diff: Some(60000), - min_client_version: None, - max_client_version: None, - cipher_suites: Vec::new(), - }; - - let conn = RealityServerConnection::new(config).unwrap(); - assert!(conn.is_handshaking()); - assert!(!conn.wants_write()); - assert_eq!(conn.ciphertext_write_buf.capacity(), 0); - assert_eq!(conn.plaintext_write_buf.capacity(), 0); - } - - #[test] - fn test_io_state() { - let config = RealityServerConfig { - mldsa65_key: None, - private_key: [0u8; 32], - short_ids: vec![[0u8; 8]], - dest: NetLocation::new(Address::UNSPECIFIED, 443), - max_time_diff: None, - min_client_version: None, - max_client_version: None, - cipher_suites: Vec::new(), - }; - - let mut conn = RealityServerConnection::new(config).unwrap(); - let state = conn.process_new_packets().unwrap(); - - assert_eq!(state.plaintext_bytes_to_read(), 0); - assert!(!conn.wants_write()); - } + delegate_tls!(); +} + +fn denied(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::PermissionDenied, message) +} + +pub fn feed_reality_server_connection( + connection: &mut RealityServerConnection, + data: &[u8], +) -> io::Result<()> { + connection.transport.feed(data) } diff --git a/src/reality/reality_target_template.rs b/src/reality/reality_target_template.rs new file mode 100644 index 00000000..857a0c4b --- /dev/null +++ b/src/reality/reality_target_template.rs @@ -0,0 +1,62 @@ +use std::io; + +use bytes::Bytes; +use rustls::reality::FlightPlan; + +pub(super) fn verify_staged_flight(wire: &[u8], target: &[Bytes], hello: &[u8]) -> io::Result<()> { + let mut deframer = crate::crypto::tls_deframer::TlsDeframer::new(); + deframer.feed(wire); + let actual = deframer.next_records().map_err(io::Error::other)?; + if actual.len() != target.len() + || deframer.pending_bytes() != 0 + || actual + .iter() + .zip(target) + .any(|(a, b)| a.len() != b.len() || a[..5] != b[..5]) + || actual.first().is_none_or(|record| &record[5..] != hello) + || actual + .get(1) + .is_none_or(|record| record.as_ref() != [20, 3, 3, 0, 1, 1]) + { + return Err(io::Error::other( + "REALITY staged flight differs from admitted target", + )); + } + Ok(()) +} + +fn unsupported() -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + "Unsupported REALITY target record layout or insufficient capacity", + ) +} + +pub(super) fn flight_plan(records: &[Bytes]) -> io::Result { + if !matches!(records.len(), 3 | 6 | 7) { + return Err(unsupported()); + } + for (index, record) in records.iter().enumerate() { + let header = record.get(..5).ok_or_else(unsupported)?; + let expected_type = match index { + 0 => 22, + 1 => 20, + _ => 23, + }; + if header[0] != expected_type + || header[1..3] != [3, 3] + || record.len() != 5 + usize::from(u16::from_be_bytes([header[3], header[4]])) + { + return Err(unsupported()); + } + } + if records[1].as_ref() != [20, 3, 3, 0, 1, 1] { + return Err(unsupported()); + } + if (records.len() == 3) != (records[2].len() > 512) { + return Err(unsupported()); + } + let handshake_end = if records.len() == 3 { 3 } else { 6 }; + let lengths: Vec<_> = records[2..handshake_end].iter().map(Bytes::len).collect(); + FlightPlan::new(&lengths, records.get(6).map(Bytes::len)).map_err(|_| unsupported()) +} diff --git a/src/reality/reality_tls13_keys.rs b/src/reality/reality_tls13_keys.rs deleted file mode 100644 index fe580572..00000000 --- a/src/reality/reality_tls13_keys.rs +++ /dev/null @@ -1,470 +0,0 @@ -// TLS 1.3 Key Schedule Implementation -// -// Implements RFC 8446 key derivation for TLS 1.3 -// Supports both SHA256 and SHA384 based cipher suites - -use super::reality_cipher_suite::CipherSuite; -use aws_lc_rs::{digest, hmac}; -use std::io::{Error, ErrorKind, Result}; - -/// Intermediate TLS 1.3 keys (handshake secrets + master secret) -/// Used for two-phase key derivation where application secrets -/// must be derived after server Finished message -#[derive(Debug, Clone)] -pub struct Tls13HandshakeKeys { - /// Client handshake traffic secret - pub client_handshake_traffic_secret: Vec, - /// Server handshake traffic secret - pub server_handshake_traffic_secret: Vec, - /// Master secret (for deriving application secrets later) - pub master_secret: Vec, -} - -/// HKDF-Expand implementation with configurable HMAC algorithm -/// This follows RFC 5869 Section 2.3 -pub fn hkdf_expand( - hmac_algorithm: hmac::Algorithm, - prk: &[u8], - info: &[u8], - length: usize, -) -> Result> { - let hash_len = hmac_algorithm.digest_algorithm().output_len(); - let n = length.div_ceil(hash_len); // Number of iterations - - if n > 255 { - return Err(Error::new(ErrorKind::InvalidData, "HKDF output too long")); - } - - let mut output = Vec::new(); - let mut prev = Vec::new(); - - for i in 1..=n { - let key = hmac::Key::new(hmac_algorithm, prk); - let mut ctx = hmac::Context::with_key(&key); - - log::debug!( - "HKDF iteration {}: prev_len={}, info_len={}", - i, - prev.len(), - info.len() - ); - - ctx.update(&prev); - ctx.update(info); - ctx.update(&[i as u8]); - let tag = ctx.sign(); - - prev = tag.as_ref().to_vec(); - output.extend_from_slice(tag.as_ref()); - } - - output.truncate(length); - Ok(output) -} - -/// HKDF-Expand-Label as defined in RFC 8446 Section 7.1 -fn hkdf_expand_label_with_algorithm( - hmac_algorithm: hmac::Algorithm, - secret: &[u8], - label: &[u8], - context: &[u8], - length: usize, -) -> Result> { - log::debug!( - "DEBUG hkdf_expand_label: secret len={}, label={:?}, context len={}, length={}", - secret.len(), - std::str::from_utf8(label).unwrap_or(""), - context.len(), - length - ); - // HkdfLabel structure: - // struct { - // uint16 length = Length; - // opaque label<7..255> = "tls13 " + Label; - // opaque context<0..255> = Context; - // } HkdfLabel; - - let mut hkdf_label = Vec::new(); - - // Length (2 bytes, big-endian) - hkdf_label.extend_from_slice(&(length as u16).to_be_bytes()); - - // Label length and content - let full_label = format!("tls13 {}", std::str::from_utf8(label).unwrap()); - hkdf_label.push(full_label.len() as u8); - hkdf_label.extend_from_slice(full_label.as_bytes()); - - // Context length and content - hkdf_label.push(context.len() as u8); - hkdf_label.extend_from_slice(context); - - log::debug!("HKDF_LABEL_BYTES: {:02x?}", hkdf_label); - - hkdf_expand(hmac_algorithm, secret, &hkdf_label, length) -} - -/// Derive-Secret as defined in RFC 8446 Section 7.1 (with configurable hash) -fn derive_secret_with_algorithm( - hmac_algorithm: hmac::Algorithm, - secret: &[u8], - label: &[u8], - messages_hash: &[u8], -) -> Result> { - let hash_len = hmac_algorithm.digest_algorithm().output_len(); - hkdf_expand_label_with_algorithm(hmac_algorithm, secret, label, messages_hash, hash_len) -} - -/// HKDF-Extract operation with configurable HMAC algorithm -fn hkdf_extract_with_algorithm( - hmac_algorithm: hmac::Algorithm, - salt: &[u8], - ikm: &[u8], -) -> Vec { - let key = hmac::Key::new(hmac_algorithm, salt); - let tag = hmac::sign(&key, ikm); - tag.as_ref().to_vec() -} - -/// Derive traffic keys and IV from traffic secret using CipherSuite -/// -/// # Arguments -/// * `traffic_secret` - Traffic secret (hash_len bytes) -/// * `cipher_suite` - CipherSuite with key/IV lengths and HMAC algorithm -/// -/// # Returns -/// (key, iv) tuple for AEAD -pub fn derive_traffic_keys( - traffic_secret: &[u8], - cipher_suite: CipherSuite, -) -> Result<(Vec, Vec)> { - let key_length = cipher_suite.key_len(); - let iv_length = cipher_suite.nonce_len(); - let hash_len = cipher_suite.hash_len(); - let hmac_algorithm = cipher_suite.hmac_algorithm(); - - log::debug!( - "TRAFFIC_KEY_DERIVE: cipher_suite={:?}, key_len={}, iv_len={}, hash_len={}", - cipher_suite, - key_length, - iv_length, - hash_len - ); - - // key = HKDF-Expand-Label(Secret, "key", "", key_length) - let key = - hkdf_expand_label_with_algorithm(hmac_algorithm, traffic_secret, b"key", b"", key_length)?; - - // iv = HKDF-Expand-Label(Secret, "iv", "", iv_length) - let iv = - hkdf_expand_label_with_algorithm(hmac_algorithm, traffic_secret, b"iv", b"", iv_length)?; - - Ok((key, iv)) -} - -/// Derive TLS 1.3 handshake keys and master secret using CipherSuite (Phase 1) -/// -/// This function derives handshake traffic secrets and the master secret, -/// but NOT the application traffic secrets. Application secrets must be -/// derived separately after the server Finished message is sent (Phase 2). -/// -/// # Arguments -/// * `cipher_suite` - CipherSuite with HMAC/digest algorithms -/// * `shared_secret` - ECDH shared secret (32 bytes for X25519) -/// * `client_hello_hash` - Hash of ClientHello (hash_len bytes) -/// * `server_hello_hash` - Hash of ClientHello...ServerHello (hash_len bytes) -/// -/// # Returns -/// Handshake traffic secrets and master secret -pub fn derive_handshake_keys( - group: super::reality_key_exchange::RealityGroup, - cipher_suite: CipherSuite, - shared_secret: &[u8], - _client_hello_hash: &[u8], // Not used in TLS 1.3 key derivation - kept for API consistency - server_hello_hash: &[u8], -) -> Result { - let hash_len = cipher_suite.hash_len(); - let hmac_algorithm = cipher_suite.hmac_algorithm(); - let digest_algorithm = cipher_suite.digest_algorithm(); - - // Validate input lengths - if shared_secret.len() != group.secret_len() { - return Err(Error::new( - ErrorKind::InvalidInput, - format!( - "Invalid shared_secret length: {} (expected {})", - shared_secret.len(), - group.secret_len() - ), - )); - } - if server_hello_hash.len() != hash_len { - return Err(Error::new( - ErrorKind::InvalidInput, - format!( - "Hash length mismatch: {} (expected {})", - server_hello_hash.len(), - hash_len - ), - )); - } - - log::debug!( - "TLS13 DEBUG: Deriving handshake keys (Phase 1) with {:?}...", - cipher_suite - ); - - // 1. Early Secret = HKDF-Extract(salt=0, IKM=0) - let zero_salt = vec![0u8; hash_len]; - let early_secret = hkdf_extract_with_algorithm(hmac_algorithm, &zero_salt, &zero_salt); - - // 2. Derive-Secret(., "derived", "") - let mut empty_ctx = digest::Context::new(digest_algorithm); - empty_ctx.update(b""); - let empty_hash = empty_ctx.finish(); - let derived_secret = derive_secret_with_algorithm( - hmac_algorithm, - &early_secret, - b"derived", - empty_hash.as_ref(), - )?; - - // 3. Handshake Secret = HKDF-Extract(salt=derived_secret, IKM=shared_secret) - let handshake_secret = - hkdf_extract_with_algorithm(hmac_algorithm, &derived_secret, shared_secret); - - // 4. Client Handshake Traffic Secret - let client_handshake_traffic_secret = derive_secret_with_algorithm( - hmac_algorithm, - &handshake_secret, - b"c hs traffic", - server_hello_hash, - )?; - - // 5. Server Handshake Traffic Secret - let server_handshake_traffic_secret = derive_secret_with_algorithm( - hmac_algorithm, - &handshake_secret, - b"s hs traffic", - server_hello_hash, - )?; - - // 6. Derive-Secret(., "derived", "") - let mut empty_ctx_2 = digest::Context::new(digest_algorithm); - empty_ctx_2.update(b""); - let empty_hash_2 = empty_ctx_2.finish(); - let derived_secret_2 = derive_secret_with_algorithm( - hmac_algorithm, - &handshake_secret, - b"derived", - empty_hash_2.as_ref(), - )?; - - // 7. Master Secret = HKDF-Extract(salt=derived_secret, IKM=0) - let master_secret = hkdf_extract_with_algorithm(hmac_algorithm, &derived_secret_2, &zero_salt); - - Ok(Tls13HandshakeKeys { - client_handshake_traffic_secret, - server_handshake_traffic_secret, - master_secret, - }) -} - -/// Derive TLS 1.3 application traffic secrets using CipherSuite (Phase 2) -/// -/// This function must be called AFTER the server Finished message is sent, -/// with a transcript hash that includes the Finished message. -/// -/// # Arguments -/// * `cipher_suite` - CipherSuite with HMAC algorithm -/// * `master_secret` - Master secret from Phase 1 (hash_len bytes) -/// * `handshake_hash` - Hash including server Finished (hash_len bytes) -/// -/// # Returns -/// (client_application_traffic_secret, server_application_traffic_secret) -pub fn derive_application_secrets( - cipher_suite: CipherSuite, - master_secret: &[u8], - handshake_hash: &[u8], -) -> Result<(Vec, Vec)> { - let hash_len = cipher_suite.hash_len(); - let hmac_algorithm = cipher_suite.hmac_algorithm(); - - if master_secret.len() != hash_len || handshake_hash.len() != hash_len { - return Err(Error::new( - ErrorKind::InvalidInput, - format!( - "Master secret and handshake hash must be {} bytes", - hash_len - ), - )); - } - - log::debug!( - "TLS13 DEBUG: Deriving application secrets (Phase 2) with {:?}...", - cipher_suite - ); - log::debug!( - " handshake_hash (with Finished): {:?}", - &handshake_hash[..8] - ); - - // Client Application Traffic Secret - let client_application_traffic_secret = derive_secret_with_algorithm( - hmac_algorithm, - master_secret, - b"c ap traffic", - handshake_hash, - )?; - - // Server Application Traffic Secret - let server_application_traffic_secret = derive_secret_with_algorithm( - hmac_algorithm, - master_secret, - b"s ap traffic", - handshake_hash, - )?; - - Ok(( - client_application_traffic_secret, - server_application_traffic_secret, - )) -} - -/// Compute "Finished" verify data using CipherSuite -/// -/// finished_key = HKDF-Expand-Label(BaseKey, "finished", "", Hash.length) -/// verify_data = HMAC(finished_key, Transcript-Hash(Handshake Context)) -pub fn compute_finished_verify_data( - cipher_suite: CipherSuite, - base_key: &[u8], - handshake_hash: &[u8], -) -> Result> { - let hash_len = cipher_suite.hash_len(); - let hmac_algorithm = cipher_suite.hmac_algorithm(); - - // finished_key = HKDF-Expand-Label(BaseKey, "finished", "", hash_len) - let finished_key = - hkdf_expand_label_with_algorithm(hmac_algorithm, base_key, b"finished", b"", hash_len)?; - - // verify_data = HMAC(finished_key, handshake_hash) - let key = hmac::Key::new(hmac_algorithm, &finished_key); - let tag = hmac::sign(&key, handshake_hash); - let verify_data = tag.as_ref().to_vec(); - - Ok(verify_data) -} - -#[cfg(test)] -mod tests { - use super::*; - - const CS_SHA256: CipherSuite = CipherSuite::AES_128_GCM_SHA256; - - // Test vectors from RFC 5869 Appendix A - #[test] - fn test_hkdf_expand_sha256_rfc_vector() { - // Test Case 1 from RFC 5869 (simplified - using extracted PRK directly) - let prk = [ - 0x07, 0x77, 0x09, 0x36, 0x2c, 0x2e, 0x32, 0xdf, 0x0d, 0xdc, 0x3f, 0x0d, 0xc4, 0x7b, - 0xba, 0x63, 0x90, 0xb6, 0xc7, 0x3b, 0xb5, 0x0f, 0x9c, 0x31, 0x22, 0xec, 0x84, 0x4a, - 0xd7, 0xc2, 0xb3, 0xe5, - ]; - let info = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9]; - - let result = hkdf_expand(hmac::HMAC_SHA256, &prk, &info, 42).unwrap(); - assert_eq!(result.len(), 42); - - // Check first few bytes match expected pattern - assert_eq!(result[0], 0x3c); - assert_eq!(result[1], 0xb2); - assert_eq!(result[2], 0x5f); - } - - #[test] - fn test_hkdf_expand_sha256_empty_info() { - let prk = vec![0x42u8; 32]; - let result = hkdf_expand(hmac::HMAC_SHA256, &prk, &[], 16); - assert!(result.is_ok()); - assert_eq!(result.unwrap().len(), 16); - } - - #[test] - fn test_hkdf_expand_sha256_max_length() { - let prk = vec![0x42u8; 32]; - let info = b"test info"; - - // Maximum output length is 255 * hash_len (32 for SHA256) = 8160 bytes - let result = hkdf_expand(hmac::HMAC_SHA256, &prk, info, 8160); - assert!(result.is_ok()); - assert_eq!(result.unwrap().len(), 8160); - - // Should fail for length > 8160 - let result = hkdf_expand(hmac::HMAC_SHA256, &prk, info, 8161); - assert!(result.is_err()); - } - - #[test] - fn test_hkdf_expand_label() { - let secret = vec![0x42u8; 32]; - let result = hkdf_expand_label_with_algorithm(hmac::HMAC_SHA256, &secret, b"test", b"", 16); - assert!(result.is_ok()); - assert_eq!(result.unwrap().len(), 16); - } - - #[test] - fn test_hkdf_expand_label_with_context() { - let secret = vec![0x42u8; 32]; - let context = vec![0x11u8; 32]; - let result = - hkdf_expand_label_with_algorithm(hmac::HMAC_SHA256, &secret, b"finished", &context, 32); - assert!(result.is_ok()); - let output = result.unwrap(); - assert_eq!(output.len(), 32); - - // Result should be deterministic - let result2 = - hkdf_expand_label_with_algorithm(hmac::HMAC_SHA256, &secret, b"finished", &context, 32) - .unwrap(); - assert_eq!(output, result2); - } - - #[test] - fn test_hkdf_extract() { - let salt = vec![0x11u8; 32]; - let ikm = vec![0x22u8; 32]; - - let result1 = hkdf_extract_with_algorithm(hmac::HMAC_SHA256, &salt, &ikm); - assert_eq!(result1.len(), 32); // SHA256 output length - - // Should be deterministic - let result2 = hkdf_extract_with_algorithm(hmac::HMAC_SHA256, &salt, &ikm); - assert_eq!(result1, result2); - - // Different input should give different output - let ikm2 = vec![0x33u8; 32]; - let result3 = hkdf_extract_with_algorithm(hmac::HMAC_SHA256, &salt, &ikm2); - assert_ne!(result1, result3); - } - - #[test] - fn test_derive_traffic_keys() { - let traffic_secret = vec![0x99u8; 32]; - - // Test TLS_AES_128_GCM_SHA256 - let result = derive_traffic_keys(&traffic_secret, CS_SHA256); - assert!(result.is_ok()); - let (key, iv) = result.unwrap(); - assert_eq!(key.len(), 16); - assert_eq!(iv.len(), 12); - } - - #[test] - fn test_compute_finished_verify_data() { - let base_key = vec![0xAAu8; 32]; - let handshake_hash = vec![0xBBu8; 32]; - - let result = compute_finished_verify_data(CS_SHA256, &base_key, &handshake_hash); - assert!(result.is_ok()); - assert_eq!(result.unwrap().len(), 32); - } -} diff --git a/src/reality/reality_util.rs b/src/reality/reality_util.rs index d0227f3c..394a1a6d 100644 --- a/src/reality/reality_util.rs +++ b/src/reality/reality_util.rs @@ -2,9 +2,6 @@ use aws_lc_rs::agreement; use base64::engine::{Engine as _, general_purpose::URL_SAFE_NO_PAD}; use rand::Rng; -use super::reality_cipher_suite::CipherSuite; -use crate::buf_reader::BufReader; - pub(crate) fn parse_server_name( name: &str, ) -> std::io::Result> { @@ -170,103 +167,6 @@ pub fn extract_session_id_slice(client_hello: &[u8]) -> Result<&[u8], std::io::E Ok(&client_hello[SESSION_ID_LEN_OFFSET + 1..SESSION_ID_LEN_OFFSET + 1 + session_id_len]) } -/// Extract the cipher suite selected by the server from ServerHello message -/// -/// This parses the TLS 1.3 ServerHello to find the cipher suite. -/// ServerHello contains a single cipher suite (the server's choice). -pub fn extract_server_cipher_suite(server_hello: &[u8]) -> Result { - const TLS_HEADER_LEN: usize = 5; - - if server_hello.len() < TLS_HEADER_LEN { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "ServerHello too short", - )); - } - - let mut reader = BufReader::new(&server_hello[TLS_HEADER_LEN..]); - - // Parse handshake header - let _handshake_type = reader.read_u8()?; - let _handshake_len = reader.read_u24_be()?; - let _protocol_version = reader.read_u16_be()?; - - // Skip random (32 bytes) - reader.skip(32)?; - - // Read session ID (ServerHello can echo it back) - let session_id_len = reader.read_u8()? as usize; - reader.skip(session_id_len)?; - - // Read cipher suite (single 2-byte value in ServerHello) - let cipher_suite = reader.read_u16_be()?; - - Ok(cipher_suite) -} - -/// Extracts cipher suites offered by client from ClientHello -/// -/// Returns a Vec of cipher suite IDs in the order they appear in the ClientHello. -pub fn extract_client_cipher_suites(client_hello: &[u8]) -> Result, std::io::Error> { - const TLS_HEADER_LEN: usize = 5; - - if client_hello.len() < TLS_HEADER_LEN { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "ClientHello too short", - )); - } - - let mut reader = BufReader::new(&client_hello[TLS_HEADER_LEN..]); - - // Parse handshake header - let _handshake_type = reader.read_u8()?; - let _handshake_len = reader.read_u24_be()?; - let _protocol_version = reader.read_u16_be()?; - - // Skip random (32 bytes) - reader.skip(32)?; - - // Skip session ID - let session_id_len = reader.read_u8()? as usize; - reader.skip(session_id_len)?; - - // Read cipher suites - let cipher_suites_len = reader.read_u16_be()? as usize; - if !cipher_suites_len.is_multiple_of(2) { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidData, - "Invalid cipher suites length (not even)", - )); - } - - let cipher_suites_data = reader.read_slice(cipher_suites_len)?; - let mut cipher_suites = Vec::with_capacity(cipher_suites_len / 2); - - for chunk in cipher_suites_data.chunks(2) { - let suite = u16::from_be_bytes([chunk[0], chunk[1]]); - cipher_suites.push(suite); - } - - Ok(cipher_suites) -} - -/// Negotiate cipher suite between server preferences and client offers (CipherSuite version) -/// -/// Returns the first CipherSuite from server_preferences that the client supports, -/// or None if no common cipher suite is found. -pub fn negotiate_cipher_suite( - server_preferences: &[CipherSuite], - client_cipher_suite_ids: &[u16], -) -> Option { - for server_suite in server_preferences { - if client_cipher_suite_ids.contains(&server_suite.id()) { - return Some(*server_suite); - } - } - None -} - pub fn generate_keypair() -> std::io::Result<(String, String)> { // Generate 32 random bytes for private key let mut private_key_bytes = [0u8; 32]; diff --git a/src/vless/vision_stream.rs b/src/vless/vision_stream.rs index d22354a1..a74265d9 100644 --- a/src/vless/vision_stream.rs +++ b/src/vless/vision_stream.rs @@ -1912,34 +1912,16 @@ mod tests { } } - fn completed_reality_connection() -> CryptoConnection { - let config = RealityServerConfig { - mldsa65_key: None, - private_key: [0; 32], - short_ids: vec![[0; 8]], - dest: NetLocation::new(Address::UNSPECIFIED, 443), - max_time_diff: None, - min_client_version: None, - max_client_version: None, - cipher_suites: Vec::new(), - }; - CryptoConnection::new_reality_server( - RealityServerConnection::new(config) - .unwrap() - .complete_for_test() - .unwrap(), - ) - } - fn assert_initial_mode_transition(command: UnpadCommand, session_plaintext: &[u8]) { let uuid = [7; 16]; let mut initial = uuid.to_vec(); initial.extend_from_slice(&[command as u8, 0, 3, 0, 2]); initial.extend_from_slice(b"one\0\0-two"); - let mut session = completed_reality_connection(); + let (peer, session) = crate::reality::established_pair(); + let mut peer = CryptoConnection::new_reality_client(peer); + let mut session = CryptoConnection::new_reality_server(session); if !session_plaintext.is_empty() { - let mut peer = completed_reality_connection(); peer.writer().write_all(session_plaintext).unwrap(); let mut ciphertext = Vec::new(); peer.write_tls(&mut ciphertext).unwrap(); diff --git a/src/websocket/websocket_stream.rs b/src/websocket/websocket_stream.rs index 309d2f2f..0ef5f041 100644 --- a/src/websocket/websocket_stream.rs +++ b/src/websocket/websocket_stream.rs @@ -834,10 +834,8 @@ fn pack_frame(opcode: u8, use_mask: bool, input: &[u8], output: &mut [u8]) -> us #[cfg(test)] mod tests { use super::*; - use crate::address::{Address, NetLocation}; use crate::crypto::tls_deframer::TlsDeframer; use crate::crypto::{CryptoConnection, CryptoTlsStream}; - use crate::reality::{RealityServerConfig, RealityServerConnection}; use futures::task::noop_waker_ref; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -905,19 +903,7 @@ mod tests { WebsocketPingType::PingFrame, if pong { &[0x89, 0] } else { &[] }, ); - let session = RealityServerConnection::new(RealityServerConfig { - mldsa65_key: None, - private_key: [0; 32], - short_ids: vec![[0; 8]], - dest: NetLocation::new(Address::UNSPECIFIED, 443), - max_time_diff: None, - min_client_version: None, - max_client_version: None, - cipher_suites: Vec::new(), - }) - .unwrap() - .complete_for_test() - .unwrap(); + let session = crate::reality::established_pair().1; let mut tls = CryptoTlsStream::new( websocket, CryptoConnection::new_reality_server(session),