Coverage Report

Created: 2024-12-17 06:15

/rust/registry/src/index.crates.io-6f17d22bba15001f/ring-0.17.8/src/hmac.rs
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2015-2016 Brian Smith.
2
//
3
// Permission to use, copy, modify, and/or distribute this software for any
4
// purpose with or without fee is hereby granted, provided that the above
5
// copyright notice and this permission notice appear in all copies.
6
//
7
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15
//! HMAC is specified in [RFC 2104].
16
//!
17
//! After a `Key` is constructed, it can be used for multiple signing or
18
//! verification operations. Separating the construction of the key from the
19
//! rest of the HMAC operation allows the per-key precomputation to be done
20
//! only once, instead of it being done in every HMAC operation.
21
//!
22
//! Frequently all the data to be signed in a message is available in a single
23
//! contiguous piece. In that case, the module-level `sign` function can be
24
//! used. Otherwise, if the input is in multiple parts, `Context` should be
25
//! used.
26
//!
27
//! # Examples:
28
//!
29
//! ## Signing a value and verifying it wasn't tampered with
30
//!
31
//! ```
32
//! use ring::{hmac, rand};
33
//!
34
//! let rng = rand::SystemRandom::new();
35
//! let key = hmac::Key::generate(hmac::HMAC_SHA256, &rng)?;
36
//!
37
//! let msg = "hello, world";
38
//!
39
//! let tag = hmac::sign(&key, msg.as_bytes());
40
//!
41
//! // [We give access to the message to an untrusted party, and they give it
42
//! // back to us. We need to verify they didn't tamper with it.]
43
//!
44
//! hmac::verify(&key, msg.as_bytes(), tag.as_ref())?;
45
//!
46
//! # Ok::<(), ring::error::Unspecified>(())
47
//! ```
48
//!
49
//! ## Using the one-shot API:
50
//!
51
//! ```
52
//! use ring::{digest, hmac, rand};
53
//! use ring::rand::SecureRandom;
54
//!
55
//! let msg = "hello, world";
56
//!
57
//! // The sender generates a secure key value and signs the message with it.
58
//! // Note that in a real protocol, a key agreement protocol would be used to
59
//! // derive `key_value`.
60
//! let rng = rand::SystemRandom::new();
61
//! let key_value: [u8; digest::SHA256_OUTPUT_LEN] = rand::generate(&rng)?.expose();
62
//!
63
//! let s_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref());
64
//! let tag = hmac::sign(&s_key, msg.as_bytes());
65
//!
66
//! // The receiver (somehow!) knows the key value, and uses it to verify the
67
//! // integrity of the message.
68
//! let v_key = hmac::Key::new(hmac::HMAC_SHA256, key_value.as_ref());
69
//! hmac::verify(&v_key, msg.as_bytes(), tag.as_ref())?;
70
//!
71
//! # Ok::<(), ring::error::Unspecified>(())
72
//! ```
73
//!
74
//! ## Using the multi-part API:
75
//! ```
76
//! use ring::{digest, hmac, rand};
77
//! use ring::rand::SecureRandom;
78
//!
79
//! let parts = ["hello", ", ", "world"];
80
//!
81
//! // The sender generates a secure key value and signs the message with it.
82
//! // Note that in a real protocol, a key agreement protocol would be used to
83
//! // derive `key_value`.
84
//! let rng = rand::SystemRandom::new();
85
//! let mut key_value: [u8; digest::SHA384_OUTPUT_LEN] = rand::generate(&rng)?.expose();
86
//!
87
//! let s_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref());
88
//! let mut s_ctx = hmac::Context::with_key(&s_key);
89
//! for part in &parts {
90
//!     s_ctx.update(part.as_bytes());
91
//! }
92
//! let tag = s_ctx.sign();
93
//!
94
//! // The receiver (somehow!) knows the key value, and uses it to verify the
95
//! // integrity of the message.
96
//! let v_key = hmac::Key::new(hmac::HMAC_SHA384, key_value.as_ref());
97
//! let mut msg = Vec::<u8>::new();
98
//! for part in &parts {
99
//!     msg.extend(part.as_bytes());
100
//! }
101
//! hmac::verify(&v_key, &msg.as_ref(), tag.as_ref())?;
102
//!
103
//! # Ok::<(), ring::error::Unspecified>(())
104
//! ```
105
//!
106
//! [RFC 2104]: https://tools.ietf.org/html/rfc2104
107
//! [code for `ring::pbkdf2`]:
108
//!     https://github.com/briansmith/ring/blob/main/src/pbkdf2.rs
109
//! [code for `ring::hkdf`]:
110
//!     https://github.com/briansmith/ring/blob/main/src/hkdf.rs
111
112
use crate::{constant_time, digest, error, hkdf, rand};
113
114
/// An HMAC algorithm.
115
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116
pub struct Algorithm(&'static digest::Algorithm);
117
118
impl Algorithm {
119
    /// The digest algorithm this HMAC algorithm is based on.
120
    #[inline]
121
0
    pub fn digest_algorithm(&self) -> &'static digest::Algorithm {
122
0
        self.0
123
0
    }
Unexecuted instantiation: <ring::hmac::Algorithm>::digest_algorithm
Unexecuted instantiation: <ring::hmac::Algorithm>::digest_algorithm
124
}
125
126
/// HMAC using SHA-1. Obsolete.
127
pub static HMAC_SHA1_FOR_LEGACY_USE_ONLY: Algorithm = Algorithm(&digest::SHA1_FOR_LEGACY_USE_ONLY);
128
129
/// HMAC using SHA-256.
130
pub static HMAC_SHA256: Algorithm = Algorithm(&digest::SHA256);
131
132
/// HMAC using SHA-384.
133
pub static HMAC_SHA384: Algorithm = Algorithm(&digest::SHA384);
134
135
/// HMAC using SHA-512.
136
pub static HMAC_SHA512: Algorithm = Algorithm(&digest::SHA512);
137
138
/// An HMAC tag.
139
///
140
/// For a given tag `t`, use `t.as_ref()` to get the tag value as a byte slice.
141
#[derive(Clone, Copy, Debug)]
142
pub struct Tag(digest::Digest);
143
144
impl AsRef<[u8]> for Tag {
145
    #[inline]
146
0
    fn as_ref(&self) -> &[u8] {
147
0
        self.0.as_ref()
148
0
    }
Unexecuted instantiation: <ring::hmac::Tag as core::convert::AsRef<[u8]>>::as_ref
Unexecuted instantiation: <ring::hmac::Tag as core::convert::AsRef<[u8]>>::as_ref
149
}
150
151
/// A key to use for HMAC signing.
152
#[derive(Clone)]
153
pub struct Key {
154
    inner: digest::BlockContext,
155
    outer: digest::BlockContext,
156
}
157
158
impl core::fmt::Debug for Key {
159
0
    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
160
0
        f.debug_struct("Key")
161
0
            .field("algorithm", self.algorithm().digest_algorithm())
162
0
            .finish()
163
0
    }
164
}
165
166
impl Key {
167
    /// Generate an HMAC signing key using the given digest algorithm with a
168
    /// random value generated from `rng`.
169
    ///
170
    /// The key will be `digest_alg.output_len` bytes long, based on the
171
    /// recommendation in [RFC 2104 Section 3].
172
    ///
173
    /// [RFC 2104 Section 3]: https://tools.ietf.org/html/rfc2104#section-3
174
0
    pub fn generate(
175
0
        algorithm: Algorithm,
176
0
        rng: &dyn rand::SecureRandom,
177
0
    ) -> Result<Self, error::Unspecified> {
178
0
        Self::construct(algorithm, |buf| rng.fill(buf))
179
0
    }
180
181
0
    fn construct<F>(algorithm: Algorithm, fill: F) -> Result<Self, error::Unspecified>
182
0
    where
183
0
        F: FnOnce(&mut [u8]) -> Result<(), error::Unspecified>,
184
0
    {
185
0
        let mut key_bytes = [0; digest::MAX_OUTPUT_LEN];
186
0
        let key_bytes = &mut key_bytes[..algorithm.0.output_len()];
187
0
        fill(key_bytes)?;
188
0
        Ok(Self::new(algorithm, key_bytes))
189
0
    }
Unexecuted instantiation: <ring::hmac::Key>::construct::<<ring::hmac::Key>::generate::{closure#0}>
Unexecuted instantiation: <ring::hmac::Key>::construct::<<ring::hmac::Key as core::convert::From<ring::hkdf::Okm<ring::hmac::Algorithm>>>::from::{closure#0}>
190
191
    /// Construct an HMAC signing key using the given digest algorithm and key
192
    /// value.
193
    ///
194
    /// `key_value` should be a value generated using a secure random number
195
    /// generator (e.g. the `key_value` output by
196
    /// `SealingKey::generate_serializable()`) or derived from a random key by
197
    /// a key derivation function (e.g. `ring::hkdf`). In particular,
198
    /// `key_value` shouldn't be a password.
199
    ///
200
    /// As specified in RFC 2104, if `key_value` is shorter than the digest
201
    /// algorithm's block length (as returned by `digest::Algorithm::block_len()`,
202
    /// not the digest length returned by `digest::Algorithm::output_len()`) then
203
    /// it will be padded with zeros. Similarly, if it is longer than the block
204
    /// length then it will be compressed using the digest algorithm.
205
    ///
206
    /// You should not use keys larger than the `digest_alg.block_len` because
207
    /// the truncation described above reduces their strength to only
208
    /// `digest_alg.output_len * 8` bits. Support for such keys is likely to be
209
    /// removed in a future version of *ring*.
210
0
    pub fn new(algorithm: Algorithm, key_value: &[u8]) -> Self {
211
0
        let digest_alg = algorithm.0;
212
0
        let mut key = Self {
213
0
            inner: digest::BlockContext::new(digest_alg),
214
0
            outer: digest::BlockContext::new(digest_alg),
215
0
        };
216
0
217
0
        let block_len = digest_alg.block_len();
218
219
        let key_hash;
220
0
        let key_value = if key_value.len() <= block_len {
221
0
            key_value
222
        } else {
223
0
            key_hash = digest::digest(digest_alg, key_value);
224
0
            key_hash.as_ref()
225
        };
226
227
        const IPAD: u8 = 0x36;
228
229
0
        let mut padded_key = [IPAD; digest::MAX_BLOCK_LEN];
230
0
        let padded_key = &mut padded_key[..block_len];
231
232
        // If the key is shorter than one block then we're supposed to act like
233
        // it is padded with zero bytes up to the block length. `x ^ 0 == x` so
234
        // we can just leave the trailing bytes of `padded_key` untouched.
235
0
        for (padded_key, key_value) in padded_key.iter_mut().zip(key_value.iter()) {
236
0
            *padded_key ^= *key_value;
237
0
        }
238
0
        key.inner.update(padded_key);
239
240
        const OPAD: u8 = 0x5C;
241
242
        // Remove the `IPAD` masking, leaving the unmasked padded key, then
243
        // mask with `OPAD`, all in one step.
244
0
        for b in padded_key.iter_mut() {
245
0
            *b ^= IPAD ^ OPAD;
246
0
        }
247
0
        key.outer.update(padded_key);
248
0
249
0
        key
250
0
    }
251
252
    /// The digest algorithm for the key.
253
    #[inline]
254
0
    pub fn algorithm(&self) -> Algorithm {
255
0
        Algorithm(self.inner.algorithm)
256
0
    }
Unexecuted instantiation: <ring::hmac::Key>::algorithm
Unexecuted instantiation: <ring::hmac::Key>::algorithm
257
}
258
259
impl hkdf::KeyType for Algorithm {
260
0
    fn len(&self) -> usize {
261
0
        self.digest_algorithm().output_len()
262
0
    }
263
}
264
265
impl From<hkdf::Okm<'_, Algorithm>> for Key {
266
0
    fn from(okm: hkdf::Okm<Algorithm>) -> Self {
267
0
        Self::construct(*okm.len(), |buf| okm.fill(buf)).unwrap()
268
0
    }
269
}
270
271
/// A context for multi-step (Init-Update-Finish) HMAC signing.
272
///
273
/// Use `sign` for single-step HMAC signing.
274
#[derive(Clone)]
275
pub struct Context {
276
    inner: digest::Context,
277
    outer: digest::BlockContext,
278
}
279
280
impl core::fmt::Debug for Context {
281
0
    fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
282
0
        f.debug_struct("Context")
283
0
            .field("algorithm", self.inner.algorithm())
284
0
            .finish()
285
0
    }
286
}
287
288
impl Context {
289
    /// Constructs a new HMAC signing context using the given digest algorithm
290
    /// and key.
291
0
    pub fn with_key(signing_key: &Key) -> Self {
292
0
        Self {
293
0
            inner: digest::Context::clone_from(&signing_key.inner),
294
0
            outer: signing_key.outer.clone(),
295
0
        }
296
0
    }
297
298
    /// Updates the HMAC with all the data in `data`. `update` may be called
299
    /// zero or more times until `finish` is called.
300
0
    pub fn update(&mut self, data: &[u8]) {
301
0
        self.inner.update(data);
302
0
    }
303
304
    /// Finalizes the HMAC calculation and returns the HMAC value. `sign`
305
    /// consumes the context so it cannot be (mis-)used after `sign` has been
306
    /// called.
307
    ///
308
    /// It is generally not safe to implement HMAC verification by comparing
309
    /// the return value of `sign` to a tag. Use `verify` for verification
310
    /// instead.
311
0
    pub fn sign(self) -> Tag {
312
0
        let algorithm = self.inner.algorithm();
313
0
        let mut pending = [0u8; digest::MAX_BLOCK_LEN];
314
0
        let pending = &mut pending[..algorithm.block_len()];
315
0
        let num_pending = algorithm.output_len();
316
0
        pending[..num_pending].copy_from_slice(self.inner.finish().as_ref());
317
0
        Tag(self.outer.finish(pending, num_pending))
318
0
    }
319
}
320
321
/// Calculates the HMAC of `data` using the key `key` in one step.
322
///
323
/// Use `Context` to calculate HMACs where the input is in multiple parts.
324
///
325
/// It is generally not safe to implement HMAC verification by comparing the
326
/// return value of `sign` to a tag. Use `verify` for verification instead.
327
0
pub fn sign(key: &Key, data: &[u8]) -> Tag {
328
0
    let mut ctx = Context::with_key(key);
329
0
    ctx.update(data);
330
0
    ctx.sign()
331
0
}
332
333
/// Calculates the HMAC of `data` using the signing key `key`, and verifies
334
/// whether the resultant value equals `tag`, in one step.
335
///
336
/// This is logically equivalent to, but more efficient than, constructing a
337
/// `Key` with the same value as `key` and then using `verify`.
338
///
339
/// The verification will be done in constant time to prevent timing attacks.
340
0
pub fn verify(key: &Key, data: &[u8], tag: &[u8]) -> Result<(), error::Unspecified> {
341
0
    constant_time::verify_slices_are_equal(sign(key, data).as_ref(), tag)
342
0
}
343
344
#[cfg(test)]
345
mod tests {
346
    use crate::{hmac, rand};
347
348
    // Make sure that `Key::generate` and `verify_with_own_key` aren't
349
    // completely wacky.
350
    #[test]
351
    pub fn hmac_signing_key_coverage() {
352
        let rng = rand::SystemRandom::new();
353
354
        const HELLO_WORLD_GOOD: &[u8] = b"hello, world";
355
        const HELLO_WORLD_BAD: &[u8] = b"hello, worle";
356
357
        for algorithm in &[
358
            hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
359
            hmac::HMAC_SHA256,
360
            hmac::HMAC_SHA384,
361
            hmac::HMAC_SHA512,
362
        ] {
363
            let key = hmac::Key::generate(*algorithm, &rng).unwrap();
364
            let tag = hmac::sign(&key, HELLO_WORLD_GOOD);
365
            assert!(hmac::verify(&key, HELLO_WORLD_GOOD, tag.as_ref()).is_ok());
366
            assert!(hmac::verify(&key, HELLO_WORLD_BAD, tag.as_ref()).is_err())
367
        }
368
    }
369
}