1use ring::{aead, hkdf};
2
3use crate::tls::rustls::cipher::{Iv, IvLen};
5use crate::tls::rustls::error::Error;
6use crate::tls::rustls::msgs::enums::AlertDescription;
7use crate::tls::rustls::suites::BulkAlgorithm;
8use crate::tls::rustls::tls13::key_schedule::hkdf_expand;
9use crate::tls::rustls::tls13::{Tls13CipherSuite, TLS13_AES_128_GCM_SHA256_INTERNAL};
10
11#[derive(Clone, Debug)]
13pub struct Secrets {
14 client: hkdf::Prk,
16 server: hkdf::Prk,
18 suite: &'static Tls13CipherSuite,
20 is_client: bool,
21}
22
23impl Secrets {
24 pub fn new(
25 client: hkdf::Prk,
26 server: hkdf::Prk,
27 suite: &'static Tls13CipherSuite,
28 is_client: bool,
29 ) -> Self {
30 Self {
31 client,
32 server,
33 suite,
34 is_client,
35 }
36 }
37
38 pub fn next_packet_keys(&mut self) -> PacketKeySet {
40 let keys = PacketKeySet::new(self);
41 self.update();
42 keys
43 }
44
45 fn update(&mut self) {
46 let hkdf_alg = self.suite.hkdf_algorithm;
47 self.client = hkdf_expand(&self.client, hkdf_alg, b"quic ku", &[]);
48 self.server = hkdf_expand(&self.server, hkdf_alg, b"quic ku", &[]);
49 }
50
51 fn local_remote(&self) -> (&hkdf::Prk, &hkdf::Prk) {
52 if self.is_client {
53 (&self.client, &self.server)
54 } else {
55 (&self.server, &self.client)
56 }
57 }
58}
59
60pub trait QuicExt {
62 fn quic_transport_parameters(&self) -> Option<&[u8]>;
70
71 fn zero_rtt_keys(&self) -> Option<DirectionalKeys>;
73
74 fn read_hs(&mut self, plaintext: &[u8]) -> Result<(), Error>;
79
80 fn write_hs(&mut self, buf: &mut Vec<u8>) -> Option<KeyChange>;
84
85 fn alert(&self) -> Option<AlertDescription>;
89}
90
91pub struct DirectionalKeys {
93 pub header: HeaderProtectionKey,
95 pub packet: PacketKey,
97}
98
99impl DirectionalKeys {
100 pub fn new(suite: &'static Tls13CipherSuite, secret: &hkdf::Prk) -> Self {
101 Self {
102 header: HeaderProtectionKey::new(suite, secret),
103 packet: PacketKey::new(suite, secret),
104 }
105 }
106}
107
108pub struct HeaderProtectionKey(aead::quic::HeaderProtectionKey);
110
111impl HeaderProtectionKey {
112 fn new(suite: &'static Tls13CipherSuite, secret: &hkdf::Prk) -> Self {
113 let alg = match suite.common.bulk {
114 BulkAlgorithm::Aes128Gcm => &aead::quic::AES_128,
115 BulkAlgorithm::Aes256Gcm => &aead::quic::AES_256,
116 BulkAlgorithm::Chacha20Poly1305 => &aead::quic::CHACHA20,
117 };
118
119 Self(hkdf_expand(secret, alg, b"quic hp", &[]))
120 }
121
122 #[inline]
143 pub fn encrypt_in_place(
144 &self,
145 sample: &[u8],
146 first: &mut u8,
147 packet_number: &mut [u8],
148 ) -> Result<(), Error> {
149 self.xor_in_place(sample, first, packet_number, false)
150 }
151
152 #[inline]
174 pub fn decrypt_in_place(
175 &self,
176 sample: &[u8],
177 first: &mut u8,
178 packet_number: &mut [u8],
179 ) -> Result<(), Error> {
180 self.xor_in_place(sample, first, packet_number, true)
181 }
182
183 fn xor_in_place(
184 &self,
185 sample: &[u8],
186 first: &mut u8,
187 packet_number: &mut [u8],
188 masked: bool,
189 ) -> Result<(), Error> {
190 let mask = self
193 .0
194 .new_mask(sample)
195 .map_err(|_| Error::General("sample of invalid length".into()))?;
196
197 let (first_mask, pn_mask) = mask.split_first().unwrap();
200
201 if packet_number.len() > pn_mask.len() {
204 return Err(Error::General("packet number too long".into()));
205 }
206
207 const LONG_HEADER_FORM: u8 = 0x80;
211 let bits = match *first & LONG_HEADER_FORM == LONG_HEADER_FORM {
212 true => 0x0f, false => 0x1f, };
215
216 let first_plain = match masked {
217 true => *first ^ (first_mask & bits),
219 false => *first,
221 };
222 let pn_len = (first_plain & 0x03) as usize + 1;
223
224 *first ^= first_mask & bits;
225 for (dst, m) in packet_number.iter_mut().zip(pn_mask).take(pn_len) {
226 *dst ^= m;
227 }
228
229 Ok(())
230 }
231
232 #[inline]
234 pub fn sample_len(&self) -> usize {
235 self.0.algorithm().sample_len()
236 }
237}
238
239pub struct PacketKey {
241 key: aead::LessSafeKey,
243 iv: Iv,
245 suite: &'static Tls13CipherSuite,
247}
248
249impl PacketKey {
250 fn new(suite: &'static Tls13CipherSuite, secret: &hkdf::Prk) -> Self {
251 Self {
252 key: aead::LessSafeKey::new(hkdf_expand(
253 secret,
254 suite.common.aead_algorithm,
255 b"quic key",
256 &[],
257 )),
258 iv: hkdf_expand(secret, IvLen, b"quic iv", &[]),
259 suite,
260 }
261 }
262
263 pub fn encrypt_in_place(
271 &self,
272 packet_number: u64,
273 header: &[u8],
274 payload: &mut [u8],
275 ) -> Result<Tag, Error> {
276 let aad = aead::Aad::from(header);
277 let nonce = nonce_for(packet_number, &self.iv);
278 let tag = self
279 .key
280 .seal_in_place_separate_tag(nonce, aad, payload)
281 .map_err(|_| Error::EncryptError)?;
282 Ok(Tag(tag))
283 }
284
285 pub fn decrypt_in_place<'a>(
293 &self,
294 packet_number: u64,
295 header: &[u8],
296 payload: &'a mut [u8],
297 ) -> Result<&'a [u8], Error> {
298 let payload_len = payload.len();
299 let aad = aead::Aad::from(header);
300 let nonce = nonce_for(packet_number, &self.iv);
301 self.key
302 .open_in_place(nonce, aad, payload)
303 .map_err(|_| Error::DecryptError)?;
304
305 let plain_len = payload_len - self.key.algorithm().tag_len();
306 Ok(&payload[..plain_len])
307 }
308
309 #[inline]
313 pub fn confidentiality_limit(&self) -> u64 {
314 self.suite.confidentiality_limit
315 }
316
317 #[inline]
321 pub fn integrity_limit(&self) -> u64 {
322 self.suite.integrity_limit
323 }
324
325 #[inline]
327 pub fn tag_len(&self) -> usize {
328 self.key.algorithm().tag_len()
329 }
330}
331
332pub struct Tag(aead::Tag);
334
335impl AsRef<[u8]> for Tag {
336 #[inline]
337 fn as_ref(&self) -> &[u8] {
338 self.0.as_ref()
339 }
340}
341
342pub struct PacketKeySet {
344 pub local: PacketKey,
346 pub remote: PacketKey,
348}
349
350impl PacketKeySet {
351 fn new(secrets: &Secrets) -> Self {
352 let (local, remote) = secrets.local_remote();
353 Self {
354 local: PacketKey::new(secrets.suite, local),
355 remote: PacketKey::new(secrets.suite, remote),
356 }
357 }
358}
359
360pub struct Keys {
362 pub local: DirectionalKeys,
364 pub remote: DirectionalKeys,
366}
367
368impl Keys {
369 pub fn initial(version: Version, client_dst_connection_id: &[u8], is_client: bool) -> Self {
371 const CLIENT_LABEL: &[u8] = b"client in";
372 const SERVER_LABEL: &[u8] = b"server in";
373 let salt = version.initial_salt();
374 let hs_secret = hkdf::Salt::new(hkdf::HKDF_SHA256, salt).extract(client_dst_connection_id);
375
376 let secrets = Secrets {
377 client: hkdf_expand(&hs_secret, hkdf::HKDF_SHA256, CLIENT_LABEL, &[]),
378 server: hkdf_expand(&hs_secret, hkdf::HKDF_SHA256, SERVER_LABEL, &[]),
379 suite: TLS13_AES_128_GCM_SHA256_INTERNAL,
380 is_client,
381 };
382 Self::new(&secrets)
383 }
384
385 fn new(secrets: &Secrets) -> Self {
386 let (local, remote) = secrets.local_remote();
387 Self {
388 local: DirectionalKeys::new(secrets.suite, local),
389 remote: DirectionalKeys::new(secrets.suite, remote),
390 }
391 }
392}
393
394#[allow(clippy::large_enum_variant)]
408pub enum KeyChange {
409 Handshake {
411 keys: Keys,
413 },
414 OneRtt {
416 keys: Keys,
418 next: Secrets,
420 },
421}
422
423fn nonce_for(packet_number: u64, iv: &Iv) -> ring::aead::Nonce {
425 let mut out = [0; aead::NONCE_LEN];
426 out[4..].copy_from_slice(&packet_number.to_be_bytes());
427 for (out, inp) in out.iter_mut().zip(iv.0.iter()) {
428 *out ^= inp;
429 }
430 aead::Nonce::assume_unique_for_key(out)
431}
432
433#[non_exhaustive]
437#[derive(Clone, Copy)]
438pub enum Version {
439 V1Draft,
441 V1,
443}
444
445impl Version {
446 fn initial_salt(self) -> &'static [u8; 20] {
447 match self {
448 Self::V1Draft => &[
449 0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61,
451 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99,
452 ],
453 Self::V1 => &[
454 0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8,
456 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a,
457 ],
458 }
459 }
460}
461
462#[cfg(test)]
463mod tests {
464 use super::*;
465
466 #[test_log::test]
467 fn short_packet_header_protection() {
468 const PN: u64 = 654360564;
471 const SECRET: &[u8] = &[
472 0x9a, 0xc3, 0x12, 0xa7, 0xf8, 0x77, 0x46, 0x8e, 0xbe, 0x69, 0x42, 0x27, 0x48, 0xad,
473 0x00, 0xa1, 0x54, 0x43, 0xf1, 0x82, 0x03, 0xa0, 0x7d, 0x60, 0x60, 0xf6, 0x88, 0xf3,
474 0x0f, 0x21, 0x63, 0x2b,
475 ];
476
477 let secret = hkdf::Prk::new_less_safe(hkdf::HKDF_SHA256, SECRET);
478 use crate::tls::rustls::tls13::TLS13_CHACHA20_POLY1305_SHA256_INTERNAL;
479 let hpk = HeaderProtectionKey::new(TLS13_CHACHA20_POLY1305_SHA256_INTERNAL, &secret);
480 let packet = PacketKey::new(TLS13_CHACHA20_POLY1305_SHA256_INTERNAL, &secret);
481
482 const PLAIN: &[u8] = &[0x42, 0x00, 0xbf, 0xf4, 0x01];
483
484 let mut buf = PLAIN.to_vec();
485 let (header, payload) = buf.split_at_mut(4);
486 let tag = packet.encrypt_in_place(PN, &*header, payload).unwrap();
487 buf.extend(tag.as_ref());
488
489 let pn_offset = 1;
490 let (header, sample) = buf.split_at_mut(pn_offset + 4);
491 let (first, rest) = header.split_at_mut(1);
492 let sample = &sample[..hpk.sample_len()];
493 hpk.encrypt_in_place(sample, &mut first[0], dbg!(rest))
494 .unwrap();
495
496 const PROTECTED: &[u8] = &[
497 0x4c, 0xfe, 0x41, 0x89, 0x65, 0x5e, 0x5c, 0xd5, 0x5c, 0x41, 0xf6, 0x90, 0x80, 0x57,
498 0x5d, 0x79, 0x99, 0xc2, 0x5a, 0x5b, 0xfb,
499 ];
500
501 assert_eq!(&buf, PROTECTED);
502
503 let (header, sample) = buf.split_at_mut(pn_offset + 4);
504 let (first, rest) = header.split_at_mut(1);
505 let sample = &sample[..hpk.sample_len()];
506 hpk.decrypt_in_place(sample, &mut first[0], rest).unwrap();
507
508 let (header, payload_tag) = buf.split_at_mut(4);
509 let plain = packet.decrypt_in_place(PN, &*header, payload_tag).unwrap();
510
511 assert_eq!(plain, &PLAIN[4..]);
512 }
513
514 #[test_log::test]
515 fn key_update_test_vector() {
516 fn equal_prk(x: &hkdf::Prk, y: &hkdf::Prk) -> bool {
517 let mut x_data = [0; 16];
518 let mut y_data = [0; 16];
519 let x_okm = x.expand(&[b"info"], &aead::quic::AES_128).unwrap();
520 x_okm.fill(&mut x_data[..]).unwrap();
521 let y_okm = y.expand(&[b"info"], &aead::quic::AES_128).unwrap();
522 y_okm.fill(&mut y_data[..]).unwrap();
523 x_data == y_data
524 }
525
526 let mut secrets = Secrets {
527 client: hkdf::Prk::new_less_safe(
529 hkdf::HKDF_SHA256,
530 &[
531 0xb8, 0x76, 0x77, 0x08, 0xf8, 0x77, 0x23, 0x58, 0xa6, 0xea, 0x9f, 0xc4, 0x3e,
532 0x4a, 0xdd, 0x2c, 0x96, 0x1b, 0x3f, 0x52, 0x87, 0xa6, 0xd1, 0x46, 0x7e, 0xe0,
533 0xae, 0xab, 0x33, 0x72, 0x4d, 0xbf,
534 ],
535 ),
536 server: hkdf::Prk::new_less_safe(
537 hkdf::HKDF_SHA256,
538 &[
539 0x42, 0xdc, 0x97, 0x21, 0x40, 0xe0, 0xf2, 0xe3, 0x98, 0x45, 0xb7, 0x67, 0x61,
540 0x34, 0x39, 0xdc, 0x67, 0x58, 0xca, 0x43, 0x25, 0x9b, 0x87, 0x85, 0x06, 0x82,
541 0x4e, 0xb1, 0xe4, 0x38, 0xd8, 0x55,
542 ],
543 ),
544 suite: TLS13_AES_128_GCM_SHA256_INTERNAL,
545 is_client: true,
546 };
547 secrets.update();
548
549 assert!(equal_prk(
550 &secrets.client,
551 &hkdf::Prk::new_less_safe(
552 hkdf::HKDF_SHA256,
553 &[
554 0x42, 0xca, 0xc8, 0xc9, 0x1c, 0xd5, 0xeb, 0x40, 0x68, 0x2e, 0x43, 0x2e, 0xdf,
555 0x2d, 0x2b, 0xe9, 0xf4, 0x1a, 0x52, 0xca, 0x6b, 0x22, 0xd8, 0xe6, 0xcd, 0xb1,
556 0xe8, 0xac, 0xa9, 0x6, 0x1f, 0xce
557 ]
558 )
559 ));
560 assert!(equal_prk(
561 &secrets.server,
562 &hkdf::Prk::new_less_safe(
563 hkdf::HKDF_SHA256,
564 &[
565 0xeb, 0x7f, 0x5e, 0x2a, 0x12, 0x3f, 0x40, 0x7d, 0xb4, 0x99, 0xe3, 0x61, 0xca,
566 0xe5, 0x90, 0xd4, 0xd9, 0x92, 0xe1, 0x4b, 0x7a, 0xce, 0x3, 0xc2, 0x44, 0xe0,
567 0x42, 0x21, 0x15, 0xb6, 0xd3, 0x8a
568 ]
569 )
570 ));
571 }
572}