use aes::Aes128;
use aes::cipher::{BlockCipherEncrypt, KeyInit};
use log::debug;
use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey};
use ring::{aead, hkdf};
use super::packet::{initial_salt_for_version, is_quic_v2, parse_variable_length_int};
pub(super) fn decrypt_client_initial_packet(
packet: &[u8],
dcid: &[u8],
version: u32,
) -> Option<Vec<u8>> {
let salt = hkdf::Salt::new(hkdf::HKDF_SHA256, initial_salt_for_version(version));
let initial_secret = salt.extract(dcid);
let mut client_secret = [0u8; 32];
if !derive_secret(&initial_secret, b"client in", &mut client_secret) {
debug!("QUIC: Failed to derive client initial secret");
return None;
}
debug!(
"QUIC: Attempting client Initial decryption with DCID len={}",
dcid.len()
);
let result = try_decrypt_initial_with_secret(packet, &client_secret, version);
if result.is_none() {
debug!("QUIC: Client Initial decryption failed");
}
result
}
fn try_decrypt_initial_with_secret(packet: &[u8], secret: &[u8], version: u32) -> Option<Vec<u8>> {
let mut key = [0u8; 16];
let mut iv = [0u8; 12];
let mut hp_key = [0u8; 16];
if !derive_protection_material(secret, &mut key, version, ProtectionMaterial::Key)
|| !derive_protection_material(secret, &mut iv, version, ProtectionMaterial::Iv)
|| !derive_protection_material(
secret,
&mut hp_key,
version,
ProtectionMaterial::HeaderProtection,
)
{
debug!("QUIC: Failed to derive keys from secret");
return None;
}
let mut offset = 5;
if offset >= packet.len() {
debug!("QUIC: Packet too short for DCID length field");
return None;
}
let dcid_len = packet[offset] as usize;
offset += 1 + dcid_len;
if offset >= packet.len() {
debug!("QUIC: Packet too short after DCID");
return None;
}
let scid_len = packet[offset] as usize;
offset += 1 + scid_len;
if offset >= packet.len() {
debug!("QUIC: Packet too short after SCID");
return None;
}
debug!(
"QUIC: Parsed connection IDs - DCID len={}, SCID len={}, offset now={}",
dcid_len, scid_len, offset
);
let (token_len, bytes_read) = parse_variable_length_int(&packet[offset..])?;
let token_len_usize = usize::try_from(token_len).ok()?;
offset = offset
.checked_add(bytes_read)?
.checked_add(token_len_usize)?;
if offset > packet.len() {
debug!("QUIC: token_len pushed offset past end of packet");
return None;
}
let (packet_payload_length, bytes_read) = parse_variable_length_int(&packet[offset..])?;
offset += bytes_read;
let pn_offset = offset;
let sample_offset = pn_offset + 4;
if sample_offset + 16 > packet.len() {
debug!("QUIC: Not enough data for header protection sample");
return None;
}
let sample = &packet[sample_offset..sample_offset + 16];
let mask = aes_ecb_encrypt(&hp_key, sample)?;
let mut first_byte = packet[0];
first_byte ^= mask[0] & 0x0f; let pn_length = ((first_byte & 0x03) + 1) as usize;
let mut packet_number = 0u64;
for i in 0..pn_length {
let unmasked = packet[pn_offset + i] ^ mask[1 + i];
packet_number = (packet_number << 8) | (unmasked as u64);
}
let aead_key = LessSafeKey::new(UnboundKey::new(&aead::AES_128_GCM, &key).ok()?);
let mut nonce_bytes = iv;
for i in 0..8 {
nonce_bytes[11 - i] ^= ((packet_number >> (i * 8)) & 0xff) as u8;
}
let nonce = Nonce::assume_unique_for_key(nonce_bytes);
let mut aad = Vec::new();
aad.push(first_byte); aad.extend_from_slice(&packet[1..pn_offset]); for i in 0..pn_length {
aad.push(packet[pn_offset + i] ^ mask[1 + i]); }
let ciphertext_offset = pn_offset + pn_length;
let ciphertext_len = (packet_payload_length as usize).checked_sub(pn_length)?;
if ciphertext_offset + ciphertext_len > packet.len() {
debug!("QUIC: Ciphertext extends beyond packet");
return None;
}
if ciphertext_len < 16 {
debug!("QUIC: Ciphertext too short for auth tag");
return None;
}
let mut plaintext = packet[ciphertext_offset..ciphertext_offset + ciphertext_len].to_vec();
match aead_key.open_in_place(nonce, Aad::from(&aad), &mut plaintext) {
Ok(decrypted) => {
let decrypted_len = decrypted.len();
plaintext.truncate(decrypted_len);
Some(plaintext)
}
Err(e) => {
debug!("QUIC: AEAD decryption failed: {:?}", e);
None
}
}
}
pub(super) fn derive_secret(prk: &hkdf::Prk, label: &[u8], out: &mut [u8]) -> bool {
let info = build_hkdf_label(label, &[], out.len());
prk.expand(&[&info], ArbitraryOutputLen(out.len()))
.and_then(|okm| okm.fill(out))
.is_ok()
}
pub(super) enum ProtectionMaterial {
Key,
Iv,
HeaderProtection,
}
pub(super) fn derive_protection_material(
secret: &[u8],
out: &mut [u8],
version: u32,
material: ProtectionMaterial,
) -> bool {
let label: &[u8] = match (material, is_quic_v2(version)) {
(ProtectionMaterial::Key, false) => b"quic key",
(ProtectionMaterial::Key, true) => b"quicv2 key",
(ProtectionMaterial::Iv, false) => b"quic iv",
(ProtectionMaterial::Iv, true) => b"quicv2 iv",
(ProtectionMaterial::HeaderProtection, false) => b"quic hp",
(ProtectionMaterial::HeaderProtection, true) => b"quicv2 hp",
};
let prk = hkdf::Prk::new_less_safe(hkdf::HKDF_SHA256, secret);
derive_secret(&prk, label, out)
}
fn build_hkdf_label(label: &[u8], context: &[u8], length: usize) -> Vec<u8> {
let mut info = Vec::new();
info.push((length >> 8) as u8);
info.push((length & 0xff) as u8);
let full_label = [b"tls13 ", label].concat();
info.push(full_label.len() as u8);
info.extend_from_slice(&full_label);
info.push(context.len() as u8);
info.extend_from_slice(context);
info
}
pub(super) fn aes_ecb_encrypt(key: &[u8], block: &[u8]) -> Option<[u8; 16]> {
let cipher = Aes128::new(key.try_into().ok()?);
let mut output: aes::cipher::Array<u8, aes::cipher::consts::U16> = block.try_into().ok()?;
cipher.encrypt_block(&mut output);
Some(output.into())
}
struct ArbitraryOutputLen(usize);
impl hkdf::KeyType for ArbitraryOutputLen {
fn len(&self) -> usize {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_initial_packet_oversized_token_len_does_not_panic() {
let mut packet = Vec::new();
packet.push(0xC0); packet.extend_from_slice(&1u32.to_be_bytes()); packet.push(0); packet.push(0); let token_varint: u16 = 1000 | 0x4000;
packet.extend_from_slice(&token_varint.to_be_bytes());
let secret = [0u8; 32];
let result = try_decrypt_initial_with_secret(&packet, &secret, 1);
assert!(result.is_none());
}
#[test]
fn test_initial_packet_short_length_does_not_underflow() {
let mut packet = Vec::new();
packet.push(0xC0); packet.extend_from_slice(&1u32.to_be_bytes()); packet.push(0); packet.push(0); packet.push(0); packet.push(0); packet.extend(std::iter::repeat_n(0u8, 24));
let secret = [0u8; 32];
let result = try_decrypt_initial_with_secret(&packet, &secret, 1);
assert!(result.is_none());
}
}