rustls 0.24.0-dev.0

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
use alloc::vec::Vec;
use core::cmp;
use core::time::Duration;

use pki_types::{DnsName, UnixTime};
use zeroize::Zeroizing;

use crate::client::Tls13ClientSessionValue;
use crate::crypto::cipher::Payload;
use crate::crypto::{CipherSuite, Identity};
use crate::enums::{ApplicationProtocol, ProtocolVersion};
use crate::error::InvalidMessage;
use crate::msgs::base::{MaybeEmpty, SizedPayload};
use crate::msgs::codec::{Codec, Reader};
use crate::sync::Arc;

pub(crate) struct Retrieved<T> {
    pub(crate) value: T,
    retrieved_at: UnixTime,
}

impl<T> Retrieved<T> {
    pub(crate) fn new(value: T, retrieved_at: UnixTime) -> Self {
        Self {
            value,
            retrieved_at,
        }
    }

    pub(crate) fn map<M>(&self, f: impl FnOnce(&T) -> Option<&M>) -> Option<Retrieved<&M>> {
        Some(Retrieved {
            value: f(&self.value)?,
            retrieved_at: self.retrieved_at,
        })
    }
}

impl Retrieved<&Tls13ClientSessionValue> {
    pub(crate) fn obfuscated_ticket_age(&self) -> u32 {
        let age_secs = self
            .retrieved_at
            .as_secs()
            .saturating_sub(self.value.common.epoch);
        let age_millis = age_secs as u32 * 1000;
        age_millis.wrapping_add(self.value.age_add)
    }
}

impl<T: core::ops::Deref<Target = ClientSessionCommon>> Retrieved<T> {
    pub(crate) fn has_expired(&self) -> bool {
        let common = &*self.value;
        common.lifetime != Duration::ZERO
            && common
                .epoch
                .saturating_add(common.lifetime.as_secs())
                < self.retrieved_at.as_secs()
    }
}

impl<T> core::ops::Deref for Retrieved<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

#[derive(Debug, Clone)]
pub struct ClientSessionCommon {
    pub(crate) ticket: Arc<SizedPayload<'static, u16>>,
    pub(crate) epoch: u64,
    lifetime: Duration,
    peer_identity: Arc<Identity<'static>>,
}

impl ClientSessionCommon {
    pub(crate) fn new(
        ticket: Arc<SizedPayload<'static, u16>>,
        time_now: UnixTime,
        lifetime: Duration,
        peer_identity: Identity<'static>,
    ) -> Self {
        Self {
            ticket,
            epoch: time_now.as_secs(),
            lifetime: cmp::min(lifetime, MAX_TICKET_LIFETIME),
            peer_identity: Arc::new(peer_identity),
        }
    }

    pub(crate) fn peer_identity(&self) -> &Identity<'static> {
        &self.peer_identity
    }

    pub(crate) fn ticket(&self) -> &[u8] {
        (*self.ticket).bytes()
    }
}

static MAX_TICKET_LIFETIME: Duration = Duration::from_secs(7 * 24 * 60 * 60);

/// This is the maximum allowed skew between server and client clocks, over
/// the maximum ticket lifetime period.  This encompasses TCP retransmission
/// times in case packet loss occurs when the client sends the ClientHello
/// or receives the NewSessionTicket, _and_ actual clock skew over this period.
static MAX_FRESHNESS_SKEW_MS: u32 = 60 * 1000;

// --- Server types ---
#[non_exhaustive]
#[derive(Debug)]
pub enum ServerSessionValue {
    Tls12(Tls12ServerSessionValue),
    Tls13(Tls13ServerSessionValue),
}

impl Codec<'_> for ServerSessionValue {
    fn encode(&self, bytes: &mut Vec<u8>) {
        match self {
            Self::Tls12(value) => {
                ProtocolVersion::TLSv1_2.encode(bytes);
                value.encode(bytes);
            }
            Self::Tls13(value) => {
                ProtocolVersion::TLSv1_3.encode(bytes);
                value.encode(bytes);
            }
        }
    }

    fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> {
        match ProtocolVersion::read(r)? {
            ProtocolVersion::TLSv1_2 => Ok(Self::Tls12(Tls12ServerSessionValue::read(r)?)),
            ProtocolVersion::TLSv1_3 => Ok(Self::Tls13(Tls13ServerSessionValue::read(r)?)),
            _ => Err(InvalidMessage::UnknownProtocolVersion),
        }
    }
}

#[derive(Debug)]
pub struct Tls12ServerSessionValue {
    pub(crate) common: CommonServerSessionValue,
    pub(crate) master_secret: Zeroizing<[u8; 48]>,
    pub(crate) extended_ms: bool,
}

impl Tls12ServerSessionValue {
    pub(crate) fn new(
        common: CommonServerSessionValue,
        master_secret: &[u8; 48],
        extended_ms: bool,
    ) -> Self {
        Self {
            common,
            master_secret: Zeroizing::new(*master_secret),
            extended_ms,
        }
    }
}

impl Codec<'_> for Tls12ServerSessionValue {
    fn encode(&self, bytes: &mut Vec<u8>) {
        self.common.encode(bytes);
        bytes.extend_from_slice(self.master_secret.as_ref());
        (self.extended_ms as u8).encode(bytes);
    }

    fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> {
        Ok(Self {
            common: CommonServerSessionValue::read(r)?,
            master_secret: Zeroizing::new(
                match r
                    .take(48)
                    .and_then(|slice| slice.try_into().ok())
                {
                    Some(array) => array,
                    None => return Err(InvalidMessage::MessageTooShort),
                },
            ),
            extended_ms: matches!(u8::read(r)?, 1),
        })
    }
}

impl From<Tls12ServerSessionValue> for ServerSessionValue {
    fn from(value: Tls12ServerSessionValue) -> Self {
        Self::Tls12(value)
    }
}

#[derive(Debug)]
pub struct Tls13ServerSessionValue {
    pub(crate) common: CommonServerSessionValue,
    pub(crate) secret: Zeroizing<SizedPayload<'static, u8>>,
    pub(crate) age_obfuscation_offset: u32,

    // not encoded vv
    freshness: Option<bool>,
}

impl Tls13ServerSessionValue {
    pub(crate) fn new(
        common: CommonServerSessionValue,
        secret: &[u8],
        age_obfuscation_offset: u32,
    ) -> Self {
        Self {
            common,
            secret: Zeroizing::new(secret.to_vec().into()),
            age_obfuscation_offset,
            freshness: None,
        }
    }

    pub(crate) fn set_freshness(
        mut self,
        obfuscated_client_age_ms: u32,
        time_now: UnixTime,
    ) -> Self {
        let client_age_ms = obfuscated_client_age_ms.wrapping_sub(self.age_obfuscation_offset);
        let server_age_ms = (time_now
            .as_secs()
            .saturating_sub(self.common.creation_time_sec) as u32)
            .saturating_mul(1000);

        let age_difference = server_age_ms.abs_diff(client_age_ms);

        self.freshness = Some(age_difference <= MAX_FRESHNESS_SKEW_MS);
        self
    }

    pub(crate) fn is_fresh(&self) -> bool {
        self.freshness.unwrap_or_default()
    }
}

impl Codec<'_> for Tls13ServerSessionValue {
    fn encode(&self, bytes: &mut Vec<u8>) {
        self.common.encode(bytes);
        self.secret.encode(bytes);
        self.age_obfuscation_offset
            .encode(bytes);
    }

    fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> {
        Ok(Self {
            common: CommonServerSessionValue::read(r)?,
            secret: Zeroizing::new(SizedPayload::read(r)?.into_owned()),
            age_obfuscation_offset: u32::read(r)?,
            freshness: None,
        })
    }
}

impl From<Tls13ServerSessionValue> for ServerSessionValue {
    fn from(value: Tls13ServerSessionValue) -> Self {
        Self::Tls13(value)
    }
}

#[derive(Debug)]
pub(crate) struct CommonServerSessionValue {
    pub(crate) creation_time_sec: u64,
    pub(crate) sni: Option<DnsName<'static>>,
    pub(crate) cipher_suite: CipherSuite,
    pub(crate) peer_identity: Option<Identity<'static>>,
    pub(crate) alpn: Option<ApplicationProtocol<'static>>,
    pub(crate) application_data: SizedPayload<'static, u16, MaybeEmpty>,
}

impl CommonServerSessionValue {
    pub(crate) fn new(
        sni: Option<&DnsName<'_>>,
        cipher_suite: CipherSuite,
        peer_identity: Option<Identity<'static>>,
        alpn: Option<ApplicationProtocol<'static>>,
        application_data: Vec<u8>,
        creation_time: UnixTime,
    ) -> Self {
        Self {
            creation_time_sec: creation_time.as_secs(),
            sni: sni.map(|s| s.to_owned()),
            cipher_suite,
            peer_identity,
            alpn,
            application_data: SizedPayload::from(Payload::new(application_data)),
        }
    }

    pub(crate) fn can_resume(&self, suite: CipherSuite, sni: Option<&DnsName<'_>>) -> bool {
        // The RFCs underspecify what happens if we try to resume to
        // an unoffered/varying suite.  We merely don't resume in weird cases.
        //
        // RFC 6066 says "A server that implements this extension MUST NOT accept
        // the request to resume the session if the server_name extension contains
        // a different name. Instead, it proceeds with a full handshake to
        // establish a new session."
        //
        // RFC 8446: "The server MUST ensure that it selects
        // a compatible PSK (if any) and cipher suite."
        self.cipher_suite == suite && self.sni.as_ref() == sni
    }
}

impl Codec<'_> for CommonServerSessionValue {
    fn encode(&self, bytes: &mut Vec<u8>) {
        self.creation_time_sec.encode(bytes);
        if let Some(sni) = &self.sni {
            1u8.encode(bytes);
            let sni_bytes: &str = sni.as_ref();
            SizedPayload::<u8, MaybeEmpty>::from(Payload::Borrowed(sni_bytes.as_bytes()))
                .encode(bytes);
        } else {
            0u8.encode(bytes);
        }
        self.cipher_suite.encode(bytes);
        if let Some(identity) = &self.peer_identity {
            1u8.encode(bytes);
            identity.encode(bytes);
        } else {
            0u8.encode(bytes);
        }
        if let Some(alpn) = &self.alpn {
            1u8.encode(bytes);
            alpn.encode(bytes);
        } else {
            0u8.encode(bytes);
        }
        self.application_data.encode(bytes);
    }

    fn read(r: &mut Reader<'_>) -> Result<Self, InvalidMessage> {
        let creation_time_sec = u64::read(r)?;
        let sni = match u8::read(r)? {
            1 => {
                let dns_name = SizedPayload::<u8, MaybeEmpty>::read(r)?;
                let dns_name = match DnsName::try_from(dns_name.bytes()) {
                    Ok(dns_name) => dns_name.to_owned(),
                    Err(_) => return Err(InvalidMessage::InvalidServerName),
                };

                Some(dns_name)
            }
            _ => None,
        };

        Ok(Self {
            creation_time_sec,
            sni,
            cipher_suite: CipherSuite::read(r)?,
            peer_identity: match u8::read(r)? {
                1 => Some(Identity::read(r)?.into_owned()),
                _ => None,
            },
            alpn: match u8::read(r)? {
                1 => Some(ApplicationProtocol::read(r)?.to_owned()),
                _ => None,
            },
            application_data: SizedPayload::read(r)?.into_owned(),
        })
    }
}

#[cfg(test)]
mod tests {
    use pki_types::CertificateDer;

    use super::*;
    use crate::crypto::CertificateIdentity;

    #[cfg(feature = "std")] // for UnixTime::now
    #[test]
    fn serversessionvalue_is_debug() {
        use std::{println, vec};
        let ssv = ServerSessionValue::Tls13(Tls13ServerSessionValue::new(
            CommonServerSessionValue::new(
                None,
                CipherSuite::TLS13_AES_128_GCM_SHA256,
                None,
                None,
                vec![4, 5, 6],
                UnixTime::now(),
            ),
            &[1, 2, 3],
            0x12345678,
        ));
        println!("{ssv:?}");
        println!("{:#04x?}", ssv.get_encoding());
    }

    #[test]
    fn serversessionvalue_no_sni() {
        let bytes = [
            0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x69, 0x7a, 0x4a, 0xdf, 0x00, 0x13, 0x01, 0x00,
            0x00, 0x00, 0x03, 0x04, 0x05, 0x06, 0x03, 0x01, 0x02, 0x03, 0x12, 0x34, 0x56, 0x78,
        ];
        let mut rd = Reader::init(&bytes);
        let ssv = ServerSessionValue::read(&mut rd).unwrap();
        assert_eq!(ssv.get_encoding(), bytes);
    }

    #[test]
    fn serversessionvalue_with_cert() {
        std::eprintln!(
            "{:#04x?}",
            ServerSessionValue::Tls13(Tls13ServerSessionValue::new(
                CommonServerSessionValue::new(
                    None,
                    CipherSuite::TLS13_AES_128_GCM_SHA256,
                    Some(Identity::X509(CertificateIdentity {
                        end_entity: CertificateDer::from(&[10, 11, 12][..]),
                        intermediates: alloc::vec![],
                    })),
                    None,
                    alloc::vec![4, 5, 6],
                    UnixTime::now(),
                ),
                &[1, 2, 3],
                0x12345678,
            ))
            .get_encoding()
        );

        let bytes = [
            0x03, 0x04, 0x00, 0x00, 0x00, 0x00, 0x69, 0x7a, 0x4b, 0x06, 0x00, 0x13, 0x01, 0x01,
            0x00, 0x00, 0x00, 0x03, 0x0a, 0x0b, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x04,
            0x05, 0x06, 0x03, 0x01, 0x02, 0x03, 0x12, 0x34, 0x56, 0x78,
        ];
        let mut rd = Reader::init(&bytes);
        let ssv = ServerSessionValue::read(&mut rd).unwrap();
        assert_eq!(ssv.get_encoding(), bytes);
    }
}