aws_lc_rs/
key_wrap.rs

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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC

//! Key Wrap Algorithms.
//!
//! # Examples
//! ```rust
//! # use std::error::Error;
//! # fn main() -> Result<(), Box<dyn Error>> {
//! use aws_lc_rs::key_wrap::{AesKek, KeyWrapPadded, AES_128};
//!
//! const KEY: &[u8] = &[
//!     0xa8, 0xe0, 0x6d, 0xa6, 0x25, 0xa6, 0x5b, 0x25, 0xcf, 0x50, 0x30, 0x82, 0x68, 0x30, 0xb6,
//!     0x61,
//! ];
//! const PLAINTEXT: &[u8] = &[0x43, 0xac, 0xff, 0x29, 0x31, 0x20, 0xdd, 0x5d];
//!
//! let kek = AesKek::new(&AES_128, KEY)?;
//!
//! let mut output = vec![0u8; PLAINTEXT.len() + 15];
//!
//! let ciphertext = kek.wrap_with_padding(PLAINTEXT, &mut output)?;
//!
//! let kek = AesKek::new(&AES_128, KEY)?;
//!
//! let mut output = vec![0u8; ciphertext.len()];
//!
//! let plaintext = kek.unwrap_with_padding(&*ciphertext, &mut output)?;
//!
//! assert_eq!(PLAINTEXT, plaintext);
//! # Ok(())
//! # }
//! ```

use crate::{error::Unspecified, fips::indicator_check, sealed::Sealed};
use aws_lc::{
    AES_set_decrypt_key, AES_set_encrypt_key, AES_unwrap_key, AES_unwrap_key_padded, AES_wrap_key,
    AES_wrap_key_padded, AES_KEY,
};
use core::{fmt::Debug, mem::MaybeUninit, ptr::null};

mod tests;

/// The Key Wrapping Algorithm Identifier
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[non_exhaustive]
pub enum BlockCipherId {
    /// AES Block Cipher with 128-bit key.
    Aes128,

    /// AES Block Cipher with 256-bit key.
    Aes256,
}

/// A key wrap block cipher.
pub trait BlockCipher: 'static + Debug + Sealed {
    /// The block cipher identifier.
    fn id(&self) -> BlockCipherId;

    /// The key size in bytes to be used with the block cipher.
    fn key_len(&self) -> usize;
}

/// An AES Block Cipher
pub struct AesBlockCipher {
    id: BlockCipherId,
    key_len: usize,
}

impl BlockCipher for AesBlockCipher {
    /// Returns the algorithm identifier.
    #[inline]
    #[must_use]
    fn id(&self) -> BlockCipherId {
        self.id
    }

    /// Returns the algorithm key length.
    #[inline]
    #[must_use]
    fn key_len(&self) -> usize {
        self.key_len
    }
}

impl Sealed for AesBlockCipher {}

impl Debug for AesBlockCipher {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        Debug::fmt(&self.id, f)
    }
}

/// AES Block Cipher with 128-bit key.
pub const AES_128: AesBlockCipher = AesBlockCipher {
    id: BlockCipherId::Aes128,
    key_len: 16,
};

/// AES Block Cipher with 256-bit key.
pub const AES_256: AesBlockCipher = AesBlockCipher {
    id: BlockCipherId::Aes256,
    key_len: 32,
};

/// A Key Wrap (KW) algorithm implementation.
#[allow(clippy::module_name_repetitions)]
pub trait KeyWrap: Sealed {
    /// Peforms the key wrap encryption algorithm using a block cipher.
    /// It wraps `plaintext` and writes the corresponding ciphertext to `output`.
    ///
    /// # Errors
    /// * [`Unspecified`]: Any error that has occurred performing the operation.
    fn wrap<'output>(
        self,
        plaintext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified>;

    /// Peforms the key wrap decryption algorithm using a block cipher.
    /// It unwraps `ciphertext` and writes the corresponding plaintext to `output`.
    ///
    /// # Errors
    /// * [`Unspecified`]: Any error that has occurred performing the operation.
    fn unwrap<'output>(
        self,
        ciphertext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified>;
}

/// A Key Wrap with Padding (KWP) algorithm implementation.
#[allow(clippy::module_name_repetitions)]
pub trait KeyWrapPadded: Sealed {
    /// Peforms the key wrap padding encryption algorithm using a block cipher.
    /// It wraps and pads `plaintext` writes the corresponding ciphertext to `output`.
    ///
    /// # Errors
    /// * [`Unspecified`]: Any error that has occurred performing the operation.
    fn wrap_with_padding<'output>(
        self,
        plaintext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified>;

    /// Peforms the key wrap padding decryption algorithm using a block cipher.
    /// It unwraps the padded `ciphertext` and writes the corresponding plaintext to `output`.
    ///
    /// # Errors
    /// * [`Unspecified`]: Any error that has occurred performing the operation.
    fn unwrap_with_padding<'output>(
        self,
        ciphertext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified>;
}

/// AES Key Encryption Key.
pub type AesKek = KeyEncryptionKey<AesBlockCipher>;

/// The key-encryption key used with the selected cipher algorithn to wrap or unwrap a key.
///
/// Implements the NIST SP 800-38F key wrapping algoirthm.
///
/// The NIST specification is similar to that of RFC 3394 but with the following caveats:
/// * Specifies a maxiumum plaintext length that can be accepted.
/// * Allows implementations to specify a subset of valid lengths accepted.
/// * Allows for the usage of other 128-bit block ciphers other than AES.
pub struct KeyEncryptionKey<Cipher: BlockCipher> {
    cipher: &'static Cipher,
    key: Box<[u8]>,
}

impl<Cipher: BlockCipher> KeyEncryptionKey<Cipher> {
    /// Construct a new Key Encryption Key.
    ///
    /// # Errors
    /// * [`Unspecified`]: Any error that occurs constructing the key encryption key.
    pub fn new(cipher: &'static Cipher, key: &[u8]) -> Result<Self, Unspecified> {
        if key.len() != cipher.key_len() {
            return Err(Unspecified);
        }

        let key = Vec::from(key).into_boxed_slice();

        Ok(Self { cipher, key })
    }

    /// Returns the block cipher algorithm identifier configured for the key.
    #[must_use]
    pub fn block_cipher_id(&self) -> BlockCipherId {
        self.cipher.id()
    }
}

impl<Cipher: BlockCipher> Sealed for KeyEncryptionKey<Cipher> {}

impl KeyWrap for KeyEncryptionKey<AesBlockCipher> {
    /// Peforms the key wrap encryption algorithm using `KeyEncryptionKey`'s configured block cipher.
    /// It wraps `plaintext` and writes the corresponding ciphertext to `output`.
    ///
    /// # Validation
    /// * `plaintext.len()` must be a multiple of eight
    /// * `output.len() >= (input.len() + 8)`
    ///
    /// # Errors
    /// * [`Unspecified`]: An error occurred either due to `output` being insufficiently sized, `input` exceeding
    ///   the allowed input size, or for other unspecified reasons.
    fn wrap<'output>(
        self,
        plaintext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified> {
        if output.len() < plaintext.len() + 8 {
            return Err(Unspecified);
        }

        let mut aes_key = MaybeUninit::<AES_KEY>::uninit();

        let key_bits: u32 = (self.key.len() * 8).try_into().map_err(|_| Unspecified)?;

        if 0 != unsafe { AES_set_encrypt_key(self.key.as_ptr(), key_bits, aes_key.as_mut_ptr()) } {
            return Err(Unspecified);
        }

        let aes_key = unsafe { aes_key.assume_init() };

        // AWS-LC validates the following:
        // * in_len <= INT_MAX - 8
        // * in_len >= 16
        // * in_len % 8 == 0
        let out_len = indicator_check!(unsafe {
            AES_wrap_key(
                &aes_key,
                null(),
                output.as_mut_ptr(),
                plaintext.as_ptr(),
                plaintext.len(),
            )
        });

        if out_len == -1 {
            return Err(Unspecified);
        }

        let out_len: usize = out_len.try_into().map_err(|_| Unspecified)?;

        debug_assert_eq!(out_len, plaintext.len() + 8);

        Ok(&mut output[..out_len])
    }

    /// Peforms the key wrap decryption algorithm using `KeyEncryptionKey`'s configured block cipher.
    /// It unwraps `ciphertext` and writes the corresponding plaintext to `output`.
    ///
    /// # Validation
    /// * `ciphertext.len()` must be a multiple of 8
    /// * `output.len() >= (input.len() - 8)`
    ///
    /// # Errors
    /// * [`Unspecified`]: An error occurred either due to `output` being insufficiently sized, `input` exceeding
    ///   the allowed input size, or for other unspecified reasons.
    fn unwrap<'output>(
        self,
        ciphertext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified> {
        if output.len() < ciphertext.len() - 8 {
            return Err(Unspecified);
        }

        let mut aes_key = MaybeUninit::<AES_KEY>::uninit();

        if 0 != unsafe {
            AES_set_decrypt_key(
                self.key.as_ptr(),
                (self.key.len() * 8).try_into().map_err(|_| Unspecified)?,
                aes_key.as_mut_ptr(),
            )
        } {
            return Err(Unspecified);
        }

        let aes_key = unsafe { aes_key.assume_init() };

        // AWS-LC validates the following:
        // * in_len < INT_MAX
        // * in_len > 24
        // * in_len % 8 == 0
        let out_len = indicator_check!(unsafe {
            AES_unwrap_key(
                &aes_key,
                null(),
                output.as_mut_ptr(),
                ciphertext.as_ptr(),
                ciphertext.len(),
            )
        });

        if out_len == -1 {
            return Err(Unspecified);
        }

        let out_len: usize = out_len.try_into().map_err(|_| Unspecified)?;

        debug_assert_eq!(out_len, ciphertext.len() - 8);

        Ok(&mut output[..out_len])
    }
}

impl KeyWrapPadded for KeyEncryptionKey<AesBlockCipher> {
    /// Peforms the key wrap padding encryption algorithm using `KeyEncryptionKey`'s configured block cipher.
    /// It wraps and pads `plaintext` writes the corresponding ciphertext to `output`.
    ///
    /// # Validation
    /// * `output.len() >= (input.len() + 15)`
    ///
    /// # Errors
    /// * [`Unspecified`]: An error occurred either due to `output` being insufficiently sized, `input` exceeding
    ///   the allowed input size, or for other unspecified reasons.
    fn wrap_with_padding<'output>(
        self,
        plaintext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified> {
        let mut aes_key = MaybeUninit::<AES_KEY>::uninit();

        let key_bits: u32 = (self.key.len() * 8).try_into().map_err(|_| Unspecified)?;

        if 0 != unsafe { AES_set_encrypt_key(self.key.as_ptr(), key_bits, aes_key.as_mut_ptr()) } {
            return Err(Unspecified);
        }

        let aes_key = unsafe { aes_key.assume_init() };

        let mut out_len: usize = 0;

        // AWS-LC validates the following:
        // * in_len != 0
        // * in_len <= INT_MAX
        // * max_out >= required_padding + 8
        if 1 != indicator_check!(unsafe {
            AES_wrap_key_padded(
                &aes_key,
                output.as_mut_ptr(),
                &mut out_len,
                output.len(),
                plaintext.as_ptr(),
                plaintext.len(),
            )
        }) {
            return Err(Unspecified);
        }

        Ok(&mut output[..out_len])
    }

    /// Peforms the key wrap padding decryption algorithm using `KeyEncryptionKey`'s configured block cipher.
    /// It unwraps the padded `ciphertext` and writes the corresponding plaintext to `output`.
    ///
    /// # Sizing `output`
    /// `output.len() >= input.len()`.
    ///
    /// # Errors
    /// * [`Unspecified`]: An error occurred either due to `output` being insufficiently sized, `input` exceeding
    ///   the allowed input size, or for other unspecified reasons.
    fn unwrap_with_padding<'output>(
        self,
        ciphertext: &[u8],
        output: &'output mut [u8],
    ) -> Result<&'output mut [u8], Unspecified> {
        let mut aes_key = MaybeUninit::<AES_KEY>::uninit();

        if 0 != unsafe {
            AES_set_decrypt_key(
                self.key.as_ptr(),
                (self.key.len() * 8).try_into().map_err(|_| Unspecified)?,
                aes_key.as_mut_ptr(),
            )
        } {
            return Err(Unspecified);
        }

        let aes_key = unsafe { aes_key.assume_init() };

        let mut out_len: usize = 0;

        // AWS-LC validates the following:
        // * in_len >= AES_BLOCK_SIZE
        // * max_out >= in_len - 8
        if 1 != indicator_check!(unsafe {
            AES_unwrap_key_padded(
                &aes_key,
                output.as_mut_ptr(),
                &mut out_len,
                output.len(),
                ciphertext.as_ptr(),
                ciphertext.len(),
            )
        }) {
            return Err(Unspecified);
        };

        Ok(&mut output[..out_len])
    }
}

impl<Cipher: BlockCipher> Debug for KeyEncryptionKey<Cipher> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("KeyEncryptionKey")
            .field("cipher", &self.cipher)
            .finish_non_exhaustive()
    }
}