Debian Codegraph @

third_party/rust/ohttp/src/nss/aead.rs

raw
1 use super::{
2 err::secstatus_to_res,
3 p11::{
4 sys::{
5 self, PK11Context, PK11_AEADOp, PK11_CreateContextBySymKey, PRBool, CKA_DECRYPT,
6 CKA_ENCRYPT, CKA_NSS_MESSAGE, CKG_GENERATE_COUNTER_XOR, CKG_NO_GENERATE, CKM_AES_GCM,
7 CKM_CHACHA20_POLY1305, CK_ATTRIBUTE_TYPE, CK_GENERATOR_FUNCTION, CK_MECHANISM_TYPE,
8 },
9 Item, SymKey,
10 },
11 };
12 use crate::{
13 err::{Error, Res},
14 hpke::Aead as AeadId,
15 };
16 use log::trace;
17 use std::{
18 convert::{TryFrom, TryInto},
19 mem,
20 os::raw::c_int,
21 };
22
23 /// All the nonces are the same length. Exploit that.
24 pub const NONCE_LEN: usize = 12;
25 /// The portion of the nonce that is a counter.
26 const COUNTER_LEN: usize = mem::size_of::<SequenceNumber>();
27 /// The NSS API insists on us identifying the tag separately, which is awful.
28 /// All of the AEAD functions here have a tag of this length, so use a fixed offset.
29 const TAG_LEN: usize = 16;
30
31 pub type SequenceNumber = u64;
32
33 /// All the lengths used by `PK11_AEADOp` are signed. This converts to that.
34 fn c_int_len<T>(l: T) -> c_int
35 where
36 T: TryInto<c_int>,
37 T::Error: std::error::Error,
38 {
39 l.try_into().unwrap()
40 }
41
42 unsafe fn destroy_aead_context(ctx: *mut PK11Context) {
43 sys::PK11_DestroyContext(ctx, PRBool::from(true));
44 }
45 scoped_ptr!(Context, PK11Context, destroy_aead_context);
46
47 unsafe impl Send for Context {}
48
49 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
50 pub enum Mode {
51 Encrypt,
52 Decrypt,
53 }
54
55 impl Mode {
56 fn p11mode(self) -> CK_ATTRIBUTE_TYPE {
57 CK_ATTRIBUTE_TYPE::from(
58 CKA_NSS_MESSAGE
59 | match self {
60 Self::Encrypt => CKA_ENCRYPT,
61 Self::Decrypt => CKA_DECRYPT,
62 },
63 )
64 }
65 }
66
67 /// This is an AEAD instance that uses the
68 pub struct Aead {
69 mode: Mode,
70 ctx: Context,
71 nonce_base: [u8; NONCE_LEN],
72 }
73
74 impl Aead {
75 fn mech(algorithm: AeadId) -> CK_MECHANISM_TYPE {
76 CK_MECHANISM_TYPE::from(match algorithm {
77 // The key size determines which AES variant is used.
78 AeadId::Aes128Gcm | AeadId::Aes256Gcm => CKM_AES_GCM,
79 AeadId::ChaCha20Poly1305 => CKM_CHACHA20_POLY1305,
80 })
81 }
82
83 #[cfg(test)]
84 pub fn import_key(algorithm: AeadId, key: &[u8]) -> Res<SymKey> {
85 let slot = super::p11::Slot::internal()?;
86 let ptr = unsafe {
87 sys::PK11_ImportSymKey(
88 *slot,
89 Self::mech(algorithm),
90 sys::PK11Origin::PK11_OriginUnwrap,
91 sys::CK_ATTRIBUTE_TYPE::from(sys::CKA_ENCRYPT | sys::CKA_DECRYPT),
92 &mut super::p11::Item::wrap(key),
93 std::ptr::null_mut(),
94 )
95 };
96 SymKey::from_ptr(ptr)
97 }
98
99 pub fn new(
100 mode: Mode,
101 algorithm: AeadId,
102 key: &SymKey,
103 nonce_base: [u8; NONCE_LEN],
104 ) -> Res<Self> {
105 trace!(
106 "New AEAD: key={} nonce_base={}",
107 hex::encode(key.key_data()?),
108 hex::encode(nonce_base)
109 );
110
111 let ptr = unsafe {
112 PK11_CreateContextBySymKey(
113 Self::mech(algorithm),
114 mode.p11mode(),
115 **key,
116 &Item::wrap(&nonce_base[..]),
117 )
118 };
119 Ok(Self {
120 mode,
121 ctx: Context::from_ptr(ptr)?,
122 nonce_base,
123 })
124 }
125
126 pub fn seal(&mut self, aad: &[u8], pt: &[u8]) -> Res<Vec<u8>> {
127 assert_eq!(self.mode, Mode::Encrypt);
128 // A copy for the nonce generator to write into. But we don't use the value.
129 let mut nonce = self.nonce_base;
130 // Ciphertext with enough space for the tag.
131 // Even though we give the operation a separate buffer for the tag,
132 // reserve the capacity on allocation.
133 let mut ct = vec![0; pt.len() + TAG_LEN];
134 let mut ct_len: c_int = 0;
135 let mut tag = vec![0; TAG_LEN];
136 secstatus_to_res(unsafe {
137 PK11_AEADOp(
138 *self.ctx,
139 CK_GENERATOR_FUNCTION::from(CKG_GENERATE_COUNTER_XOR),
140 c_int_len(NONCE_LEN - COUNTER_LEN), // Fixed portion of the nonce.
141 nonce.as_mut_ptr(),
142 c_int_len(nonce.len()),
143 aad.as_ptr(),
144 c_int_len(aad.len()),
145 ct.as_mut_ptr(),
146 &mut ct_len,
147 c_int_len(ct.len()), // signed :(
148 tag.as_mut_ptr(),
149 c_int_len(tag.len()),
150 pt.as_ptr(),
151 c_int_len(pt.len()),
152 )
153 })?;
154 ct.truncate(usize::try_from(ct_len).unwrap());
155 debug_assert_eq!(ct.len(), pt.len());
156 ct.append(&mut tag);
157 Ok(ct)
158 }
159
160 pub fn open(&mut self, aad: &[u8], seq: SequenceNumber, ct: &[u8]) -> Res<Vec<u8>> {
161 assert_eq!(self.mode, Mode::Decrypt);
162 let mut nonce = self.nonce_base;
163 for (i, n) in nonce.iter_mut().rev().take(COUNTER_LEN).enumerate() {
164 *n ^= u8::try_from((seq >> (8 * i)) & 0xff).unwrap();
165 }
166 let mut pt = vec![0; ct.len()]; // NSS needs more space than it uses for plaintext.
167 let mut pt_len: c_int = 0;
168 let pt_expected = ct.len().checked_sub(TAG_LEN).ok_or(Error::Truncated)?;
169 secstatus_to_res(unsafe {
170 PK11_AEADOp(
171 *self.ctx,
172 CK_GENERATOR_FUNCTION::from(CKG_NO_GENERATE),
173 c_int_len(NONCE_LEN - COUNTER_LEN), // Fixed portion of the nonce.
174 nonce.as_mut_ptr(),
175 c_int_len(nonce.len()),
176 aad.as_ptr(),
177 c_int_len(aad.len()),
178 pt.as_mut_ptr(),
179 &mut pt_len,
180 c_int_len(pt.len()), // signed :(
181 ct.as_ptr().add(pt_expected) as *mut _, // const cast :(
182 c_int_len(TAG_LEN),
183 ct.as_ptr(),
184 c_int_len(pt_expected),
185 )
186 })?;
187 let len = usize::try_from(pt_len).unwrap();
188 debug_assert_eq!(len, pt_expected);
189 pt.truncate(len);
190 Ok(pt)
191 }
192 }
193
194 #[cfg(test)]
195 mod test {
196 use super::{
197 super::{super::hpke::Aead as AeadId, init},
198 Aead, Mode, SequenceNumber, NONCE_LEN,
199 };
200
201 /// Check that the first invocation of encryption matches expected values.
202 /// Also check decryption of the same.
203 fn check0(
204 algorithm: AeadId,
205 key: &[u8],
206 nonce: &[u8; NONCE_LEN],
207 aad: &[u8],
208 pt: &[u8],
209 ct: &[u8],
210 ) {
211 init();
212 let k = Aead::import_key(algorithm, key).unwrap();
213
214 let mut enc = Aead::new(Mode::Encrypt, algorithm, &k, *nonce).unwrap();
215 let ciphertext = enc.seal(aad, pt).unwrap();
216 assert_eq!(&ciphertext[..], ct);
217
218 let mut dec = Aead::new(Mode::Decrypt, algorithm, &k, *nonce).unwrap();
219 let plaintext = dec.open(aad, 0, ct).unwrap();
220 assert_eq!(&plaintext[..], pt);
221 }
222
223 fn decrypt(
224 algorithm: AeadId,
225 key: &[u8],
226 nonce: &[u8; NONCE_LEN],
227 seq: SequenceNumber,
228 aad: &[u8],
229 pt: &[u8],
230 ct: &[u8],
231 ) {
232 let k = Aead::import_key(algorithm, key).unwrap();
233 let mut dec = Aead::new(Mode::Decrypt, algorithm, &k, *nonce).unwrap();
234 let plaintext = dec.open(aad, seq, ct).unwrap();
235 assert_eq!(&plaintext[..], pt);
236 }
237
238 /// This tests the AEAD in QUIC in combination with the HKDF code.
239 /// This is an AEAD-only example.
240 #[test]
241 fn quic_retry() {
242 const KEY: &[u8] = &[
243 0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68,
244 0xc8, 0x4e,
245 ];
246 const NONCE: &[u8; NONCE_LEN] = &[
247 0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb,
248 ];
249 const AAD: &[u8] = &[
250 0x08, 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08, 0xff, 0x00, 0x00, 0x00, 0x01,
251 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62, 0xb5, 0x74, 0x6f, 0x6b, 0x65,
252 0x6e,
253 ];
254 const CT: &[u8] = &[
255 0x04, 0xa2, 0x65, 0xba, 0x2e, 0xff, 0x4d, 0x82, 0x90, 0x58, 0xfb, 0x3f, 0x0f, 0x24,
256 0x96, 0xba,
257 ];
258 check0(AeadId::Aes128Gcm, KEY, NONCE, AAD, &[], CT);
259 }
260
261 #[test]
262 fn quic_server_initial() {
263 const ALG: AeadId = AeadId::Aes128Gcm;
264 const KEY: &[u8] = &[
265 0xcf, 0x3a, 0x53, 0x31, 0x65, 0x3c, 0x36, 0x4c, 0x88, 0xf0, 0xf3, 0x79, 0xb6, 0x06,
266 0x7e, 0x37,
267 ];
268 const NONCE_BASE: &[u8; NONCE_LEN] = &[
269 0x0a, 0xc1, 0x49, 0x3c, 0xa1, 0x90, 0x58, 0x53, 0xb0, 0xbb, 0xa0, 0x3e,
270 ];
271 // Note that this integrates the sequence number of 1 from the example,
272 // otherwise we can't use a sequence number of 0 to encrypt.
273 const NONCE: &[u8; NONCE_LEN] = &[
274 0x0a, 0xc1, 0x49, 0x3c, 0xa1, 0x90, 0x58, 0x53, 0xb0, 0xbb, 0xa0, 0x3f,
275 ];
276 const AAD: &[u8] = &[
277 0xc1, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0xf0, 0x67, 0xa5, 0x50, 0x2a, 0x42, 0x62,
278 0xb5, 0x00, 0x40, 0x75, 0x00, 0x01,
279 ];
280 const PT: &[u8] = &[
281 0x02, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x40, 0x5a, 0x02, 0x00, 0x00, 0x56, 0x03,
282 0x03, 0xee, 0xfc, 0xe7, 0xf7, 0xb3, 0x7b, 0xa1, 0xd1, 0x63, 0x2e, 0x96, 0x67, 0x78,
283 0x25, 0xdd, 0xf7, 0x39, 0x88, 0xcf, 0xc7, 0x98, 0x25, 0xdf, 0x56, 0x6d, 0xc5, 0x43,
284 0x0b, 0x9a, 0x04, 0x5a, 0x12, 0x00, 0x13, 0x01, 0x00, 0x00, 0x2e, 0x00, 0x33, 0x00,
285 0x24, 0x00, 0x1d, 0x00, 0x20, 0x9d, 0x3c, 0x94, 0x0d, 0x89, 0x69, 0x0b, 0x84, 0xd0,
286 0x8a, 0x60, 0x99, 0x3c, 0x14, 0x4e, 0xca, 0x68, 0x4d, 0x10, 0x81, 0x28, 0x7c, 0x83,
287 0x4d, 0x53, 0x11, 0xbc, 0xf3, 0x2b, 0xb9, 0xda, 0x1a, 0x00, 0x2b, 0x00, 0x02, 0x03,
288 0x04,
289 ];
290 const CT: &[u8] = &[
291 0x5a, 0x48, 0x2c, 0xd0, 0x99, 0x1c, 0xd2, 0x5b, 0x0a, 0xac, 0x40, 0x6a, 0x58, 0x16,
292 0xb6, 0x39, 0x41, 0x00, 0xf3, 0x7a, 0x1c, 0x69, 0x79, 0x75, 0x54, 0x78, 0x0b, 0xb3,
293 0x8c, 0xc5, 0xa9, 0x9f, 0x5e, 0xde, 0x4c, 0xf7, 0x3c, 0x3e, 0xc2, 0x49, 0x3a, 0x18,
294 0x39, 0xb3, 0xdb, 0xcb, 0xa3, 0xf6, 0xea, 0x46, 0xc5, 0xb7, 0x68, 0x4d, 0xf3, 0x54,
295 0x8e, 0x7d, 0xde, 0xb9, 0xc3, 0xbf, 0x9c, 0x73, 0xcc, 0x3f, 0x3b, 0xde, 0xd7, 0x4b,
296 0x56, 0x2b, 0xfb, 0x19, 0xfb, 0x84, 0x02, 0x2f, 0x8e, 0xf4, 0xcd, 0xd9, 0x37, 0x95,
297 0xd7, 0x7d, 0x06, 0xed, 0xbb, 0x7a, 0xaf, 0x2f, 0x58, 0x89, 0x18, 0x50, 0xab, 0xbd,
298 0xca, 0x3d, 0x20, 0x39, 0x8c, 0x27, 0x64, 0x56, 0xcb, 0xc4, 0x21, 0x58, 0x40, 0x7d,
299 0xd0, 0x74, 0xee,
300 ];
301 check0(ALG, KEY, NONCE, AAD, PT, CT);
302 decrypt(ALG, KEY, NONCE_BASE, 1, AAD, PT, CT);
303 }
304
305 #[test]
306 fn quic_chacha() {
307 const ALG: AeadId = AeadId::ChaCha20Poly1305;
308 const KEY: &[u8] = &[
309 0xc6, 0xd9, 0x8f, 0xf3, 0x44, 0x1c, 0x3f, 0xe1, 0xb2, 0x18, 0x20, 0x94, 0xf6, 0x9c,
310 0xaa, 0x2e, 0xd4, 0xb7, 0x16, 0xb6, 0x54, 0x88, 0x96, 0x0a, 0x7a, 0x98, 0x49, 0x79,
311 0xfb, 0x23, 0xe1, 0xc8,
312 ];
313 const NONCE_BASE: &[u8; NONCE_LEN] = &[
314 0xe0, 0x45, 0x9b, 0x34, 0x74, 0xbd, 0xd0, 0xe4, 0x4a, 0x41, 0xc1, 0x44,
315 ];
316 // Note that this integrates the sequence number of 654360564 from the example,
317 // otherwise we can't use a sequence number of 0 to encrypt.
318 const NONCE: &[u8; NONCE_LEN] = &[
319 0xe0, 0x45, 0x9b, 0x34, 0x74, 0xbd, 0xd0, 0xe4, 0x6d, 0x41, 0x7e, 0xb0,
320 ];
321 const AAD: &[u8] = &[0x42, 0x00, 0xbf, 0xf4];
322 const PT: &[u8] = &[0x01];
323 const CT: &[u8] = &[
324 0x65, 0x5e, 0x5c, 0xd5, 0x5c, 0x41, 0xf6, 0x90, 0x80, 0x57, 0x5d, 0x79, 0x99, 0xc2,
325 0x5a, 0x5b, 0xfb,
326 ];
327 check0(ALG, KEY, NONCE, AAD, PT, CT);
328 // Now use the real nonce and sequence number from the example.
329 decrypt(ALG, KEY, NONCE_BASE, 654_360_564, AAD, PT, CT);
330 }
331 }