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
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::fmt::{Debug, Formatter};
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;
use rustls::crypto::{GetRandomFailed, TicketProducer};
use rustls::error::Error;
use verified_garbage::aead::aes_gcm::AesGcm;
use zeroize::Zeroizing;
use crate::aead::TAG_LEN;
const NONCE_LEN: usize = 12;
/// A [`TicketProducer`] that encrypts tickets with AES-256-GCM.
///
/// It does not enforce any lifetime constraint.
pub(super) struct AeadTicketer {
key: AesGcm,
key_name: [u8; 16],
/// Tracks the largest ciphertext produced by `encrypt`, and
/// uses it to early-reject `decrypt` queries that are too long.
///
/// Accepting excessively long ciphertexts means a "Partitioning
/// Oracle Attack" (see <https://eprint.iacr.org/2020/1491.pdf>)
/// can be more efficient, though also note that these are thought
/// to be cryptographically hard if the key is full-entropy (as it
/// is here).
maximum_ciphertext_len: AtomicUsize,
}
impl AeadTicketer {
#[allow(clippy::new_ret_no_self)]
pub(super) fn new() -> Result<Box<dyn TicketProducer>, Error> {
let mut key = Zeroizing::new([0u8; 32]);
getrandom::fill(&mut *key).map_err(|_| GetRandomFailed)?;
let mut key_name = [0u8; 16];
getrandom::fill(&mut key_name).map_err(|_| GetRandomFailed)?;
Ok(Box::new(Self {
key: AesGcm::new(&*key).unwrap(),
key_name,
maximum_ciphertext_len: AtomicUsize::new(0),
}))
}
}
impl TicketProducer for AeadTicketer {
/// Encrypt `message` and return the ciphertext.
fn encrypt(&self, message: &[u8]) -> Option<Vec<u8>> {
// Random nonce, because a counter is a privacy leak.
let mut nonce = [0u8; NONCE_LEN];
getrandom::fill(&mut nonce).ok()?;
// ciphertext structure is:
// key_name: [u8; 16]
// nonce: [u8; 12]
// message: [u8, _]
// tag: [u8; 16]
let mut ciphertext =
Vec::with_capacity(self.key_name.len() + nonce.len() + message.len() + TAG_LEN);
ciphertext.extend(self.key_name);
ciphertext.extend(nonce);
ciphertext.extend(message);
let tag = self
.key
.encrypt_in_place(
&nonce,
&self.key_name,
&mut ciphertext[self.key_name.len() + NONCE_LEN..],
)
.ok()?;
ciphertext.extend(tag);
self.maximum_ciphertext_len
.fetch_max(ciphertext.len(), Ordering::SeqCst);
Some(ciphertext)
}
/// Decrypt `ciphertext` and recover the original message.
fn decrypt(&self, ciphertext: &[u8]) -> Option<Vec<u8>> {
if ciphertext.len() > self.maximum_ciphertext_len.load(Ordering::SeqCst) {
return None;
}
let (alleged_key_name, ciphertext) = ciphertext.split_at_checked(self.key_name.len())?;
let (nonce, ciphertext) = ciphertext.split_at_checked(NONCE_LEN)?;
let (ciphertext, tag) =
ciphertext.split_at_checked(ciphertext.len().checked_sub(TAG_LEN)?)?;
// checking the key_name is the expected one, *and* then putting it into the
// additionally authenticated data is duplicative. this check quickly rejects
// tickets for a different ticketer (see `TicketRotator`), while including it
// in the AAD ensures it is authenticated independent of that check and that
// any attempted attack on the integrity such as [^1] must happen for each
// `key_label`, not over a population of potential keys. this approach
// is overall similar to [^2].
//
// [^1]: https://eprint.iacr.org/2020/1491.pdf
// [^2]: "Authenticated Encryption with Key Identification", fig 6
// <https://eprint.iacr.org/2022/1680.pdf>
// The key name is not secret: every ticket carries it in the clear.
if self.key_name[..] != *alleged_key_name {
return None;
}
let mut out = Vec::from(ciphertext);
self.key
.decrypt_in_place(nonce, alleged_key_name, &mut out, tag.try_into().ok()?)
.ok()?;
Some(out)
}
fn lifetime(&self) -> Duration {
// this is not used, as this ticketer is only used via a `TicketRotator`
// that is responsible for defining and managing the lifetime of tickets.
Duration::ZERO
}
}
impl Debug for AeadTicketer {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// Note: we deliberately omit the key from the debug output.
f.debug_struct("AeadTicketer").finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use alloc::format;
use core::time::Duration;
use super::AeadTicketer;
/// A ticketer opens the tickets it made, but not one longer than any it
/// made, nor one too short to hold a tag, nor one changed, nor another
/// ticketer's. Its lifetime is its rotator's to set, and its debug form
/// leaves out its key.
#[test]
fn tickets() {
let ticketer = AeadTicketer::new().unwrap();
let ticket = ticketer.encrypt(b"session").unwrap();
assert_eq!(ticketer.decrypt(&ticket).unwrap(), b"session");
assert!(
ticketer
.decrypt(&[ticket.as_slice(), &[0]].concat())
.is_none()
);
assert!(ticketer.decrypt(&ticket[..16 + 12 + 15]).is_none());
let mut changed = ticket.clone();
*changed.last_mut().unwrap() ^= 1;
assert!(ticketer.decrypt(&changed).is_none());
let other = AeadTicketer::new().unwrap();
other.encrypt(&[0; 64]).unwrap();
assert!(other.decrypt(&ticket).is_none());
assert_eq!(ticketer.lifetime(), Duration::ZERO);
assert_eq!(format!("{ticketer:?}"), "AeadTicketer { .. }");
}
}