huskarl-crypto-native 0.8.1

Native crypto for huskarl (OAuth2 client) ecosystem.
Documentation
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
416
//! AEAD encryptor/decryptor implementations.

use std::{array::TryFromSliceError, borrow::Cow, fmt};

use aes_gcm::{AeadInOut, KeyInit, aead::Generate};
use huskarl_core::{
    Error, ErrorKind,
    crypto::{
        KeyMatchStrength,
        cipher::{AeadDecryptor, AeadEncryptor, AeadOutput, CipherMatch, DecryptError},
    },
    platform::MaybeSendBoxFuture,
    secrets::{Secret, SecretBytes},
};
use sha2::digest::array::Array;
use snafu::prelude::*;

// aes-gcm ships `Aes128Gcm`/`Aes256Gcm` aliases but not 192; spell it out from
// the re-exported `aes` building blocks (96-bit nonce, like the other two).
type Aes192Gcm = aes_gcm::AesGcm<aes_gcm::aes::Aes192, aes_gcm::aes::cipher::consts::U12>;

enum NativeKey {
    Aes128(Box<aes_gcm::Aes128Gcm>),
    Aes192(Box<Aes192Gcm>),
    Aes256(Box<aes_gcm::Aes256Gcm>),
}

impl NativeKey {
    pub fn enc_algorithm(&self) -> &'static str {
        match self {
            NativeKey::Aes128(_) => "A128GCM",
            NativeKey::Aes192(_) => "A192GCM",
            NativeKey::Aes256(_) => "A256GCM",
        }
    }
}

/// An AES-GCM key.
pub struct AesGcmKey {
    inner: NativeKey,
    kid: Option<String>,
}

impl fmt::Debug for AesGcmKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AesGcmKey")
            .field("enc", &self.inner.enc_algorithm())
            .field("kid", &self.kid)
            .finish_non_exhaustive()
    }
}

/// Errors that can occur when loading a key.
#[derive(Debug, Snafu)]
pub enum LoadKeyError {
    /// There was an error fetching the secret.
    Secret {
        /// The underlying error.
        source: Error,
    },
    /// The key had the incorrect length;
    InvalidKeyLength,
}

impl AesGcmKey {
    /// Load a key from a secret, inferring AES-128/192/256 from the key length
    /// (16/24/32 bytes).
    ///
    /// # Errors
    ///
    /// Fails if the secret cannot be fetched, or the key material is not 16, 24,
    /// or 32 bytes.
    pub async fn from_secret<S: Secret<Output = SecretBytes>>(
        secret: S,
        kid_from_identity: impl Fn(Option<&str>) -> Option<String>,
    ) -> Result<Self, LoadKeyError> {
        let key_source = secret.get_secret_value().await.context(SecretSnafu)?;
        let bytes = key_source.value.expose_secret();

        let inner = match bytes.len() {
            16 => NativeKey::Aes128(Box::new(
                aes_gcm::Aes128Gcm::new_from_slice(bytes)
                    .map_err(|_| InvalidKeyLengthSnafu.build())?,
            )),
            24 => NativeKey::Aes192(Box::new(
                Aes192Gcm::new_from_slice(bytes).map_err(|_| InvalidKeyLengthSnafu.build())?,
            )),
            32 => NativeKey::Aes256(Box::new(
                aes_gcm::Aes256Gcm::new_from_slice(bytes)
                    .map_err(|_| InvalidKeyLengthSnafu.build())?,
            )),
            _ => return InvalidKeyLengthSnafu.fail(),
        };

        Ok(AesGcmKey {
            inner,
            kid: kid_from_identity(key_source.identity.as_deref()),
        })
    }
}

/// Errors that can occur during AEAD operations.
#[derive(Debug, Snafu)]
pub enum AesGcmError {
    /// An error occurred when decrypting the ciphertext.
    Decrypt {
        /// The underlying error.
        source: aes_gcm::Error,
    },
    /// An error occurred when encrypting the plaintext.
    Encrypt {
        /// The underlying error.
        source: aes_gcm::Error,
    },
    /// The supplied nonce had an invalid length.
    InvalidNonce {
        /// The underlying error.
        source: TryFromSliceError,
    },
    /// The supplied tag had an invalid length.
    InvalidTag {
        /// The underlying error.
        source: TryFromSliceError,
    },
}

impl From<AesGcmError> for Error {
    fn from(value: AesGcmError) -> Self {
        Error::new(ErrorKind::Crypto, value)
    }
}

impl From<AesGcmError> for DecryptError {
    fn from(value: AesGcmError) -> Self {
        Error::from(value).into()
    }
}

impl AeadEncryptor for AesGcmKey {
    fn enc_algorithm(&self) -> Cow<'_, str> {
        Cow::Borrowed(self.inner.enc_algorithm())
    }

    fn key_id(&self) -> Option<Cow<'_, str>> {
        self.kid.as_deref().map(Cow::Borrowed)
    }

    fn encrypt<'a>(
        &'a self,
        plaintext: &'a [u8],
        aad: &'a [u8],
    ) -> MaybeSendBoxFuture<'a, Result<AeadOutput, Error>> {
        Box::pin(async move {
            let nonce = Array::generate();
            let mut ciphertext = plaintext.to_vec();

            let tag = match &self.inner {
                NativeKey::Aes128(aes_gcm) => {
                    aes_gcm.encrypt_inout_detached(&nonce, aad, ciphertext.as_mut_slice().into())
                }
                NativeKey::Aes192(aes_gcm) => {
                    aes_gcm.encrypt_inout_detached(&nonce, aad, ciphertext.as_mut_slice().into())
                }
                NativeKey::Aes256(aes_gcm) => {
                    aes_gcm.encrypt_inout_detached(&nonce, aad, ciphertext.as_mut_slice().into())
                }
            }
            .context(EncryptSnafu)?;

            Ok(AeadOutput {
                nonce: nonce.into(),
                ciphertext,
                tag: tag.into(),
            })
        })
    }
}

impl AeadDecryptor for AesGcmKey {
    fn cipher_match(&self, m: &CipherMatch<'_>) -> Option<KeyMatchStrength> {
        m.strength_for(self.inner.enc_algorithm(), self.kid.as_deref())
    }

    fn decrypt<'a>(
        &'a self,
        _cipher_match: Option<&'a CipherMatch<'a>>,
        nonce: &'a [u8],
        ciphertext: &'a [u8],
        tag: &'a [u8],
        aad: &'a [u8],
    ) -> MaybeSendBoxFuture<'a, Result<Vec<u8>, DecryptError>> {
        Box::pin(async move {
            let nonce = nonce.try_into().context(InvalidNonceSnafu)?;
            let tag = tag.try_into().context(InvalidTagSnafu)?;
            let mut plaintext = ciphertext.to_vec();

            match &self.inner {
                NativeKey::Aes128(aes_gcm) => aes_gcm.decrypt_inout_detached(
                    &nonce,
                    aad,
                    plaintext.as_mut_slice().into(),
                    &tag,
                ),
                NativeKey::Aes192(aes_gcm) => aes_gcm.decrypt_inout_detached(
                    &nonce,
                    aad,
                    plaintext.as_mut_slice().into(),
                    &tag,
                ),
                NativeKey::Aes256(aes_gcm) => aes_gcm.decrypt_inout_detached(
                    &nonce,
                    aad,
                    plaintext.as_mut_slice().into(),
                    &tag,
                ),
            }
            .context(DecryptSnafu)?;

            Ok(plaintext)
        })
    }
}

#[cfg(test)]
mod tests {
    use huskarl_core::{
        platform::MaybeSendBoxFuture,
        secrets::{Secret, SecretBytes, SecretOutput},
    };

    use super::*;

    #[derive(Clone)]
    struct TestSecret {
        bytes: Vec<u8>,
        identity: Option<String>,
    }

    impl Secret for TestSecret {
        type Output = SecretBytes;

        fn get_secret_value(
            &self,
        ) -> MaybeSendBoxFuture<'_, Result<SecretOutput<SecretBytes>, Error>> {
            let out = SecretOutput {
                value: SecretBytes::new(self.bytes.clone()),
                identity: self.identity.clone(),
            };
            Box::pin(async move { Ok(out) })
        }
    }

    async fn key_from(bytes: Vec<u8>, identity: Option<&str>) -> AesGcmKey {
        AesGcmKey::from_secret(
            TestSecret {
                bytes,
                identity: identity.map(str::to_owned),
            },
            |id| id.map(str::to_owned),
        )
        .await
        .unwrap()
    }

    /// Decode an ASCII hex string into bytes (for the NIST known-answer test).
    fn hex(s: &str) -> Vec<u8> {
        assert!(
            s.len().is_multiple_of(2),
            "hex string must have even length"
        );
        (0..s.len())
            .step_by(2)
            .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
            .collect()
    }

    async fn roundtrip(key_bytes: Vec<u8>, expected_enc: &str) {
        let key = key_from(key_bytes, None).await;
        assert_eq!(key.enc_algorithm().as_ref(), expected_enc);

        let pt = b"the quick brown fox jumps over the lazy dog";
        let aad = b"session-context";
        let out = key.encrypt(pt, aad).await.unwrap();

        assert_eq!(out.nonce.len(), 12, "96-bit nonce");
        assert_eq!(out.tag.len(), 16, "128-bit tag");
        assert_eq!(out.ciphertext.len(), pt.len(), "GCM is length-preserving");
        assert_ne!(out.ciphertext, pt, "ciphertext must not equal plaintext");

        let recovered = key
            .decrypt(None, &out.nonce, &out.ciphertext, &out.tag, aad)
            .await
            .unwrap();
        assert_eq!(recovered, pt);
    }

    #[tokio::test]
    async fn roundtrip_a128gcm() {
        roundtrip(vec![1u8; 16], "A128GCM").await;
    }

    #[tokio::test]
    async fn roundtrip_a192gcm() {
        roundtrip(vec![2u8; 24], "A192GCM").await;
    }

    #[tokio::test]
    async fn roundtrip_a256gcm() {
        roundtrip(vec![3u8; 32], "A256GCM").await;
    }

    #[tokio::test]
    async fn invalid_key_length_rejected() {
        for len in [0usize, 15, 17, 31, 33, 64] {
            let err = AesGcmKey::from_secret(
                TestSecret {
                    bytes: vec![0u8; len],
                    identity: None,
                },
                |_| None,
            )
            .await
            .unwrap_err();
            assert!(
                matches!(err, LoadKeyError::InvalidKeyLength),
                "{len}-byte key must be rejected"
            );
        }
    }

    #[tokio::test]
    async fn kid_derived_from_identity() {
        let key = key_from(vec![4u8; 32], Some("cookie-key-2026")).await;
        assert_eq!(key.key_id().as_deref(), Some("cookie-key-2026"));
    }

    #[tokio::test]
    async fn wrong_aad_fails_to_open() {
        let key = key_from(vec![5u8; 32], None).await;
        let out = key.encrypt(b"payload", b"session").await.unwrap();
        let res = key
            .decrypt(None, &out.nonce, &out.ciphertext, &out.tag, b"other")
            .await;
        assert!(res.is_err(), "AAD must bind: a different AAD must not open");
    }

    #[tokio::test]
    async fn tampered_ciphertext_fails_to_open() {
        let key = key_from(vec![6u8; 32], None).await;
        let out = key.encrypt(b"payload", b"session").await.unwrap();
        let mut ct = out.ciphertext.clone();
        ct[0] ^= 0x01;
        let res = key
            .decrypt(None, &out.nonce, &ct, &out.tag, b"session")
            .await;
        assert!(
            res.is_err(),
            "a flipped ciphertext bit must fail the tag check"
        );
    }

    #[tokio::test]
    async fn wrong_length_nonce_and_tag_rejected() {
        let key = key_from(vec![7u8; 32], None).await;
        let out = key.encrypt(b"payload", b"session").await.unwrap();

        // Nonce too short (11 bytes instead of 12).
        let res = key
            .decrypt(
                None,
                &out.nonce[..11],
                &out.ciphertext,
                &out.tag,
                b"session",
            )
            .await;
        assert!(res.is_err(), "a wrong-length nonce must be rejected");

        // Tag too short (15 bytes instead of 16).
        let res = key
            .decrypt(
                None,
                &out.nonce,
                &out.ciphertext,
                &out.tag[..15],
                b"session",
            )
            .await;
        assert!(res.is_err(), "a wrong-length tag must be rejected");
    }

    /// NIST GCM spec (`McGrew` & Viega) Test Case 4 — AES-128-GCM with AAD.
    /// Exercises the detached-tag decrypt path against a known-answer vector.
    #[tokio::test]
    async fn aes128_nist_test_case_4_decrypt() {
        let key_bytes = hex("feffe9928665731c6d6a8f9467308308");
        let nonce = hex("cafebabefacedbaddecaf888");
        let aad = hex("feedfacedeadbeeffeedfacedeadbeefabaddad2");
        let ciphertext = hex(
            "42831ec2217774244b7221b784d0d49ce3aa212f2c02a4e035c17e2329aca12e\
             21d514b25466931c7d8f6a5aac84aa051ba30b396a0aac973d58e091",
        );
        let tag = hex("5bc94fbc3221a5db94fae95ae7121a47");
        let expected_pt = hex(
            "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a72\
             1c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b39",
        );

        let key = key_from(key_bytes, None).await;
        let pt = key
            .decrypt(None, &nonce, &ciphertext, &tag, &aad)
            .await
            .unwrap();
        assert_eq!(pt, expected_pt);
    }
}