tlspuffin/tls/rustls/
quic.rs

1use ring::{aead, hkdf};
2
3/// This module contains optional APIs for implementing QUIC TLS.
4use 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/// Secrets used to encrypt/decrypt traffic
12#[derive(Clone, Debug)]
13pub struct Secrets {
14    /// Secret used to encrypt packets transmitted by the client
15    client: hkdf::Prk,
16    /// Secret used to encrypt packets transmitted by the server
17    server: hkdf::Prk,
18    /// Cipher suite used with these secrets
19    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    /// Derive the next set of packet keys
39    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
60/// Generic methods for QUIC sessions
61pub trait QuicExt {
62    /// Return the TLS-encoded transport parameters for the session's peer.
63    ///
64    /// While the transport parameters are technically available prior to the
65    /// completion of the handshake, they cannot be fully trusted until the
66    /// handshake completes, and reliance on them should be minimized.
67    /// However, any tampering with the parameters will cause the handshake
68    /// to fail.
69    fn quic_transport_parameters(&self) -> Option<&[u8]>;
70
71    /// Compute the keys for encrypting/decrypting 0-RTT packets, if available
72    fn zero_rtt_keys(&self) -> Option<DirectionalKeys>;
73
74    /// Consume unencrypted TLS handshake data.
75    ///
76    /// Handshake data obtained from separate encryption levels should be supplied in separate
77    /// calls.
78    fn read_hs(&mut self, plaintext: &[u8]) -> Result<(), Error>;
79
80    /// Emit unencrypted TLS handshake data.
81    ///
82    /// When this returns `Some(_)`, the new keys must be used for future handshake data.
83    fn write_hs(&mut self, buf: &mut Vec<u8>) -> Option<KeyChange>;
84
85    /// Emit the TLS description code of a fatal alert, if one has arisen.
86    ///
87    /// Check after `read_hs` returns `Err(_)`.
88    fn alert(&self) -> Option<AlertDescription>;
89}
90
91/// Keys used to communicate in a single direction
92pub struct DirectionalKeys {
93    /// Encrypts or decrypts a packet's headers
94    pub header: HeaderProtectionKey,
95    /// Encrypts or decrypts the payload of a packet
96    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
108/// A QUIC header protection key
109pub 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    /// Adds QUIC Header Protection.
123    ///
124    /// `sample` must contain the sample of encrypted payload; see
125    /// [Header Protection Sample].
126    ///
127    /// `first` must reference the first byte of the header, referred to as
128    /// `packet[0]` in [Header Protection Application].
129    ///
130    /// `packet_number` must reference the Packet Number field; this is
131    /// `packet[pn_offset:pn_offset+pn_length]` in [Header Protection Application].
132    ///
133    /// Returns an error without modifying anything if `sample` is not
134    /// the correct length (see [Header Protection Sample] and [`Self::sample_len()`]),
135    /// or `packet_number` is longer than allowed (see [Packet Number Encoding and Decoding]).
136    ///
137    /// Otherwise, `first` and `packet_number` will have the header protection added.
138    ///
139    /// [Header Protection Application]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.1
140    /// [Header Protection Sample]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.2
141    /// [Packet Number Encoding and Decoding]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.1
142    #[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    /// Removes QUIC Header Protection.
153    ///
154    /// `sample` must contain the sample of encrypted payload; see
155    /// [Header Protection Sample].
156    ///
157    /// `first` must reference the first byte of the header, referred to as
158    /// `packet[0]` in [Header Protection Application].
159    ///
160    /// `packet_number` must reference the Packet Number field; this is
161    /// `packet[pn_offset:pn_offset+pn_length]` in [Header Protection Application].
162    ///
163    /// Returns an error without modifying anything if `sample` is not
164    /// the correct length (see [Header Protection Sample] and [`Self::sample_len()`]),
165    /// or `packet_number` is longer than allowed (see
166    /// [Packet Number Encoding and Decoding]).
167    ///
168    /// Otherwise, `first` and `packet_number` will have the header protection removed.
169    ///
170    /// [Header Protection Application]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.1
171    /// [Header Protection Sample]: https://datatracker.ietf.org/doc/html/rfc9001#section-5.4.2
172    /// [Packet Number Encoding and Decoding]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.1
173    #[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        // This implements [Header Protection Application] almost verbatim.
191
192        let mask = self
193            .0
194            .new_mask(sample)
195            .map_err(|_| Error::General("sample of invalid length".into()))?;
196
197        // The `unwrap()` will not panic because `new_mask` returns a
198        // non-empty result.
199        let (first_mask, pn_mask) = mask.split_first().unwrap();
200
201        // It is OK for the `mask` to be longer than `packet_number`,
202        // but a valid `packet_number` will never be longer than `mask`.
203        if packet_number.len() > pn_mask.len() {
204            return Err(Error::General("packet number too long".into()));
205        }
206
207        // Infallible from this point on. Before this point, `first` and
208        // `packet_number` are unchanged.
209
210        const LONG_HEADER_FORM: u8 = 0x80;
211        let bits = match *first & LONG_HEADER_FORM == LONG_HEADER_FORM {
212            true => 0x0f,  // Long header: 4 bits masked
213            false => 0x1f, // Short header: 5 bits masked
214        };
215
216        let first_plain = match masked {
217            // When unmasking, use the packet length bits after unmasking
218            true => *first ^ (first_mask & bits),
219            // When masking, use the packet length bits before masking
220            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    /// Expected sample length for the key's algorithm
233    #[inline]
234    pub fn sample_len(&self) -> usize {
235        self.0.algorithm().sample_len()
236    }
237}
238
239/// Keys to encrypt or decrypt the payload of a packet
240pub struct PacketKey {
241    /// Encrypts or decrypts a packet's payload
242    key: aead::LessSafeKey,
243    /// Computes unique nonces for each packet
244    iv: Iv,
245    /// The cipher suite used for this packet key
246    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    /// Encrypt a QUIC packet
264    ///
265    /// Takes a `packet_number`, used to derive the nonce; the packet `header`, which is used as
266    /// the additional authenticated data; and the `payload`. The authentication tag is returned if
267    /// encryption succeeds.
268    ///
269    /// Fails iff the payload is longer than allowed by the cipher suite's AEAD algorithm.
270    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    /// Decrypt a QUIC packet
286    ///
287    /// Takes the packet `header`, which is used as the additional authenticated data, and the
288    /// `payload`, which includes the authentication tag.
289    ///
290    /// If the return value is `Ok`, the decrypted payload can be found in `payload`, up to the
291    /// length found in the return value.
292    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    /// Number of times the packet key can be used without sacrificing confidentiality
310    ///
311    /// See <https://www.rfc-editor.org/rfc/rfc9001.html#name-confidentiality-limit>.
312    #[inline]
313    pub fn confidentiality_limit(&self) -> u64 {
314        self.suite.confidentiality_limit
315    }
316
317    /// Number of times the packet key can be used without sacrificing integrity
318    ///
319    /// See <https://www.rfc-editor.org/rfc/rfc9001.html#name-integrity-limit>.
320    #[inline]
321    pub fn integrity_limit(&self) -> u64 {
322        self.suite.integrity_limit
323    }
324
325    /// Tag length for the underlying AEAD algorithm
326    #[inline]
327    pub fn tag_len(&self) -> usize {
328        self.key.algorithm().tag_len()
329    }
330}
331
332/// AEAD tag, must be appended to encrypted cipher text
333pub 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
342/// Packet protection keys for bidirectional 1-RTT communication
343pub struct PacketKeySet {
344    /// Encrypts outgoing packets
345    pub local: PacketKey,
346    /// Decrypts incoming packets
347    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
360/// Complete set of keys used to communicate with the peer
361pub struct Keys {
362    /// Encrypts outgoing packets
363    pub local: DirectionalKeys,
364    /// Decrypts incoming packets
365    pub remote: DirectionalKeys,
366}
367
368impl Keys {
369    /// Construct keys for use with initial packets
370    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/// Key material for use in QUIC packet spaces
395///
396/// QUIC uses 4 different sets of keys (and progressive key updates for long-running connections):
397///
398/// * Initial: these can be created from [`Keys::initial()`]
399/// * 0-RTT keys: can be retrieved from [`QuicExt::zero_rtt_keys()`]
400/// * Handshake: these are returned from [`QuicExt::write_hs()`] after `ClientHello` and
401///   `ServerHello` messages have been exchanged
402/// * 1-RTT keys: these are returned from [`QuicExt::write_hs()`] after the handshake is done
403///
404/// Once the 1-RTT keys have been exchanged, either side may initiate a key update. Progressive
405/// update keys can be obtained from the [`Secrets`] returned in [`KeyChange::OneRtt`]. Note that
406/// only packet keys are updated by key updates; header protection keys remain the same.
407#[allow(clippy::large_enum_variant)]
408pub enum KeyChange {
409    /// Keys for the handshake space
410    Handshake {
411        /// Header and packet keys for the handshake space
412        keys: Keys,
413    },
414    /// Keys for 1-RTT data
415    OneRtt {
416        /// Header and packet keys for 1-RTT data
417        keys: Keys,
418        /// Secrets to derive updated keys from
419        next: Secrets,
420    },
421}
422
423/// Compute the nonce to use for encrypting or decrypting `packet_number`
424fn 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/// QUIC protocol version
434///
435/// Governs version-specific behavior in the TLS layer
436#[non_exhaustive]
437#[derive(Clone, Copy)]
438pub enum Version {
439    /// Draft versions 29, 30, 31 and 32
440    V1Draft,
441    /// First stable RFC
442    V1,
443}
444
445impl Version {
446    fn initial_salt(self) -> &'static [u8; 20] {
447        match self {
448            Self::V1Draft => &[
449                // https://datatracker.ietf.org/doc/html/draft-ietf-quic-tls-32#section-5.2
450                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                // https://www.rfc-editor.org/rfc/rfc9001.html#name-initial-secrets
455                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        // https://www.rfc-editor.org/rfc/rfc9001.html#name-chacha20-poly1305-short-hea
469
470        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            // Constant dummy values for reproducibility
528            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}