1use super::aead_ctx::AeadCtx;
5use super::{
6 Algorithm, Nonce, Tag, AES_128_GCM, AES_128_GCM_SIV, AES_192_GCM, AES_256_GCM, AES_256_GCM_SIV,
7 CHACHA20_POLY1305, MAX_KEY_LEN, MAX_TAG_LEN, NONCE_LEN,
8};
9use crate::aws_lc::{
10 EVP_AEAD_CTX_open, EVP_AEAD_CTX_open_gather, EVP_AEAD_CTX_seal, EVP_AEAD_CTX_seal_scatter,
11};
12use crate::error::Unspecified;
13use crate::fips::indicator_check;
14use crate::hkdf;
15use crate::iv::FixedLength;
16use core::fmt::Debug;
17use core::mem::MaybeUninit;
18use core::ops::RangeFrom;
19use core::ptr::null;
20
21const MAX_NONCE_LEN: usize = NONCE_LEN;
23
24const MAX_TAG_NONCE_BUFFER_LEN: usize = MAX_TAG_LEN + MAX_NONCE_LEN;
26
27pub struct UnboundKey {
29 ctx: AeadCtx,
30 algorithm: &'static Algorithm,
31}
32
33#[allow(clippy::missing_fields_in_debug)]
34impl Debug for UnboundKey {
35 fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
36 f.debug_struct("UnboundKey")
37 .field("algorithm", &self.algorithm)
38 .finish()
39 }
40}
41
42impl UnboundKey {
43 pub fn new(algorithm: &'static Algorithm, key_bytes: &[u8]) -> Result<Self, Unspecified> {
47 Ok(Self {
48 ctx: (algorithm.init)(key_bytes, algorithm.tag_len())?,
49 algorithm,
50 })
51 }
52
53 #[inline]
54 pub(crate) fn open_within<'in_out>(
55 &self,
56 nonce: Nonce,
57 aad: &[u8],
58 in_out: &'in_out mut [u8],
59 ciphertext_and_tag: RangeFrom<usize>,
60 ) -> Result<&'in_out mut [u8], Unspecified> {
61 let in_prefix_len = ciphertext_and_tag.start;
62 let ciphertext_and_tag_len = in_out.len().checked_sub(in_prefix_len).ok_or(Unspecified)?;
63 let ciphertext_len = ciphertext_and_tag_len
64 .checked_sub(self.algorithm().tag_len())
65 .ok_or(Unspecified)?;
66 self.check_per_nonce_max_bytes(ciphertext_len)?;
67
68 match self.ctx {
69 AeadCtx::AES_128_GCM_RANDNONCE(_) | AeadCtx::AES_256_GCM_RANDNONCE(_) => {
70 self.open_combined_randnonce(nonce, aad, &mut in_out[in_prefix_len..])
71 }
72 _ => self.open_combined(nonce, aad.as_ref(), &mut in_out[in_prefix_len..]),
73 }?;
74
75 in_out.copy_within(in_prefix_len..in_prefix_len + ciphertext_len, 0);
77
78 Ok(&mut in_out[..ciphertext_len])
80 }
81
82 #[inline]
83 pub(crate) fn open_separate_gather(
84 &self,
85 nonce: &Nonce,
86 aad: &[u8],
87 in_ciphertext: &[u8],
88 in_tag: &[u8],
89 out_plaintext: &mut [u8],
90 ) -> Result<(), Unspecified> {
91 self.open_separate_gather_impl(
92 nonce,
93 aad,
94 in_ciphertext.as_ptr(),
95 in_ciphertext.len(),
96 in_tag,
97 out_plaintext.as_mut_ptr(),
98 out_plaintext.len(),
99 )
100 }
101
102 #[inline]
103 pub(crate) fn open_in_place_separate_tag(
104 &self,
105 nonce: &Nonce,
106 aad: &[u8],
107 in_tag: &[u8],
108 in_out: &mut [u8],
109 ) -> Result<(), Unspecified> {
110 let ptr = in_out.as_mut_ptr();
111 let len = in_out.len();
112 self.open_separate_gather_impl(nonce, aad, ptr.cast_const(), len, in_tag, ptr, len)
113 }
114
115 #[inline]
126 #[allow(clippy::too_many_arguments)]
127 fn open_separate_gather_impl(
128 &self,
129 nonce: &Nonce,
130 aad: &[u8],
131 in_ciphertext: *const u8,
132 in_ciphertext_len: usize,
133 in_tag: &[u8],
134 out_plaintext: *mut u8,
135 out_plaintext_len: usize,
136 ) -> Result<(), Unspecified> {
137 self.check_per_nonce_max_bytes(in_ciphertext_len)?;
138
139 if in_ciphertext_len != out_plaintext_len {
141 return Err(Unspecified);
142 }
143
144 unsafe {
145 let aead_ctx = self.ctx.as_ref();
146 let nonce = nonce.as_ref();
147
148 if 1 != EVP_AEAD_CTX_open_gather(
149 aead_ctx.as_const_ptr(),
150 out_plaintext,
151 nonce.as_ptr(),
152 nonce.len(),
153 in_ciphertext,
154 in_ciphertext_len,
155 in_tag.as_ptr(),
156 in_tag.len(),
157 aad.as_ptr(),
158 aad.len(),
159 ) {
160 return Err(Unspecified);
161 }
162 Ok(())
163 }
164 }
165
166 #[inline]
167 pub(crate) fn seal_in_place_append_tag<'a, InOut>(
168 &self,
169 nonce: Option<Nonce>,
170 aad: &[u8],
171 in_out: &'a mut InOut,
172 ) -> Result<Nonce, Unspecified>
173 where
174 InOut: AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>,
175 {
176 self.check_per_nonce_max_bytes(in_out.as_mut().len())?;
177 match nonce {
178 Some(nonce) => self.seal_combined(nonce, aad, in_out),
179 None => self.seal_combined_randnonce(aad, in_out),
180 }
181 }
182
183 #[inline]
184 pub(crate) fn seal_in_place_separate_tag(
185 &self,
186 nonce: Option<Nonce>,
187 aad: &[u8],
188 in_out: &mut [u8],
189 ) -> Result<(Nonce, Tag), Unspecified> {
190 self.check_per_nonce_max_bytes(in_out.len())?;
191 match nonce {
192 Some(nonce) => self.seal_separate(nonce, aad, in_out),
193 None => self.seal_separate_randnonce(aad, in_out),
194 }
195 }
196
197 #[inline]
198 #[allow(clippy::needless_pass_by_value)]
199 pub(crate) fn seal_out_of_place_scatter(
200 &self,
201 nonce: Nonce,
202 aad: &[u8],
203 in_plaintext: &[u8],
204 out_ciphertext: &mut [u8],
205 extra_in: &[u8],
206 extra_out_and_tag: &mut [u8],
207 ) -> Result<(), Unspecified> {
208 self.check_per_nonce_max_bytes(in_plaintext.len() + extra_in.len())?;
209 if out_ciphertext.len() != in_plaintext.len()
210 || extra_out_and_tag.len() != extra_in.len() + self.algorithm().tag_len()
211 {
212 return Err(Unspecified);
213 }
214
215 let nonce = nonce.as_ref();
216 let mut out_tag_len = 0;
219
220 if 1 != unsafe {
221 EVP_AEAD_CTX_seal_scatter(
222 self.ctx.as_ref().as_const_ptr(),
223 out_ciphertext.as_mut_ptr(),
224 extra_out_and_tag.as_mut_ptr(),
225 &mut out_tag_len,
226 extra_out_and_tag.len(),
227 nonce.as_ptr(),
228 nonce.len(),
229 in_plaintext.as_ptr(),
230 in_plaintext.len(),
231 extra_in.as_ptr(),
232 extra_in.len(),
233 aad.as_ptr(),
234 aad.len(),
235 )
236 } {
237 return Err(Unspecified);
238 }
239 debug_assert_eq!(out_tag_len, extra_out_and_tag.len());
240 Ok(())
241 }
242
243 #[inline]
244 #[allow(clippy::needless_pass_by_value)]
245 pub(crate) fn seal_in_place_separate_scatter(
246 &self,
247 nonce: Nonce,
248 aad: &[u8],
249 in_out: &mut [u8],
250 extra_in: &[u8],
251 extra_out_and_tag: &mut [u8],
252 ) -> Result<(), Unspecified> {
253 self.check_per_nonce_max_bytes(in_out.len())?;
254 {
256 let actual = extra_in.len() + self.algorithm().tag_len();
257 let expected = extra_out_and_tag.len();
258
259 if actual != expected {
260 return Err(Unspecified);
261 }
262 }
263
264 let nonce = nonce.as_ref();
265 let mut out_tag_len = extra_out_and_tag.len();
266
267 if 1 != unsafe {
268 EVP_AEAD_CTX_seal_scatter(
269 self.ctx.as_ref().as_const_ptr(),
270 in_out.as_mut_ptr(),
271 extra_out_and_tag.as_mut_ptr(),
272 &mut out_tag_len,
273 extra_out_and_tag.len(),
274 nonce.as_ptr(),
275 nonce.len(),
276 in_out.as_ptr(),
277 in_out.len(),
278 extra_in.as_ptr(),
279 extra_in.len(),
280 aad.as_ptr(),
281 aad.len(),
282 )
283 } {
284 return Err(Unspecified);
285 }
286 Ok(())
287 }
288
289 #[inline]
291 #[must_use]
292 pub fn algorithm(&self) -> &'static Algorithm {
293 self.algorithm
294 }
295
296 #[inline]
297 pub(crate) fn check_per_nonce_max_bytes(&self, in_out_len: usize) -> Result<(), Unspecified> {
298 if in_out_len as u64 > self.algorithm().max_input_len {
299 return Err(Unspecified);
300 }
301 Ok(())
302 }
303
304 #[inline]
305 #[allow(clippy::needless_pass_by_value)]
306 fn open_combined(
307 &self,
308 nonce: Nonce,
309 aad: &[u8],
310 in_out: &mut [u8],
311 ) -> Result<(), Unspecified> {
312 let nonce = nonce.as_ref();
313
314 debug_assert_eq!(nonce.len(), self.algorithm().nonce_len());
315
316 let plaintext_len = in_out.len() - self.algorithm().tag_len();
317
318 let mut out_len = MaybeUninit::<usize>::uninit();
319 if 1 != indicator_check!(unsafe {
320 EVP_AEAD_CTX_open(
321 self.ctx.as_ref().as_const_ptr(),
322 in_out.as_mut_ptr(),
323 out_len.as_mut_ptr(),
324 plaintext_len,
325 nonce.as_ptr(),
326 nonce.len(),
327 in_out.as_ptr(),
328 plaintext_len + self.algorithm().tag_len(),
329 aad.as_ptr(),
330 aad.len(),
331 )
332 }) {
333 return Err(Unspecified);
334 }
335
336 Ok(())
337 }
338
339 #[inline]
340 #[allow(clippy::needless_pass_by_value)]
341 fn open_combined_randnonce(
342 &self,
343 nonce: Nonce,
344 aad: &[u8],
345 in_out: &mut [u8],
346 ) -> Result<(), Unspecified> {
347 let nonce = nonce.as_ref();
348
349 let alg_nonce_len = self.algorithm().nonce_len();
350 let alg_tag_len = self.algorithm().tag_len();
351
352 debug_assert_eq!(nonce.len(), alg_nonce_len);
353 debug_assert!(alg_tag_len + alg_nonce_len <= MAX_TAG_NONCE_BUFFER_LEN);
354
355 let plaintext_len = in_out.len() - alg_tag_len;
356
357 let mut tag_buffer = [0u8; MAX_TAG_NONCE_BUFFER_LEN];
358
359 tag_buffer[..alg_tag_len]
360 .copy_from_slice(&in_out[plaintext_len..plaintext_len + alg_tag_len]);
361 tag_buffer[alg_tag_len..alg_tag_len + alg_nonce_len].copy_from_slice(nonce);
362
363 let tag_slice = &tag_buffer[0..alg_tag_len + alg_nonce_len];
364
365 if 1 != indicator_check!(unsafe {
366 EVP_AEAD_CTX_open_gather(
367 self.ctx.as_ref().as_const_ptr(),
368 in_out.as_mut_ptr(),
369 null(),
370 0,
371 in_out.as_ptr(),
372 plaintext_len,
373 tag_slice.as_ptr(),
374 tag_slice.len(),
375 aad.as_ptr(),
376 aad.len(),
377 )
378 }) {
379 return Err(Unspecified);
380 }
381
382 Ok(())
383 }
384
385 #[inline]
386 fn seal_combined<InOut>(
387 &self,
388 nonce: Nonce,
389 aad: &[u8],
390 in_out: &mut InOut,
391 ) -> Result<Nonce, Unspecified>
392 where
393 InOut: AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>,
394 {
395 let plaintext_len = in_out.as_mut().len();
396
397 let alg_tag_len = self.algorithm().tag_len();
398
399 debug_assert!(alg_tag_len <= MAX_TAG_LEN);
400
401 let tag_buffer = [0u8; MAX_TAG_LEN];
402
403 in_out.extend(tag_buffer[..alg_tag_len].iter());
404
405 let mut out_len = MaybeUninit::<usize>::uninit();
406 let mut_in_out = in_out.as_mut();
407
408 {
409 let nonce = nonce.as_ref();
410
411 debug_assert_eq!(nonce.len(), self.algorithm().nonce_len());
412
413 if 1 != indicator_check!(unsafe {
414 EVP_AEAD_CTX_seal(
415 self.ctx.as_ref().as_const_ptr(),
416 mut_in_out.as_mut_ptr(),
417 out_len.as_mut_ptr(),
418 plaintext_len + alg_tag_len,
419 nonce.as_ptr(),
420 nonce.len(),
421 mut_in_out.as_ptr(),
422 plaintext_len,
423 aad.as_ptr(),
424 aad.len(),
425 )
426 }) {
427 return Err(Unspecified);
428 }
429 }
430
431 Ok(nonce)
432 }
433
434 #[inline]
435 fn seal_combined_randnonce<InOut>(
436 &self,
437 aad: &[u8],
438 in_out: &mut InOut,
439 ) -> Result<Nonce, Unspecified>
440 where
441 InOut: AsMut<[u8]> + for<'in_out> Extend<&'in_out u8>,
442 {
443 let mut tag_buffer = [0u8; MAX_TAG_NONCE_BUFFER_LEN];
444
445 let mut out_tag_len = MaybeUninit::<usize>::uninit();
446
447 {
448 let plaintext_len = in_out.as_mut().len();
449 let in_out = in_out.as_mut();
450
451 if 1 != indicator_check!(unsafe {
452 EVP_AEAD_CTX_seal_scatter(
453 self.ctx.as_ref().as_const_ptr(),
454 in_out.as_mut_ptr(),
455 tag_buffer.as_mut_ptr(),
456 out_tag_len.as_mut_ptr(),
457 tag_buffer.len(),
458 null(),
459 0,
460 in_out.as_ptr(),
461 plaintext_len,
462 null(),
463 0,
464 aad.as_ptr(),
465 aad.len(),
466 )
467 }) {
468 return Err(Unspecified);
469 }
470 }
471
472 let tag_len = self.algorithm().tag_len();
473 let nonce_len = self.algorithm().nonce_len();
474
475 let nonce = Nonce(FixedLength::<NONCE_LEN>::try_from(
476 &tag_buffer[tag_len..tag_len + nonce_len],
477 )?);
478
479 in_out.extend(&tag_buffer[..tag_len]);
480
481 Ok(nonce)
482 }
483
484 #[inline]
485 fn seal_separate(
486 &self,
487 nonce: Nonce,
488 aad: &[u8],
489 in_out: &mut [u8],
490 ) -> Result<(Nonce, Tag), Unspecified> {
491 let mut tag = [0u8; MAX_TAG_LEN];
492 let mut out_tag_len = MaybeUninit::<usize>::uninit();
493 {
494 let nonce = nonce.as_ref();
495
496 debug_assert_eq!(nonce.len(), self.algorithm().nonce_len());
497
498 if 1 != indicator_check!(unsafe {
499 EVP_AEAD_CTX_seal_scatter(
500 self.ctx.as_ref().as_const_ptr(),
501 in_out.as_mut_ptr(),
502 tag.as_mut_ptr(),
503 out_tag_len.as_mut_ptr(),
504 tag.len(),
505 nonce.as_ptr(),
506 nonce.len(),
507 in_out.as_ptr(),
508 in_out.len(),
509 null(),
510 0usize,
511 aad.as_ptr(),
512 aad.len(),
513 )
514 }) {
515 return Err(Unspecified);
516 }
517 }
518 Ok((nonce, Tag(tag, unsafe { out_tag_len.assume_init() })))
519 }
520
521 #[inline]
522 fn seal_separate_randnonce(
523 &self,
524 aad: &[u8],
525 in_out: &mut [u8],
526 ) -> Result<(Nonce, Tag), Unspecified> {
527 let mut tag_buffer = [0u8; MAX_TAG_NONCE_BUFFER_LEN];
528
529 debug_assert!(
530 self.algorithm().tag_len() + self.algorithm().nonce_len() <= tag_buffer.len()
531 );
532
533 let mut out_tag_len = MaybeUninit::<usize>::uninit();
534
535 if 1 != indicator_check!(unsafe {
536 EVP_AEAD_CTX_seal_scatter(
537 self.ctx.as_ref().as_const_ptr(),
538 in_out.as_mut_ptr(),
539 tag_buffer.as_mut_ptr(),
540 out_tag_len.as_mut_ptr(),
541 tag_buffer.len(),
542 null(),
543 0,
544 in_out.as_ptr(),
545 in_out.len(),
546 null(),
547 0usize,
548 aad.as_ptr(),
549 aad.len(),
550 )
551 }) {
552 return Err(Unspecified);
553 }
554
555 let tag_len = self.algorithm().tag_len();
556 let nonce_len = self.algorithm().nonce_len();
557
558 let nonce = Nonce(FixedLength::<NONCE_LEN>::try_from(
559 &tag_buffer[tag_len..tag_len + nonce_len],
560 )?);
561
562 let mut tag = [0u8; MAX_TAG_LEN];
563 tag.copy_from_slice(&tag_buffer[..tag_len]);
564
565 Ok((nonce, Tag(tag, tag_len)))
566 }
567}
568
569impl From<AeadCtx> for UnboundKey {
570 fn from(value: AeadCtx) -> Self {
571 let algorithm = match value {
572 AeadCtx::AES_128_GCM(_)
573 | AeadCtx::AES_128_GCM_TLS12(_)
574 | AeadCtx::AES_128_GCM_TLS13(_)
575 | AeadCtx::AES_128_GCM_RANDNONCE(_) => &AES_128_GCM,
576 AeadCtx::AES_192_GCM(_) => &AES_192_GCM,
577 AeadCtx::AES_128_GCM_SIV(_) => &AES_128_GCM_SIV,
578 AeadCtx::AES_256_GCM(_)
579 | AeadCtx::AES_256_GCM_RANDNONCE(_)
580 | AeadCtx::AES_256_GCM_TLS12(_)
581 | AeadCtx::AES_256_GCM_TLS13(_) => &AES_256_GCM,
582 AeadCtx::AES_256_GCM_SIV(_) => &AES_256_GCM_SIV,
583 AeadCtx::CHACHA20_POLY1305(_) => &CHACHA20_POLY1305,
584 };
585 Self {
586 ctx: value,
587 algorithm,
588 }
589 }
590}
591
592impl From<hkdf::Okm<'_, &'static Algorithm>> for UnboundKey {
593 fn from(okm: hkdf::Okm<&'static Algorithm>) -> Self {
594 let mut key_bytes = [0; MAX_KEY_LEN];
595 let key_bytes = &mut key_bytes[..okm.len().key_len];
596 let algorithm = *okm.len();
597 okm.fill(key_bytes).unwrap();
598 Self::new(algorithm, key_bytes).unwrap()
599 }
600}