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::{PacketLayout, initial_salt_for_version, is_quic_v2};
pub(super) fn decrypt_client_initial_packet(
packet: &[u8],
dcid: &[u8],
version: u32,
layout: PacketLayout,
) -> Option<Vec<u8>> {
let Some(client_secret) = derive_client_initial_secret(dcid, version) else {
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, layout);
if result.is_none() {
debug!("QUIC: Client Initial decryption failed");
}
result
}
fn try_decrypt_initial_with_secret(
packet: &[u8],
secret: &[u8],
version: u32,
layout: PacketLayout,
) -> Option<Vec<u8>> {
let PacketLayout {
pn_offset,
packet_length: packet_payload_length,
} = layout;
let ciphertext_end = pn_offset.checked_add(packet_payload_length)?;
let packet = packet.get(..ciphertext_end)?;
let header_rest = packet.get(1..pn_offset)?;
let sample_offset = pn_offset.checked_add(4)?;
let sample = packet.get(sample_offset..sample_offset.checked_add(16)?)?;
let Some(InitialKeys {
key,
iv,
hp: hp_key,
}) = derive_initial_keys(secret, version)
else {
debug!("QUIC: Failed to derive keys from secret");
return None;
};
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(header_rest);
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.checked_sub(pn_length)?;
if ciphertext_len < 16 {
debug!("QUIC: Ciphertext too short for auth tag");
return None;
}
let mut plaintext = packet[ciphertext_offset..ciphertext_end].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_client_initial_secret(dcid: &[u8], version: u32) -> Option<[u8; 32]> {
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];
derive_secret(&initial_secret, b"client in", &mut client_secret).then_some(client_secret)
}
pub(super) struct InitialKeys {
pub key: [u8; 16],
pub iv: [u8; 12],
pub hp: [u8; 16],
}
pub(super) fn derive_initial_keys(secret: &[u8], version: u32) -> Option<InitialKeys> {
let mut keys = InitialKeys {
key: [0u8; 16],
iv: [0u8; 12],
hp: [0u8; 16],
};
let ok = derive_protection_material(secret, &mut keys.key, version, ProtectionMaterial::Key)
&& derive_protection_material(secret, &mut keys.iv, version, ProtectionMaterial::Iv)
&& derive_protection_material(
secret,
&mut keys.hp,
version,
ProtectionMaterial::HeaderProtection,
);
ok.then_some(keys)
}
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()
}
enum ProtectionMaterial {
Key,
Iv,
HeaderProtection,
}
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 oversized_ciphertext_length_is_rejected_without_overflow() {
assert!(
try_decrypt_initial_with_secret(
&[0; 64],
&[0; 32],
1,
PacketLayout {
pn_offset: 8,
packet_length: usize::MAX
},
)
.is_none()
);
}
use super::super::packet::parse_long_header;
#[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 layout = parse_long_header(&packet)
.and_then(|header| header.layout)
.expect("header should parse up to the packet number");
assert_eq!(layout.packet_length, 0);
let secret = [0u8; 32];
let result = try_decrypt_initial_with_secret(&packet, &secret, 1, layout);
assert!(result.is_none());
}
}