aws_lc_rs/
hmac.rs

1// Copyright 2015-2022 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5
6//! HMAC is specified in [RFC 2104].
7//!
8//! After a `Key` is constructed, it can be used for multiple signing or
9//! verification operations. Separating the construction of the key from the
10//! rest of the HMAC operation allows the per-key precomputation to be done
11//! only once, instead of it being done in every HMAC operation.
12//!
13//! Frequently all the data to be signed in a message is available in a single
14//! contiguous piece. In that case, the module-level `sign` function can be
15//! used. Otherwise, if the input is in multiple parts, `Context` should be
16//! used.
17//!
18//! # Examples:
19//!
20//! ## Signing a value and verifying it wasn't tampered with
21//!
22//! ```
23//! use aws_lc_rs::{hmac, rand};
24//!
25//! let rng = rand::SystemRandom::new();
26//! let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?;
27//!
28//! let msg = "hello, world";
29//!
30//! let tag = hmac::sign(&key, msg.as_bytes());
31//!
32//! // [We give access to the message to an untrusted party, and they give it
33//! // back to us. We need to verify they didn't tamper with it.]
34//!
35//! hmac::verify(&key, msg.as_bytes(), tag.as_ref())?;
36//!
37//! # Ok::<(), aws_lc_rs::error::Unspecified>(())
38//! ```
39//!
40//! ## Using the one-shot API:
41//!
42//! ```
43//! use aws_lc_rs::rand::SecureRandom;
44//! use aws_lc_rs::{digest, hmac, rand};
45//!
46//! let msg = "hello, world";
47//!
48//! // The sender generates a secure key value and signs the message with it.
49//! // Note that in a real protocol, a key agreement protocol would be used to
50//! // derive `key_value`.
51//! let rng = rand::SystemRandom::new();
52//! let key_value: [u8; digest::SHA256_OUTPUT_LEN] = rand::generate(&rng)?.expose();
53//!
54//! let s_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref());
55//! let tag = hmac::sign(&s_key, msg.as_bytes());
56//!
57//! // The receiver (somehow!) knows the key value, and uses it to verify the
58//! // integrity of the message.
59//! let v_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref());
60//! hmac::verify(&v_key, msg.as_bytes(), tag.as_ref())?;
61//!
62//! # Ok::<(), aws_lc_rs::error::Unspecified>(())
63//! ```
64//!
65//! ## Using the multi-part API:
66//! ```
67//! use aws_lc_rs::rand::SecureRandom;
68//! use aws_lc_rs::{digest, hmac, rand};
69//!
70//! let parts = ["hello", ", ", "world"];
71//!
72//! // The sender generates a secure key value and signs the message with it.
73//! // Note that in a real protocol, a key agreement protocol would be used to
74//! // derive `key_value`.
75//! let rng = rand::SystemRandom::new();
76//! let mut key_value: [u8; digest::SHA384_OUTPUT_LEN] = rand::generate(&rng)?.expose();
77//!
78//! let s_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref());
79//! let mut s_ctx = hmac::Context::with_key(&s_key);
80//! for part in &parts {
81//!     s_ctx.update(part.as_bytes());
82//! }
83//! let tag = s_ctx.sign();
84//!
85//! // The receiver (somehow!) knows the key value, and uses it to verify the
86//! // integrity of the message.
87//! let v_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref());
88//! let mut msg = Vec::<u8>::new();
89//! for part in &parts {
90//!     msg.extend(part.as_bytes());
91//! }
92//! hmac::verify(&v_key, &msg.as_ref(), tag.as_ref())?;
93//!
94//! # Ok::<(), aws_lc_rs::error::Unspecified>(())
95//! ```
96//! [RFC 2104]: https://tools.ietf.org/html/rfc2104
97
98use crate::aws_lc::{
99    HMAC_CTX_cleanup, HMAC_CTX_copy_ex, HMAC_CTX_init, HMAC_Final, HMAC_Init_ex, HMAC_Update,
100    HMAC_CTX,
101};
102use crate::error::Unspecified;
103use crate::fips::indicator_check;
104use crate::{constant_time, digest, hkdf};
105use core::mem::MaybeUninit;
106use core::ptr::null_mut;
107// TODO: Uncomment when MSRV >= 1.64
108// use core::ffi::c_uint;
109use std::os::raw::c_uint;
110
111/// A deprecated alias for `Tag`.
112#[deprecated]
113pub type Signature = Tag;
114/// Renamed to `Context`.
115#[deprecated]
116pub type SigningContext = Context;
117/// Renamed to `Key`.
118#[deprecated]
119pub type SigningKey = Key;
120/// Merged into `Key`.
121#[deprecated]
122pub type VerificationKey = Key;
123
124/// An HMAC algorithm.
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub struct Algorithm(&'static digest::Algorithm);
127
128impl Algorithm {
129    /// The digest algorithm this HMAC algorithm is based on.
130    #[inline]
131    #[must_use]
132    pub fn digest_algorithm(&self) -> &'static digest::Algorithm {
133        self.0
134    }
135}
136
137/// HMAC using SHA-1. Obsolete.
138pub static HMAC_SHA1_FOR_LEGACY_USE_ONLY: Algorithm = Algorithm(&digest::SHA1_FOR_LEGACY_USE_ONLY);
139
140/// HMAC using SHA-224.
141pub static HMAC_SHA224: Algorithm = Algorithm(&digest::SHA224);
142
143/// HMAC using SHA-256.
144pub static HMAC_SHA256: Algorithm = Algorithm(&digest::SHA256);
145
146/// HMAC using SHA-384.
147pub static HMAC_SHA384: Algorithm = Algorithm(&digest::SHA384);
148
149/// HMAC using SHA-512.
150pub static HMAC_SHA512: Algorithm = Algorithm(&digest::SHA512);
151
152/// An HMAC tag.
153///
154/// For a given tag `t`, use `t.as_ref()` to get the tag value as a byte slice.
155#[derive(Clone, Copy, Debug)]
156pub struct Tag {
157    msg: [u8; digest::MAX_OUTPUT_LEN],
158    msg_len: usize,
159}
160
161impl AsRef<[u8]> for Tag {
162    #[inline]
163    fn as_ref(&self) -> &[u8] {
164        &self.msg[..self.msg_len]
165    }
166}
167
168struct LcHmacCtx(HMAC_CTX);
169
170impl LcHmacCtx {
171    fn as_mut_ptr(&mut self) -> *mut HMAC_CTX {
172        &mut self.0
173    }
174    fn as_ptr(&self) -> *const HMAC_CTX {
175        &self.0
176    }
177
178    fn try_clone(&self) -> Result<Self, Unspecified> {
179        unsafe {
180            let mut hmac_ctx = MaybeUninit::<HMAC_CTX>::uninit();
181            HMAC_CTX_init(hmac_ctx.as_mut_ptr());
182            let mut hmac_ctx = hmac_ctx.assume_init();
183            if 1 != HMAC_CTX_copy_ex(&mut hmac_ctx, self.as_ptr()) {
184                return Err(Unspecified);
185            }
186            Ok(LcHmacCtx(hmac_ctx))
187        }
188    }
189}
190unsafe impl Send for LcHmacCtx {}
191
192impl Drop for LcHmacCtx {
193    fn drop(&mut self) {
194        unsafe { HMAC_CTX_cleanup(self.as_mut_ptr()) }
195    }
196}
197
198impl Clone for LcHmacCtx {
199    fn clone(&self) -> Self {
200        self.try_clone().expect("Unable to clone LcHmacCtx")
201    }
202}
203
204/// A key to use for HMAC signing.
205//
206// # FIPS
207// Use this type with one of the following algorithms:
208// * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
209// * `HMAC_SHA224`
210// * `HMAC_SHA256`
211// * `HMAC_SHA384`
212// * `HMAC_SHA512`
213#[derive(Clone)]
214pub struct Key {
215    pub(crate) algorithm: Algorithm,
216    ctx: LcHmacCtx,
217}
218
219unsafe impl Send for Key {}
220// All uses of *mut HMAC_CTX require the creation of a Context, which will clone the Key.
221unsafe impl Sync for Key {}
222
223#[allow(clippy::missing_fields_in_debug)]
224impl core::fmt::Debug for Key {
225    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
226        f.debug_struct("Key")
227            .field("algorithm", &self.algorithm.digest_algorithm())
228            .finish()
229    }
230}
231
232impl Key {
233    /// Generate an HMAC signing key using the given digest algorithm with a
234    /// random value generated from `rng`.
235    ///
236    /// The key will be `digest_alg.output_len` bytes long, based on the
237    /// recommendation in [RFC 2104 Section 3].
238    ///
239    /// [RFC 2104 Section 3]: https://tools.ietf.org/html/rfc2104#section-3
240    ///
241    //
242    // # FIPS
243    // Use this function with one of the following algorithms:
244    // * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
245    // * `HMAC_SHA224`
246    // * `HMAC_SHA256`
247    // * `HMAC_SHA384`
248    // * `HMAC_SHA512`
249    //
250    /// # Errors
251    /// `error::Unspecified` is the `rng` fails.
252    pub fn generate(
253        algorithm: Algorithm,
254        rng: &dyn crate::rand::SecureRandom,
255    ) -> Result<Self, Unspecified> {
256        Self::construct(algorithm, |buf| rng.fill(buf))
257    }
258
259    fn construct<F>(algorithm: Algorithm, fill: F) -> Result<Self, Unspecified>
260    where
261        F: FnOnce(&mut [u8]) -> Result<(), Unspecified>,
262    {
263        let mut key_bytes = [0; digest::MAX_OUTPUT_LEN];
264        let key_bytes = &mut key_bytes[..algorithm.0.output_len];
265        fill(key_bytes)?;
266        Ok(Self::new(algorithm, key_bytes))
267    }
268
269    /// Construct an HMAC signing key using the given digest algorithm and key
270    /// value.
271    ///
272    /// `key_value` should be a value generated using a secure random number
273    /// generator (e.g. the `key_value` output by
274    /// `SealingKey::generate_serializable()`) or derived from a random key by
275    /// a key derivation function (e.g. `aws_lc_rs::hkdf`). In particular,
276    /// `key_value` shouldn't be a password.
277    ///
278    /// As specified in RFC 2104, if `key_value` is shorter than the digest
279    /// algorithm's block length (as returned by `digest::Algorithm::block_len`,
280    /// not the digest length returned by `digest::Algorithm::output_len`) then
281    /// it will be padded with zeros. Similarly, if it is longer than the block
282    /// length then it will be compressed using the digest algorithm.
283    ///
284    /// You should not use keys larger than the `digest_alg.block_len` because
285    /// the truncation described above reduces their strength to only
286    /// `digest_alg.output_len * 8` bits.
287    ///
288    /// # Panics
289    /// Panics if the HMAC context cannot be constructed
290    #[inline]
291    #[must_use]
292    pub fn new(algorithm: Algorithm, key_value: &[u8]) -> Self {
293        Key::try_new(algorithm, key_value).expect("Unable to create HmacContext")
294    }
295
296    fn try_new(algorithm: Algorithm, key_value: &[u8]) -> Result<Self, Unspecified> {
297        unsafe {
298            let mut ctx = MaybeUninit::<HMAC_CTX>::uninit();
299            HMAC_CTX_init(ctx.as_mut_ptr());
300            let evp_md_type = digest::match_digest_type(&algorithm.digest_algorithm().id);
301            if 1 != HMAC_Init_ex(
302                ctx.as_mut_ptr(),
303                key_value.as_ptr().cast(),
304                key_value.len(),
305                *evp_md_type,
306                null_mut(),
307            ) {
308                return Err(Unspecified);
309            }
310            let result = Self {
311                algorithm,
312                ctx: LcHmacCtx(ctx.assume_init()),
313            };
314            Ok(result)
315        }
316    }
317
318    unsafe fn get_hmac_ctx_ptr(&mut self) -> *mut HMAC_CTX {
319        self.ctx.as_mut_ptr()
320    }
321
322    /// The digest algorithm for the key.
323    #[inline]
324    #[must_use]
325    pub fn algorithm(&self) -> Algorithm {
326        Algorithm(self.algorithm.digest_algorithm())
327    }
328}
329
330impl hkdf::KeyType for Algorithm {
331    #[inline]
332    fn len(&self) -> usize {
333        self.digest_algorithm().output_len
334    }
335}
336
337impl From<hkdf::Okm<'_, Algorithm>> for Key {
338    fn from(okm: hkdf::Okm<Algorithm>) -> Self {
339        Self::construct(*okm.len(), |buf| okm.fill(buf)).unwrap()
340    }
341}
342
343/// A context for multi-step (Init-Update-Finish) HMAC signing.
344///
345/// Use `sign` for single-step HMAC signing.
346pub struct Context {
347    key: Key,
348}
349
350impl Clone for Context {
351    fn clone(&self) -> Self {
352        Self {
353            key: self.key.clone(),
354        }
355    }
356}
357
358unsafe impl Send for Context {}
359
360impl core::fmt::Debug for Context {
361    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
362        f.debug_struct("Context")
363            .field("algorithm", &self.key.algorithm.digest_algorithm())
364            .finish()
365    }
366}
367
368impl Context {
369    /// Constructs a new HMAC signing context using the given digest algorithm
370    /// and key.
371    #[inline]
372    #[must_use]
373    pub fn with_key(signing_key: &Key) -> Self {
374        Self {
375            key: signing_key.clone(),
376        }
377    }
378
379    /// Updates the HMAC with all the data in `data`. `update` may be called
380    /// zero or more times until `finish` is called.
381    ///
382    /// # Panics
383    /// Panics if the HMAC cannot be updated
384    #[inline]
385    pub fn update(&mut self, data: &[u8]) {
386        Self::try_update(self, data).expect("HMAC_Update failed");
387    }
388
389    #[inline]
390    fn try_update(&mut self, data: &[u8]) -> Result<(), Unspecified> {
391        unsafe {
392            if 1 != HMAC_Update(self.key.get_hmac_ctx_ptr(), data.as_ptr(), data.len()) {
393                return Err(Unspecified);
394            }
395        }
396        Ok(())
397    }
398
399    /// Finalizes the HMAC calculation and returns the HMAC value. `sign`
400    /// consumes the context so it cannot be (mis-)used after `sign` has been
401    /// called.
402    ///
403    /// It is generally not safe to implement HMAC verification by comparing
404    /// the return value of `sign` to a tag. Use `verify` for verification
405    /// instead.
406    ///
407    // # FIPS
408    // Use this method with one of the following algorithms:
409    // * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
410    // * `HMAC_SHA224`
411    // * `HMAC_SHA256`
412    // * `HMAC_SHA384`
413    // * `HMAC_SHA512`
414    //
415    /// # Panics
416    /// Panics if the HMAC calculation cannot be finalized
417    #[inline]
418    #[must_use]
419    pub fn sign(self) -> Tag {
420        Self::try_sign(self).expect("HMAC_Final failed")
421    }
422    #[inline]
423    fn try_sign(mut self) -> Result<Tag, Unspecified> {
424        let mut output = [0u8; digest::MAX_OUTPUT_LEN];
425        let mut out_len = MaybeUninit::<c_uint>::uninit();
426        unsafe {
427            if 1 != indicator_check!(HMAC_Final(
428                self.key.get_hmac_ctx_ptr(),
429                output.as_mut_ptr(),
430                out_len.as_mut_ptr(),
431            )) {
432                return Err(Unspecified);
433            }
434            Ok(Tag {
435                msg: output,
436                msg_len: out_len.assume_init() as usize,
437            })
438        }
439    }
440}
441
442/// Calculates the HMAC of `data` using the key `key` in one step.
443///
444/// Use `Context` to calculate HMACs where the input is in multiple parts.
445///
446/// It is generally not safe to implement HMAC verification by comparing the
447/// return value of `sign` to a tag. Use `verify` for verification instead.
448//
449// # FIPS
450// Use this function with one of the following algorithms:
451// * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
452// * `HMAC_SHA224`
453// * `HMAC_SHA256`
454// * `HMAC_SHA384`
455// * `HMAC_SHA512`
456#[inline]
457#[must_use]
458pub fn sign(key: &Key, data: &[u8]) -> Tag {
459    let mut ctx = Context::with_key(key);
460    ctx.update(data);
461    ctx.sign()
462}
463
464/// Calculates the HMAC of `data` using the signing key `key`, and verifies
465/// whether the resultant value equals `tag`, in one step.
466///
467/// This is logically equivalent to, but more efficient than, constructing a
468/// `Key` with the same value as `key` and then using `verify`.
469///
470/// The verification will be done in constant time to prevent timing attacks.
471///
472/// # Errors
473/// `error::Unspecified` if the inputs are not verified.
474//
475// # FIPS
476// Use this function with one of the following algorithms:
477// * `HMAC_SHA1_FOR_LEGACY_USE_ONLY`
478// * `HMAC_SHA224`
479// * `HMAC_SHA256`
480// * `HMAC_SHA384`
481// * `HMAC_SHA512`
482#[inline]
483pub fn verify(key: &Key, data: &[u8], tag: &[u8]) -> Result<(), Unspecified> {
484    constant_time::verify_slices_are_equal(sign(key, data).as_ref(), tag)
485}
486
487#[cfg(test)]
488mod tests {
489    use crate::{hmac, rand};
490
491    #[cfg(feature = "fips")]
492    mod fips;
493
494    // Make sure that `Key::generate` and `verify_with_own_key` aren't
495    // completely wacky.
496    #[test]
497    pub fn hmac_signing_key_coverage() {
498        const HELLO_WORLD_GOOD: &[u8] = b"hello, world";
499        const HELLO_WORLD_BAD: &[u8] = b"hello, worle";
500
501        let rng = rand::SystemRandom::new();
502
503        for algorithm in &[
504            hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
505            hmac::HMAC_SHA224,
506            hmac::HMAC_SHA256,
507            hmac::HMAC_SHA384,
508            hmac::HMAC_SHA512,
509        ] {
510            let key = hmac::Key::generate(*algorithm, &rng).unwrap();
511            let tag = hmac::sign(&key, HELLO_WORLD_GOOD);
512            println!("{key:?}");
513            assert!(hmac::verify(&key, HELLO_WORLD_GOOD, tag.as_ref()).is_ok());
514            assert!(hmac::verify(&key, HELLO_WORLD_BAD, tag.as_ref()).is_err());
515        }
516    }
517
518    #[test]
519    fn hmac_coverage() {
520        // Something would have gone horribly wrong for this to not pass, but we test this so our
521        // coverage reports will look better.
522        assert_ne!(hmac::HMAC_SHA256, hmac::HMAC_SHA384);
523
524        for &alg in &[
525            hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
526            hmac::HMAC_SHA224,
527            hmac::HMAC_SHA256,
528            hmac::HMAC_SHA384,
529            hmac::HMAC_SHA512,
530        ] {
531            // Clone after updating context with message, then check if the final Tag is the same.
532            let key = hmac::Key::new(alg, &[0; 32]);
533            let mut ctx = hmac::Context::with_key(&key);
534            ctx.update(b"hello, world");
535            let ctx_clone = ctx.clone();
536
537            let orig_tag = ctx.sign();
538            let clone_tag = ctx_clone.sign();
539            assert_eq!(orig_tag.as_ref(), clone_tag.as_ref());
540            assert_eq!(orig_tag.clone().as_ref(), clone_tag.as_ref());
541        }
542    }
543}