tlspuffin/tls/rustls/
ticketer.rs

1use std::sync::{Arc, Mutex, MutexGuard};
2use std::{mem, time};
3
4use ring::aead;
5
6use crate::tls::rustls::error::Error;
7use crate::tls::rustls::rand;
8use crate::tls::rustls::server::server_conn::ProducesTickets;
9
10/// The timebase for expiring and rolling tickets and ticketing
11/// keys.  This is UNIX wall time in seconds.
12///
13/// This is guaranteed to be on or after the UNIX epoch.
14#[derive(Clone, Copy, Debug)]
15pub struct TimeBase(time::Duration);
16
17impl TimeBase {
18    #[inline]
19    pub fn now() -> Result<Self, time::SystemTimeError> {
20        Ok(Self(
21            time::SystemTime::now().duration_since(time::UNIX_EPOCH)?,
22        ))
23    }
24
25    #[inline]
26    pub fn as_secs(&self) -> u64 {
27        self.0.as_secs()
28    }
29}
30
31/// This is a `ProducesTickets` implementation which uses
32/// any *ring* `aead::Algorithm` to encrypt and authentication
33/// the ticket payload.  It does not enforce any lifetime
34/// constraint.
35struct AeadTicketer {
36    alg: &'static aead::Algorithm,
37    key: aead::LessSafeKey,
38    lifetime: u32,
39}
40
41impl AeadTicketer {
42    /// Make a ticketer with recommended configuration and a random key.
43    fn new() -> Result<Self, rand::GetRandomFailed> {
44        let mut key = [0u8; 32];
45        rand::fill_random(&mut key)?;
46
47        let alg = &aead::CHACHA20_POLY1305;
48        let key = aead::UnboundKey::new(alg, &key).unwrap();
49
50        Ok(Self {
51            alg,
52            key: aead::LessSafeKey::new(key),
53            lifetime: 60 * 60 * 12,
54        })
55    }
56}
57
58impl ProducesTickets for AeadTicketer {
59    fn enabled(&self) -> bool {
60        true
61    }
62
63    fn lifetime(&self) -> u32 {
64        self.lifetime
65    }
66
67    /// Encrypt `message` and return the ciphertext.
68    fn encrypt(&self, message: &[u8]) -> Option<Vec<u8>> {
69        // Random nonce, because a counter is a privacy leak.
70        let mut nonce_buf = [0u8; 12];
71        rand::fill_random(&mut nonce_buf).ok()?;
72        let nonce = ring::aead::Nonce::assume_unique_for_key(nonce_buf);
73        let aad = ring::aead::Aad::empty();
74
75        let mut ciphertext =
76            Vec::with_capacity(nonce_buf.len() + message.len() + self.key.algorithm().tag_len());
77        ciphertext.extend(&nonce_buf);
78        ciphertext.extend(message);
79        self.key
80            .seal_in_place_separate_tag(nonce, aad, &mut ciphertext[nonce_buf.len()..])
81            .map(|tag| {
82                ciphertext.extend(tag.as_ref());
83                ciphertext
84            })
85            .ok()
86    }
87
88    /// Decrypt `ciphertext` and recover the original message.
89    fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> {
90        // Non-panicking `let (nonce, ciphertext) = ciphertext.split_at(...)`.
91        let nonce = ciphertext.get(..self.alg.nonce_len())?;
92        let ciphertext = ciphertext.get(nonce.len()..)?;
93
94        // This won't fail since `nonce` has the required length.
95        let nonce = ring::aead::Nonce::try_assume_unique_for_key(nonce).ok()?;
96
97        let mut out = Vec::from(ciphertext);
98
99        let plain_len = self
100            .key
101            .open_in_place(nonce, aead::Aad::empty(), &mut out)
102            .ok()?
103            .len();
104        out.truncate(plain_len);
105
106        Some(out)
107    }
108}
109
110struct TicketSwitcherState {
111    next: Option<Box<dyn ProducesTickets>>,
112    current: Box<dyn ProducesTickets>,
113    previous: Option<Box<dyn ProducesTickets>>,
114    next_switch_time: u64,
115}
116
117/// A ticketer that has a 'current' sub-ticketer and a single
118/// 'previous' ticketer.  It creates a new ticketer every so
119/// often, demoting the current ticketer.
120struct TicketSwitcher {
121    generator: fn() -> Result<Box<dyn ProducesTickets>, rand::GetRandomFailed>,
122    lifetime: u32,
123    state: Mutex<TicketSwitcherState>,
124}
125
126impl TicketSwitcher {
127    /// `lifetime` is in seconds, and is how long the current ticketer
128    /// is used to generate new tickets.  Tickets are accepted for no
129    /// longer than twice this duration.  `generator` produces a new
130    /// `ProducesTickets` implementation.
131    fn new(
132        lifetime: u32,
133        generator: fn() -> Result<Box<dyn ProducesTickets>, rand::GetRandomFailed>,
134    ) -> Result<Self, Error> {
135        let now = TimeBase::now()?;
136        Ok(Self {
137            generator,
138            lifetime,
139            state: Mutex::new(TicketSwitcherState {
140                next: Some(generator()?),
141                current: generator()?,
142                previous: None,
143                next_switch_time: now.as_secs() + u64::from(lifetime),
144            }),
145        })
146    }
147
148    /// If it's time, demote the `current` ticketer to `previous` (so it
149    /// does no new encryptions but can do decryption) and use next for a
150    /// new `current` ticketer.
151    ///
152    /// Calling this regularly will ensure timely key erasure.  Otherwise,
153    /// key erasure will be delayed until the next encrypt/decrypt call.
154    ///
155    /// For efficiency, this is also responsible for locking the state mutex
156    /// and returning the mutexguard.
157    fn maybe_roll(&self, now: TimeBase) -> Option<MutexGuard<'_, TicketSwitcherState>> {
158        // The code below aims to make switching as efficient as possible
159        // in the common case that the generator never fails. To achieve this
160        // we run the following steps:
161        //  1. If no switch is necessary, just return the mutexguard
162        //  2. Shift over all of the ticketers (so current becomes previous, and next becomes
163        //     current). After this, other threads can start using the new current ticketer.
164        //  3. unlock mutex and generate new ticketer.
165        //  4. Place new ticketer in next and return current
166        //
167        // There are a few things to note here. First, we don't check whether
168        // a new switch might be needed in step 4, even though, due to locking
169        // and entropy collection, significant amounts of time may have passed.
170        // This is to guarantee that the thread doing the switch will eventually
171        // make progress.
172        //
173        // Second, because next may be None, step 2 can fail. In that case
174        // we enter a recovery mode where we generate 2 new ticketers, one for
175        // next and one for the current ticketer. We then take the mutex a
176        // second time and redo the time check to see if a switch is still
177        // necessary.
178        //
179        // This somewhat convoluted approach ensures good availability of the
180        // mutex, by ensuring that the state is usable and the mutex not held
181        // during generation. It also ensures that, so long as the inner
182        // ticketer never generates panics during encryption/decryption,
183        // we are guaranteed to never panic when holding the mutex.
184
185        let now = now.as_secs();
186        let mut are_recovering = false; // Are we recovering from previous failure?
187        {
188            // Scope the mutex so we only take it for as long as needed
189            let mut state = self.state.lock().ok()?;
190
191            // Fast path in case we do not need to switch to the next ticketer yet
192            if now <= state.next_switch_time {
193                return Some(state);
194            }
195
196            // Make the switch, or mark for recovery if not possible
197            if let Some(next) = state.next.take() {
198                state.previous = Some(mem::replace(&mut state.current, next));
199                state.next_switch_time = now + u64::from(self.lifetime);
200            } else {
201                are_recovering = true;
202            }
203        }
204
205        // We always need a next, so generate it now
206        let next = (self.generator)().ok()?;
207        if !are_recovering {
208            // Normal path, generate new next and place it in the state
209            let mut state = self.state.lock().ok()?;
210            state.next = Some(next);
211            Some(state)
212        } else {
213            // Recovering, generate also a new current ticketer, and modify state
214            // as needed. (we need to redo the time check, otherwise this might
215            // result in very rapid switching of ticketers)
216            let new_current = (self.generator)().ok()?;
217            let mut state = self.state.lock().ok()?;
218            state.next = Some(next);
219            if now > state.next_switch_time {
220                state.previous = Some(mem::replace(&mut state.current, new_current));
221                state.next_switch_time = now + u64::from(self.lifetime);
222            }
223            Some(state)
224        }
225    }
226}
227
228impl ProducesTickets for TicketSwitcher {
229    fn lifetime(&self) -> u32 {
230        self.lifetime * 2
231    }
232
233    fn enabled(&self) -> bool {
234        true
235    }
236
237    fn encrypt(&self, message: &[u8]) -> Option<Vec<u8>> {
238        let state = self.maybe_roll(TimeBase::now().ok()?)?;
239
240        state.current.encrypt(message)
241    }
242
243    fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> {
244        let state = self.maybe_roll(TimeBase::now().ok()?)?;
245
246        // Decrypt with the current key; if that fails, try with the previous.
247        state.current.decrypt(ciphertext).or_else(|| {
248            state
249                .previous
250                .as_ref()
251                .and_then(|previous| previous.decrypt(ciphertext))
252        })
253    }
254}
255
256/// A concrete, safe ticket creation mechanism.
257pub struct Ticketer {}
258
259fn generate_inner() -> Result<Box<dyn ProducesTickets>, rand::GetRandomFailed> {
260    Ok(Box::new(AeadTicketer::new()?))
261}
262
263impl Ticketer {
264    /// Make the recommended Ticketer.  This produces tickets
265    /// with a 12 hour life and randomly generated keys.
266    ///
267    /// The encryption mechanism used in Chacha20Poly1305.
268    pub fn new() -> Result<Arc<dyn ProducesTickets>, Error> {
269        Ok(Arc::new(TicketSwitcher::new(6 * 60 * 60, generate_inner)?))
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test_log::test]
278    fn basic_pairwise_test() {
279        let t = Ticketer::new().unwrap();
280        assert!(t.enabled());
281        let cipher = t.encrypt(b"hello world").unwrap();
282        let plain = t.decrypt(&cipher).unwrap();
283        assert_eq!(plain, b"hello world");
284    }
285
286    #[test_log::test]
287    fn ticketswitcher_switching_test() {
288        let t = Arc::new(TicketSwitcher::new(1, generate_inner).unwrap());
289        let now = TimeBase::now().unwrap();
290        let cipher1 = t.encrypt(b"ticket 1").unwrap();
291        assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
292        {
293            // Trigger new ticketer
294            t.maybe_roll(TimeBase(now.0 + std::time::Duration::from_secs(10)));
295        }
296        let cipher2 = t.encrypt(b"ticket 2").unwrap();
297        assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
298        assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
299        {
300            // Trigger new ticketer
301            t.maybe_roll(TimeBase(now.0 + std::time::Duration::from_secs(20)));
302        }
303        let cipher3 = t.encrypt(b"ticket 3").unwrap();
304        assert!(t.decrypt(&cipher1).is_none());
305        assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
306        assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
307    }
308
309    fn fail_generator() -> Result<Box<dyn ProducesTickets>, rand::GetRandomFailed> {
310        Err(rand::GetRandomFailed)
311    }
312
313    #[test_log::test]
314    fn ticketswitcher_recover_test() {
315        let mut t = TicketSwitcher::new(1, generate_inner).unwrap();
316        let now = TimeBase::now().unwrap();
317        let cipher1 = t.encrypt(b"ticket 1").unwrap();
318        assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
319        t.generator = fail_generator;
320        {
321            // Failed new ticketer
322            t.maybe_roll(TimeBase(now.0 + std::time::Duration::from_secs(10)));
323        }
324        t.generator = generate_inner;
325        let cipher2 = t.encrypt(b"ticket 2").unwrap();
326        assert_eq!(t.decrypt(&cipher1).unwrap(), b"ticket 1");
327        assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
328        {
329            // recover
330            t.maybe_roll(TimeBase(now.0 + std::time::Duration::from_secs(20)));
331        }
332        let cipher3 = t.encrypt(b"ticket 3").unwrap();
333        assert!(t.decrypt(&cipher1).is_none());
334        assert_eq!(t.decrypt(&cipher2).unwrap(), b"ticket 2");
335        assert_eq!(t.decrypt(&cipher3).unwrap(), b"ticket 3");
336    }
337}