rustls 0.20.0-beta2

Rustls is a modern TLS library written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/// This module contains optional APIs for implementing QUIC TLS.
pub use crate::cipher::Iv;
use crate::cipher::IvLen;
pub use crate::client::ClientQuicExt;
use crate::conn::ConnectionCommon;
use crate::error::Error;
use crate::key_schedule::hkdf_expand;
use crate::msgs::base::Payload;
use crate::msgs::enums::{AlertDescription, ContentType, ProtocolVersion};
use crate::msgs::message::PlainMessage;
pub use crate::server::ServerQuicExt;
use crate::suites::{BulkAlgorithm, Tls13CipherSuite, TLS13_AES_128_GCM_SHA256_INTERNAL};

use ring::{aead, hkdf};

/// Secrets used to encrypt/decrypt traffic
#[derive(Clone, Debug)]
pub(crate) struct Secrets {
    /// Secret used to encrypt packets transmitted by the client
    pub(crate) client: hkdf::Prk,
    /// Secret used to encrypt packets transmitted by the server
    pub(crate) server: hkdf::Prk,
}

impl Secrets {
    fn local_remote(&self, is_client: bool) -> (&hkdf::Prk, &hkdf::Prk) {
        if is_client {
            (&self.client, &self.server)
        } else {
            (&self.server, &self.client)
        }
    }
}

/// Generic methods for QUIC sessions
pub trait QuicExt {
    /// Return the TLS-encoded transport parameters for the session's peer.
    ///
    /// While the transport parameters are technically available prior to the
    /// completion of the handshake, they cannot be fully trusted until the
    /// handshake completes, and reliance on them should be minimized.
    /// However, any tampering with the parameters will cause the handshake
    /// to fail.
    fn quic_transport_parameters(&self) -> Option<&[u8]>;

    /// Compute the keys for encrypting/decrypting 0-RTT packets, if available
    fn zero_rtt_keys(&self) -> Option<DirectionalKeys>;

    /// Consume unencrypted TLS handshake data.
    ///
    /// Handshake data obtained from separate encryption levels should be supplied in separate calls.
    fn read_hs(&mut self, plaintext: &[u8]) -> Result<(), Error>;

    /// Emit unencrypted TLS handshake data.
    ///
    /// When this returns `Some(_)`, the new keys must be used for future handshake data.
    fn write_hs(&mut self, buf: &mut Vec<u8>) -> Option<Keys>;

    /// Emit the TLS description code of a fatal alert, if one has arisen.
    ///
    /// Check after `read_hs` returns `Err(_)`.
    fn alert(&self) -> Option<AlertDescription>;

    /// Compute the keys to use following a 1-RTT key update
    ///
    /// Will return `None` until the handshake is complete.
    fn next_1rtt_keys(&mut self) -> Option<PacketKeySet>;
}

/// Keys used to communicate in a single direction
pub struct DirectionalKeys {
    /// Encrypts or decrypts a packet's headers
    pub header: aead::quic::HeaderProtectionKey,
    /// Encrypts or decrypts the payload of a packet
    pub packet: PacketKey,
}

impl DirectionalKeys {
    pub(crate) fn new(suite: &'static Tls13CipherSuite, secret: &hkdf::Prk) -> Self {
        let hp_alg = match suite.common.bulk {
            BulkAlgorithm::Aes128Gcm => &aead::quic::AES_128,
            BulkAlgorithm::Aes256Gcm => &aead::quic::AES_256,
            BulkAlgorithm::Chacha20Poly1305 => &aead::quic::CHACHA20,
        };

        Self {
            header: hkdf_expand(secret, hp_alg, b"quic hp", &[]),
            packet: PacketKey::new(suite, secret),
        }
    }
}

/// Keys to encrypt or decrypt the payload of a packet
pub struct PacketKey {
    /// Encrypts or decrypts a packet's payload
    pub key: aead::LessSafeKey,
    /// Computes unique nonces for each packet
    pub iv: Iv,
}

impl PacketKey {
    fn new(suite: &'static Tls13CipherSuite, secret: &hkdf::Prk) -> Self {
        Self {
            key: aead::LessSafeKey::new(hkdf_expand(
                secret,
                suite.common.aead_algorithm,
                b"quic key",
                &[],
            )),
            iv: hkdf_expand(secret, IvLen, b"quic iv", &[]),
        }
    }
}

/// Packet protection keys for bidirectional 1-RTT communication
pub struct PacketKeySet {
    /// Encrypts outgoing packets
    pub local: PacketKey,
    /// Decrypts incoming packets
    pub remote: PacketKey,
}

/// Complete set of keys used to communicate with the peer
pub struct Keys {
    /// Encrypts outgoing packets
    pub local: DirectionalKeys,
    /// Decrypts incoming packets
    pub remote: DirectionalKeys,
}

impl Keys {
    /// Construct keys for use with initial packets
    pub fn initial(
        initial_salt: &hkdf::Salt,
        client_dst_connection_id: &[u8],
        is_client: bool,
    ) -> Self {
        const CLIENT_LABEL: &[u8] = b"client in";
        const SERVER_LABEL: &[u8] = b"server in";
        let hs_secret = initial_salt.extract(client_dst_connection_id);

        let secrets = Secrets {
            client: hkdf_expand(&hs_secret, hkdf::HKDF_SHA256, CLIENT_LABEL, &[]),
            server: hkdf_expand(&hs_secret, hkdf::HKDF_SHA256, SERVER_LABEL, &[]),
        };
        Self::new(TLS13_AES_128_GCM_SHA256_INTERNAL, is_client, &secrets)
    }

    fn new(suite: &'static Tls13CipherSuite, is_client: bool, secrets: &Secrets) -> Self {
        let (local, remote) = secrets.local_remote(is_client);
        Self {
            local: DirectionalKeys::new(suite, local),
            remote: DirectionalKeys::new(suite, remote),
        }
    }
}

pub(crate) fn read_hs(this: &mut ConnectionCommon, plaintext: &[u8]) -> Result<(), Error> {
    if this
        .handshake_joiner
        .take_message(PlainMessage {
            typ: ContentType::Handshake,
            version: ProtocolVersion::TLSv1_3,
            payload: Payload::new(plaintext.to_vec()),
        })
        .is_none()
    {
        this.quic.alert = Some(AlertDescription::DecodeError);
        return Err(Error::CorruptMessage);
    }
    Ok(())
}

pub(crate) fn write_hs(this: &mut ConnectionCommon, buf: &mut Vec<u8>) -> Option<Keys> {
    while let Some((_, msg)) = this.quic.hs_queue.pop_front() {
        buf.extend_from_slice(&msg);
        if let Some(&(true, _)) = this.quic.hs_queue.front() {
            if this.quic.hs_secrets.is_some() {
                // Allow the caller to switch keys before proceeding.
                break;
            }
        }
    }

    let suite = this
        .get_suite()
        .and_then(|suite| suite.tls13())?;
    if let Some(secrets) = this.quic.hs_secrets.take() {
        return Some(Keys::new(suite, this.is_client, &secrets));
    }

    if let Some(secrets) = this.quic.traffic_secrets.as_ref() {
        if !this.quic.returned_traffic_keys {
            this.quic.returned_traffic_keys = true;
            return Some(Keys::new(suite, this.is_client, secrets));
        }
    }

    None
}

pub(crate) fn next_1rtt_keys(this: &mut ConnectionCommon) -> Option<PacketKeySet> {
    let suite = this
        .get_suite()
        .and_then(|suite| suite.tls13())?;
    let secrets = this.quic.traffic_secrets.as_ref()?;
    let next = next_1rtt_secrets(suite.hkdf_algorithm, secrets);

    let (local, remote) = next.local_remote(this.is_client);
    let keys = PacketKeySet {
        local: PacketKey::new(suite, local),
        remote: PacketKey::new(suite, remote),
    };

    this.quic.traffic_secrets = Some(next);
    Some(keys)
}

fn next_1rtt_secrets(hkdf_alg: hkdf::Algorithm, prev: &Secrets) -> Secrets {
    Secrets {
        client: hkdf_expand(&prev.client, hkdf_alg, b"quic ku", &[]),
        server: hkdf_expand(&prev.server, hkdf_alg, b"quic ku", &[]),
    }
}

/// QUIC protocol version
///
/// Governs version-specific behavior in the TLS layer
#[non_exhaustive]
pub enum Version {
    /// Draft versions prior to V1
    V1Draft,
    /// First stable RFC
    V1,
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn initial_keys_test_vectors() {
        // Test vectors based on draft 27
        const INITIAL_SALT: [u8; 20] = [
            0xc3, 0xee, 0xf7, 0x12, 0xc7, 0x2e, 0xbb, 0x5a, 0x11, 0xa7, 0xd2, 0x43, 0x2b, 0xb4,
            0x63, 0x65, 0xbe, 0xf9, 0xf5, 0x02,
        ];

        const CONNECTION_ID: &[u8] = &[0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08];
        const PACKET_NUMBER: u64 = 42;

        let initial_salt = hkdf::Salt::new(hkdf::HKDF_SHA256, &INITIAL_SALT);
        let server_keys = Keys::initial(&initial_salt, &CONNECTION_ID, false);
        let client_keys = Keys::initial(&initial_salt, &CONNECTION_ID, true);

        // Nonces
        const SERVER_NONCE: [u8; 12] = [
            0x5e, 0x5a, 0xe6, 0x51, 0xfd, 0x1e, 0x84, 0x95, 0xaf, 0x13, 0x50, 0xa1,
        ];
        assert_eq!(
            server_keys
                .local
                .packet
                .iv
                .nonce_for(PACKET_NUMBER)
                .as_ref(),
            &SERVER_NONCE
        );
        assert_eq!(
            client_keys
                .remote
                .packet
                .iv
                .nonce_for(PACKET_NUMBER)
                .as_ref(),
            &SERVER_NONCE
        );
        const CLIENT_NONCE: [u8; 12] = [
            0x86, 0x81, 0x35, 0x94, 0x10, 0xa7, 0x0b, 0xb9, 0xc9, 0x2f, 0x04, 0x0a,
        ];
        assert_eq!(
            server_keys
                .remote
                .packet
                .iv
                .nonce_for(PACKET_NUMBER)
                .as_ref(),
            &CLIENT_NONCE
        );
        assert_eq!(
            client_keys
                .local
                .packet
                .iv
                .nonce_for(PACKET_NUMBER)
                .as_ref(),
            &CLIENT_NONCE
        );

        // Header encryption mask
        const SAMPLE: &[u8] = &[
            0x70, 0x02, 0x59, 0x6f, 0x99, 0xae, 0x67, 0xab, 0xf6, 0x5a, 0x58, 0x52, 0xf5, 0x4f,
            0x58, 0xc3,
        ];

        const SERVER_MASK: [u8; 5] = [0x38, 0x16, 0x8a, 0x0c, 0x25];
        assert_eq!(
            server_keys
                .local
                .header
                .new_mask(SAMPLE)
                .unwrap(),
            SERVER_MASK
        );
        assert_eq!(
            client_keys
                .remote
                .header
                .new_mask(SAMPLE)
                .unwrap(),
            SERVER_MASK
        );
        const CLIENT_MASK: [u8; 5] = [0xae, 0x96, 0x2e, 0x67, 0xec];
        assert_eq!(
            server_keys
                .remote
                .header
                .new_mask(SAMPLE)
                .unwrap(),
            CLIENT_MASK
        );
        assert_eq!(
            client_keys
                .local
                .header
                .new_mask(SAMPLE)
                .unwrap(),
            CLIENT_MASK
        );

        const AAD: &[u8] = &[
            0xc9, 0xff, 0x00, 0x00, 0x1b, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62,
            0xb5, 0x00, 0x40, 0x74, 0x16, 0x8b,
        ];
        let aad = aead::Aad::from(AAD);
        const PLAINTEXT: [u8; 12] = [
            0x0d, 0x00, 0x00, 0x00, 0x00, 0x18, 0x41, 0x0a, 0x02, 0x00, 0x00, 0x56,
        ];
        let mut payload = PLAINTEXT;
        let server_nonce = server_keys
            .local
            .packet
            .iv
            .nonce_for(PACKET_NUMBER);
        let tag = server_keys
            .local
            .packet
            .key
            .seal_in_place_separate_tag(server_nonce, aad, &mut payload)
            .unwrap();
        assert_eq!(
            payload,
            [
                0x0d, 0x91, 0x96, 0x31, 0xc0, 0xeb, 0x84, 0xf2, 0x88, 0x59, 0xfe, 0xc0
            ]
        );
        assert_eq!(
            tag.as_ref(),
            &[
                0xdf, 0xee, 0x06, 0x81, 0x9e, 0x7a, 0x08, 0x34, 0xe4, 0x94, 0x19, 0x79, 0x5f, 0xe0,
                0xd7, 0x3f
            ]
        );

        let aad = aead::Aad::from(AAD);
        let mut payload = PLAINTEXT;
        let client_nonce = client_keys
            .local
            .packet
            .iv
            .nonce_for(PACKET_NUMBER);
        let tag = client_keys
            .local
            .packet
            .key
            .seal_in_place_separate_tag(client_nonce, aad, &mut payload)
            .unwrap();
        assert_eq!(
            payload,
            [
                0x89, 0x6c, 0x66, 0x91, 0xe0, 0x9f, 0x47, 0x7a, 0x91, 0x42, 0xa4, 0x46
            ]
        );
        assert_eq!(
            tag.as_ref(),
            &[
                0xb6, 0xff, 0xef, 0x89, 0xd5, 0xcb, 0x53, 0xd0, 0x98, 0xf7, 0x40, 0xa, 0x8d, 0x97,
                0x72, 0x6e
            ]
        );
    }

    #[test]
    fn key_update_test_vector() {
        fn equal_prk(x: &hkdf::Prk, y: &hkdf::Prk) -> bool {
            let mut x_data = [0; 16];
            let mut y_data = [0; 16];
            let x_okm = x
                .expand(&[b"info"], &aead::quic::AES_128)
                .unwrap();
            x_okm.fill(&mut x_data[..]).unwrap();
            let y_okm = y
                .expand(&[b"info"], &aead::quic::AES_128)
                .unwrap();
            y_okm.fill(&mut y_data[..]).unwrap();
            x_data == y_data
        }

        let initial = Secrets {
            // Constant dummy values for reproducibility
            client: hkdf::Prk::new_less_safe(
                hkdf::HKDF_SHA256,
                &[
                    0xb8, 0x76, 0x77, 0x08, 0xf8, 0x77, 0x23, 0x58, 0xa6, 0xea, 0x9f, 0xc4, 0x3e,
                    0x4a, 0xdd, 0x2c, 0x96, 0x1b, 0x3f, 0x52, 0x87, 0xa6, 0xd1, 0x46, 0x7e, 0xe0,
                    0xae, 0xab, 0x33, 0x72, 0x4d, 0xbf,
                ],
            ),
            server: hkdf::Prk::new_less_safe(
                hkdf::HKDF_SHA256,
                &[
                    0x42, 0xdc, 0x97, 0x21, 0x40, 0xe0, 0xf2, 0xe3, 0x98, 0x45, 0xb7, 0x67, 0x61,
                    0x34, 0x39, 0xdc, 0x67, 0x58, 0xca, 0x43, 0x25, 0x9b, 0x87, 0x85, 0x06, 0x82,
                    0x4e, 0xb1, 0xe4, 0x38, 0xd8, 0x55,
                ],
            ),
        };
        let updated = next_1rtt_secrets(hkdf::HKDF_SHA256, &initial);

        assert!(equal_prk(
            &updated.client,
            &hkdf::Prk::new_less_safe(
                hkdf::HKDF_SHA256,
                &[
                    0x42, 0xca, 0xc8, 0xc9, 0x1c, 0xd5, 0xeb, 0x40, 0x68, 0x2e, 0x43, 0x2e, 0xdf,
                    0x2d, 0x2b, 0xe9, 0xf4, 0x1a, 0x52, 0xca, 0x6b, 0x22, 0xd8, 0xe6, 0xcd, 0xb1,
                    0xe8, 0xac, 0xa9, 0x6, 0x1f, 0xce
                ]
            )
        ));
        assert!(equal_prk(
            &updated.server,
            &hkdf::Prk::new_less_safe(
                hkdf::HKDF_SHA256,
                &[
                    0xeb, 0x7f, 0x5e, 0x2a, 0x12, 0x3f, 0x40, 0x7d, 0xb4, 0x99, 0xe3, 0x61, 0xca,
                    0xe5, 0x90, 0xd4, 0xd9, 0x92, 0xe1, 0x4b, 0x7a, 0xce, 0x3, 0xc2, 0x44, 0xe0,
                    0x42, 0x21, 0x15, 0xb6, 0xd3, 0x8a
                ]
            )
        ));
    }
}