Delegate REALITY TLS state and record protection to rustls

Keep authentication and certificate policy in Shoes while rustls owns transcripts, Finished verification, key updates, records, and traffic keys. Use connection-owned authentication state and verify Ed25519 cryptographically even when the advertised schemes omit it.

Import validated target ServerHello bytes and cipher selection, then stage and independently validate the complete padded flight before exposing any output. Unsupported templates fail before commitment; the outbound client remains fail-closed with a native rustls ClientHello.

Remove the custom TLS key schedule, AEAD, and record engine. Replace fake transport test states with real handshakes and cover authentication isolation, transcript/signature tampering, cipher/group/ML-DSA combinations, and zero-output failures.
This commit is contained in:
cfal
2026-10-22 09:37:23 +00:00
parent e3a9a8e61a
commit 42b78c7662
22 changed files with 1384 additions and 5431 deletions
+2
View File
@@ -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.
+4 -18
View File
@@ -521,8 +521,7 @@ impl<IO: AsyncStream> AsyncStream for CryptoTlsStream<IO> {
#[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
+14 -264
View File
@@ -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<usize> {
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<u8>) -> io::Result<u8> {
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<u8>) -> io::Result<u8> {
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;
+7 -4
View File
@@ -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)]
-438
View File
@@ -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<Self> {
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<u8>,
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<Vec<u8>> {
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<Vec<u8>> {
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<Nonce> {
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<Vec<u8>> {
// 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<Vec<u8>> {
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<Vec<u8>> {
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);
}
}
+3 -3
View File
@@ -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)?;
+4 -86
View File
@@ -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<Self> {
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<Self> {
@@ -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 {
File diff suppressed because it is too large Load Diff
+11 -1
View File
@@ -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<Vec<u8>> {
// 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],
+177
View File
@@ -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<rustls::Connection>,
pub(super) prefix: bytes::Bytes,
failed: Option<io::ErrorKind>,
}
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<usize> {
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<RealityIoState> {
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<usize> {
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<RealityGroup> {
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<usize> {
self.transport.read_tls(reader)
}
pub fn write_tls(&mut self, writer: &mut dyn std::io::Write) -> std::io::Result<usize> {
self.transport.write_tls(writer)
}
pub fn process_new_packets(
&mut self,
) -> std::io::Result<super::reality_io_state::RealityIoState> {
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<super::reality_key_exchange::RealityGroup> {
self.transport.negotiated_group()
}
pub fn send_close_notify(&mut self) {
self.transport.send_close_notify();
}
};
}
pub(super) use delegate_tls;
+13 -11
View File
@@ -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<ClientKeyShares> {
Ok(shares)
}
pub fn extract_server_key_share(record: &[u8]) -> io::Result<KeyShareRef<'_>> {
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<u8>)> {
@@ -216,6 +216,7 @@ pub fn generate_mlkem() -> io::Result<(kem::DecapsulationKey, Vec<u8>)> {
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,
+45 -12
View File
@@ -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());
+42 -153
View File
@@ -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<rustls::Reader<'a>>,
failed: Option<io::ErrorKind>,
}
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<rustls::Reader<'a>>, failed: Option<io::ErrorKind>) -> Self {
Self { inner, failed }
}
}
impl Read for RealityReader<'_> {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
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<usize> {
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<u8>,
pending_tls_bytes: usize,
inner: Option<rustls::Writer<'a>>,
failed: Option<io::ErrorKind>,
}
impl<'a> RealityWriter<'a> {
pub fn new(buffer: &'a mut Vec<u8>, pending_tls_bytes: usize) -> Self {
RealityWriter {
buffer,
pending_tls_bytes,
}
pub(super) fn new(inner: Option<rustls::Writer<'a>>, failed: Option<io::ErrorKind>) -> Self {
Self { inner, failed }
}
}
impl<'a> Write for RealityWriter<'a> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
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<usize> {
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)
}
}
File diff suppressed because it is too large Load Diff
+352
View File
@@ -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<RealityGroup> {
match group {
NamedGroup::X25519 => Some(RealityGroup::X25519),
NamedGroup::X25519MLKEM768 => Some(RealityGroup::X25519MlKem768),
_ => None,
}
}
#[derive(Default)]
struct VerificationContext {
auth: Option<Zeroizing<[u8; 32]>>,
hellos: Vec<u8>,
public_key: Option<[u8; 32]>,
}
pub(super) struct ClientAuthentication {
server_key: [u8; 32],
short_id: [u8; 8],
shared: Option<Zeroizing<[u8; 32]>>,
context: Arc<Mutex<VerificationContext>>,
}
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<Mutex<VerificationContext>>,
mldsa: Option<super::reality_mldsa::VerifyKey>,
schemes: Vec<SignatureScheme>,
}
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<SignatureScheme>,
) -> (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<kem::DecapsulationKey>,
public: Vec<u8>,
group: NamedGroup,
}
impl ActiveKeyExchange for ClientExchange {
fn complete(self: Box<Self>, peer: &[u8]) -> Result<SharedSecret, Error> {
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<Self>, peer: &[u8]) -> Result<SharedSecret, Error> {
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<Box<dyn ActiveKeyExchange>, 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(&timestamp.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<ServerCertVerified, Error> {
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<HandshakeSignatureValid, Error> {
Err(verification_error("TLS 1.2 is not REALITY"))
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
signature: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, Error> {
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<SignatureScheme> {
self.schemes.clone()
}
}
pub(super) struct RealitySigningKey(Arc<signature::Ed25519KeyPair>);
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<Box<dyn rustls::sign::Signer>> {
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<Vec<u8>, Error> {
Ok(self.0.sign(message).as_ref().to_vec())
}
fn scheme(&self) -> SignatureScheme {
SignatureScheme::ED25519
}
}
+467
View File
@@ -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<std::collections::HashMap<String, Vec<u8>>>);
#[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<Bytes> {
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<Secrets>,
omit_ed25519: bool,
) -> (RealityClientConnection, RealityServerConnection, Vec<Bytes>) {
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<u8>),
) -> Vec<u8> {
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());
}
File diff suppressed because it is too large Load Diff
+62
View File
@@ -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<FlightPlan> {
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())
}
-470
View File
@@ -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<u8>,
/// Server handshake traffic secret
pub server_handshake_traffic_secret: Vec<u8>,
/// Master secret (for deriving application secrets later)
pub master_secret: Vec<u8>,
}
/// 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<Vec<u8>> {
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<Vec<u8>> {
log::debug!(
"DEBUG hkdf_expand_label: secret len={}, label={:?}, context len={}, length={}",
secret.len(),
std::str::from_utf8(label).unwrap_or("<binary>"),
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<Vec<u8>> {
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<u8> {
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<u8>, Vec<u8>)> {
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<Tls13HandshakeKeys> {
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<u8>, Vec<u8>)> {
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<Vec<u8>> {
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);
}
}
-100
View File
@@ -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<rustls::pki_types::ServerName<'static>> {
@@ -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<u16, std::io::Error> {
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<Vec<u16>, 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<CipherSuite> {
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];
+3 -21
View File
@@ -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();
+1 -15
View File
@@ -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),