tlspuffin/tls/rustls/
record_layer.rs

1use crate::tls::rustls::cipher::{MessageDecrypter, MessageEncrypter};
2use crate::tls::rustls::error::Error;
3use crate::tls::rustls::msgs::message::{BorrowedPlainMessage, OpaqueMessage, PlainMessage};
4
5static SEQ_SOFT_LIMIT: u64 = 0xffff_ffff_ffff_0000u64;
6static SEQ_HARD_LIMIT: u64 = 0xffff_ffff_ffff_fffeu64;
7
8#[derive(PartialEq)]
9enum DirectionState {
10    /// No keying material.
11    Invalid,
12
13    /// Keying material present, but not yet in use.
14    Prepared,
15
16    /// Keying material in use.
17    Active,
18}
19
20pub struct RecordLayer {
21    message_encrypter: Box<dyn MessageEncrypter>,
22    message_decrypter: Box<dyn MessageDecrypter>,
23    write_seq: u64,
24    read_seq: u64,
25    encrypt_state: DirectionState,
26    decrypt_state: DirectionState,
27
28    // Message encrypted with other keys may be encountered, so failures
29    // should be swallowed by the caller.  This struct tracks the amount
30    // of message size this is allowed for.
31    trial_decryption_len: Option<usize>,
32}
33
34impl RecordLayer {
35    pub fn new() -> Self {
36        Self {
37            message_encrypter: <dyn MessageEncrypter>::invalid(),
38            message_decrypter: <dyn MessageDecrypter>::invalid(),
39            write_seq: 0,
40            read_seq: 0,
41            encrypt_state: DirectionState::Invalid,
42            decrypt_state: DirectionState::Invalid,
43            trial_decryption_len: None,
44        }
45    }
46
47    pub fn is_encrypting(&self) -> bool {
48        self.encrypt_state == DirectionState::Active
49    }
50
51    pub fn is_decrypting(&self) -> bool {
52        self.decrypt_state == DirectionState::Active
53    }
54
55    pub fn doing_trial_decryption(&mut self, requested: usize) -> bool {
56        match self
57            .trial_decryption_len
58            .and_then(|value| value.checked_sub(requested))
59        {
60            Some(remaining) => {
61                self.trial_decryption_len = Some(remaining);
62                true
63            }
64            _ => false,
65        }
66    }
67
68    /// Prepare to use the given `MessageEncrypter` for future message encryption.
69    /// It is not used until you call `start_encrypting`.
70    pub fn prepare_message_encrypter(&mut self, cipher: Box<dyn MessageEncrypter>) {
71        self.message_encrypter = cipher;
72        self.write_seq = 0;
73        self.encrypt_state = DirectionState::Prepared;
74    }
75
76    /// Prepare to use the given `MessageDecrypter` for future message decryption.
77    /// It is not used until you call `start_decrypting`.
78    pub fn prepare_message_decrypter(&mut self, cipher: Box<dyn MessageDecrypter>) {
79        self.message_decrypter = cipher;
80        self.read_seq = 0;
81        self.decrypt_state = DirectionState::Prepared;
82    }
83
84    /// Start using the `MessageEncrypter` previously provided to the previous
85    /// call to `prepare_message_encrypter`.
86    pub fn start_encrypting(&mut self) {
87        debug_assert!(self.encrypt_state == DirectionState::Prepared);
88        self.encrypt_state = DirectionState::Active;
89    }
90
91    /// Start using the `MessageDecrypter` previously provided to the previous
92    /// call to `prepare_message_decrypter`.
93    pub fn start_decrypting(&mut self) {
94        debug_assert!(self.decrypt_state == DirectionState::Prepared);
95        self.decrypt_state = DirectionState::Active;
96    }
97
98    /// Set and start using the given `MessageEncrypter` for future outgoing
99    /// message encryption.
100    pub fn set_message_encrypter(&mut self, cipher: Box<dyn MessageEncrypter>) {
101        self.prepare_message_encrypter(cipher);
102        self.start_encrypting();
103    }
104
105    /// Set and start using the given `MessageDecrypter` for future incoming
106    /// message decryption.
107    pub fn set_message_decrypter(&mut self, cipher: Box<dyn MessageDecrypter>) {
108        self.prepare_message_decrypter(cipher);
109        self.start_decrypting();
110        self.trial_decryption_len = None;
111    }
112
113    /// Set and start using the given `MessageDecrypter` for future incoming
114    /// message decryption, and enable "trial decryption" mode for when TLS1.3
115    /// 0-RTT is attempted but rejected by the server.
116    pub fn set_message_decrypter_with_trial_decryption(
117        &mut self,
118        cipher: Box<dyn MessageDecrypter>,
119        max_length: usize,
120    ) {
121        self.prepare_message_decrypter(cipher);
122        self.start_decrypting();
123        self.trial_decryption_len = Some(max_length);
124    }
125
126    pub fn finish_trial_decryption(&mut self) {
127        self.trial_decryption_len = None;
128    }
129
130    /// Return true if the peer appears to getting close to encrypting
131    /// too many messages with this key.
132    ///
133    /// Perhaps if we send an alert well before their counter wraps, a
134    /// buggy peer won't make a terrible mistake here?
135    ///
136    /// Note that there's no reason to refuse to decrypt: the security
137    /// failure has already happened.
138    pub fn wants_close_before_decrypt(&self) -> bool {
139        self.read_seq == SEQ_SOFT_LIMIT
140    }
141
142    /// Return true if we are getting close to encrypting too many
143    /// messages with our encryption key.
144    pub fn wants_close_before_encrypt(&self) -> bool {
145        self.write_seq == SEQ_SOFT_LIMIT
146    }
147
148    /// Return true if we outright refuse to do anything with the
149    /// encryption key.
150    pub fn encrypt_exhausted(&self) -> bool {
151        self.write_seq >= SEQ_HARD_LIMIT
152    }
153
154    /// Decrypt a TLS message.
155    ///
156    /// `encr` is a decoded message allegedly received from the peer.
157    /// If it can be decrypted, its decryption is returned.  Otherwise,
158    /// an error is returned.
159    pub fn decrypt_incoming(&mut self, encr: OpaqueMessage) -> Result<PlainMessage, Error> {
160        debug_assert!(self.is_decrypting());
161        let seq = self.read_seq;
162        let msg = self.message_decrypter.decrypt(encr, seq)?;
163        self.read_seq += 1;
164        Ok(msg)
165    }
166
167    /// Encrypt a TLS message.
168    ///
169    /// `plain` is a TLS message we'd like to send.  This function
170    /// panics if the requisite keying material hasn't been established yet.
171    pub fn encrypt_outgoing(&mut self, plain: BorrowedPlainMessage) -> OpaqueMessage {
172        debug_assert!(self.encrypt_state == DirectionState::Active);
173        assert!(!self.encrypt_exhausted());
174        let seq = self.write_seq;
175        self.write_seq += 1;
176        self.message_encrypter.encrypt(plain, seq).unwrap()
177    }
178}
179
180impl Default for RecordLayer {
181    fn default() -> Self {
182        Self::new()
183    }
184}