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::{ |
113 | constant_time, cpu, |
114 | digest::{self, Digest, FinishError}, |
115 | error, hkdf, rand, |
116 | }; |
117 | |
118 | pub(crate) use crate::digest::InputTooLongError; |
119 | |
120 | /// An HMAC algorithm. |
121 | #[derive (Clone, Copy, Debug, PartialEq, Eq)] |
122 | pub struct Algorithm(&'static digest::Algorithm); |
123 | |
124 | impl Algorithm { |
125 | /// The digest algorithm this HMAC algorithm is based on. |
126 | #[inline ] |
127 | pub fn digest_algorithm(&self) -> &'static digest::Algorithm { |
128 | self.0 |
129 | } |
130 | } |
131 | |
132 | /// HMAC using SHA-1. Obsolete. |
133 | pub static HMAC_SHA1_FOR_LEGACY_USE_ONLY: Algorithm = Algorithm(&digest::SHA1_FOR_LEGACY_USE_ONLY); |
134 | |
135 | /// HMAC using SHA-256. |
136 | pub static HMAC_SHA256: Algorithm = Algorithm(&digest::SHA256); |
137 | |
138 | /// HMAC using SHA-384. |
139 | pub static HMAC_SHA384: Algorithm = Algorithm(&digest::SHA384); |
140 | |
141 | /// HMAC using SHA-512. |
142 | pub static HMAC_SHA512: Algorithm = Algorithm(&digest::SHA512); |
143 | |
144 | /// An HMAC tag. |
145 | /// |
146 | /// For a given tag `t`, use `t.as_ref()` to get the tag value as a byte slice. |
147 | #[derive (Clone, Copy, Debug)] |
148 | pub struct Tag(Digest); |
149 | |
150 | impl AsRef<[u8]> for Tag { |
151 | #[inline ] |
152 | fn as_ref(&self) -> &[u8] { |
153 | self.0.as_ref() |
154 | } |
155 | } |
156 | |
157 | /// A key to use for HMAC signing. |
158 | #[derive (Clone)] |
159 | pub struct Key { |
160 | inner: digest::BlockContext, |
161 | outer: digest::BlockContext, |
162 | } |
163 | |
164 | impl core::fmt::Debug for Key { |
165 | fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { |
166 | f&mut DebugStruct<'_, '_>.debug_struct("Key" ) |
167 | .field(name:"algorithm" , self.algorithm().digest_algorithm()) |
168 | .finish() |
169 | } |
170 | } |
171 | |
172 | impl Key { |
173 | /// Generate an HMAC signing key using the given digest algorithm with a |
174 | /// random value generated from `rng`. |
175 | /// |
176 | /// The key will be `digest_alg.output_len` bytes long, based on the |
177 | /// recommendation in [RFC 2104 Section 3]. |
178 | /// |
179 | /// [RFC 2104 Section 3]: https://tools.ietf.org/html/rfc2104#section-3 |
180 | pub fn generate( |
181 | algorithm: Algorithm, |
182 | rng: &dyn rand::SecureRandom, |
183 | ) -> Result<Self, error::Unspecified> { |
184 | Self::construct(algorithm, |buf| rng.fill(buf), cpu::features()) |
185 | } |
186 | |
187 | fn construct<F>( |
188 | algorithm: Algorithm, |
189 | fill: F, |
190 | cpu: cpu::Features, |
191 | ) -> Result<Self, error::Unspecified> |
192 | where |
193 | F: FnOnce(&mut [u8]) -> Result<(), error::Unspecified>, |
194 | { |
195 | let mut key_bytes = [0; digest::MAX_OUTPUT_LEN]; |
196 | let key_bytes = &mut key_bytes[..algorithm.0.output_len()]; |
197 | fill(key_bytes)?; |
198 | Self::try_new(algorithm, key_bytes, cpu).map_err(error::erase::<InputTooLongError>) |
199 | } |
200 | |
201 | /// Construct an HMAC signing key using the given digest algorithm and key |
202 | /// value. |
203 | /// |
204 | /// `key_value` should be a value generated using a secure random number |
205 | /// generator (e.g. the `key_value` output by |
206 | /// `SealingKey::generate_serializable()`) or derived from a random key by |
207 | /// a key derivation function (e.g. `ring::hkdf`). In particular, |
208 | /// `key_value` shouldn't be a password. |
209 | /// |
210 | /// As specified in RFC 2104, if `key_value` is shorter than the digest |
211 | /// algorithm's block length (as returned by `digest::Algorithm::block_len()`, |
212 | /// not the digest length returned by `digest::Algorithm::output_len()`) then |
213 | /// it will be padded with zeros. Similarly, if it is longer than the block |
214 | /// length then it will be compressed using the digest algorithm. |
215 | /// |
216 | /// You should not use keys larger than the `digest_alg.block_len` because |
217 | /// the truncation described above reduces their strength to only |
218 | /// `digest_alg.output_len * 8` bits. Support for such keys is likely to be |
219 | /// removed in a future version of *ring*. |
220 | pub fn new(algorithm: Algorithm, key_value: &[u8]) -> Self { |
221 | Self::try_new(algorithm, key_value, cpu::features()) |
222 | .map_err(error::erase::<InputTooLongError>) |
223 | .unwrap() |
224 | } |
225 | |
226 | pub(crate) fn try_new( |
227 | algorithm: Algorithm, |
228 | key_value: &[u8], |
229 | cpu_features: cpu::Features, |
230 | ) -> Result<Self, InputTooLongError> { |
231 | let digest_alg = algorithm.0; |
232 | let mut key = Self { |
233 | inner: digest::BlockContext::new(digest_alg), |
234 | outer: digest::BlockContext::new(digest_alg), |
235 | }; |
236 | |
237 | let block_len = digest_alg.block_len(); |
238 | |
239 | let key_hash; |
240 | let key_value = if key_value.len() <= block_len { |
241 | key_value |
242 | } else { |
243 | key_hash = Digest::compute_from(digest_alg, key_value, cpu_features)?; |
244 | key_hash.as_ref() |
245 | }; |
246 | |
247 | const IPAD: u8 = 0x36; |
248 | |
249 | let mut padded_key = [IPAD; digest::MAX_BLOCK_LEN]; |
250 | let padded_key = &mut padded_key[..block_len]; |
251 | |
252 | // If the key is shorter than one block then we're supposed to act like |
253 | // it is padded with zero bytes up to the block length. `x ^ 0 == x` so |
254 | // we can just leave the trailing bytes of `padded_key` untouched. |
255 | constant_time::xor_assign_at_start(&mut padded_key[..], key_value); |
256 | |
257 | let leftover = key.inner.update(padded_key, cpu_features); |
258 | debug_assert_eq!(leftover.len(), 0); |
259 | |
260 | const OPAD: u8 = 0x5C; |
261 | |
262 | // Remove the `IPAD` masking, leaving the unmasked padded key, then |
263 | // mask with `OPAD`, all in one step. |
264 | constant_time::xor_assign(&mut padded_key[..], IPAD ^ OPAD); |
265 | let leftover = key.outer.update(padded_key, cpu_features); |
266 | debug_assert_eq!(leftover.len(), 0); |
267 | |
268 | Ok(key) |
269 | } |
270 | |
271 | /// The digest algorithm for the key. |
272 | #[inline ] |
273 | pub fn algorithm(&self) -> Algorithm { |
274 | Algorithm(self.inner.algorithm) |
275 | } |
276 | |
277 | pub(crate) fn sign(&self, data: &[u8], cpu: cpu::Features) -> Result<Tag, InputTooLongError> { |
278 | let mut ctx = Context::with_key(self); |
279 | ctx.update(data); |
280 | ctx.try_sign(cpu) |
281 | } |
282 | |
283 | fn verify(&self, data: &[u8], tag: &[u8], cpu: cpu::Features) -> Result<(), VerifyError> { |
284 | let computed = self |
285 | .sign(data, cpu) |
286 | .map_err(VerifyError::InputTooLongError)?; |
287 | constant_time::verify_slices_are_equal(computed.as_ref(), tag) |
288 | .map_err(|_: error::Unspecified| VerifyError::Mismatch) |
289 | } |
290 | } |
291 | |
292 | impl hkdf::KeyType for Algorithm { |
293 | fn len(&self) -> usize { |
294 | self.digest_algorithm().output_len() |
295 | } |
296 | } |
297 | |
298 | impl From<hkdf::Okm<'_, Algorithm>> for Key { |
299 | fn from(okm: hkdf::Okm<Algorithm>) -> Self { |
300 | Self::construct(*okm.len(), |buf| okm.fill(buf), cpu:cpu::features()).unwrap() |
301 | } |
302 | } |
303 | |
304 | /// A context for multi-step (Init-Update-Finish) HMAC signing. |
305 | /// |
306 | /// Use `sign` for single-step HMAC signing. |
307 | #[derive (Clone)] |
308 | pub struct Context { |
309 | inner: digest::Context, |
310 | outer: digest::BlockContext, |
311 | } |
312 | |
313 | impl core::fmt::Debug for Context { |
314 | fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { |
315 | f&mut DebugStruct<'_, '_>.debug_struct("Context" ) |
316 | .field(name:"algorithm" , self.inner.algorithm()) |
317 | .finish() |
318 | } |
319 | } |
320 | |
321 | impl Context { |
322 | /// Constructs a new HMAC signing context using the given digest algorithm |
323 | /// and key. |
324 | pub fn with_key(signing_key: &Key) -> Self { |
325 | Self { |
326 | inner: digest::Context::clone_from(&signing_key.inner), |
327 | outer: signing_key.outer.clone(), |
328 | } |
329 | } |
330 | |
331 | /// Updates the HMAC with all the data in `data`. `update` may be called |
332 | /// zero or more times until `finish` is called. |
333 | pub fn update(&mut self, data: &[u8]) { |
334 | self.inner.update(data); |
335 | } |
336 | |
337 | /// Finalizes the HMAC calculation and returns the HMAC value. `sign` |
338 | /// consumes the context so it cannot be (mis-)used after `sign` has been |
339 | /// called. |
340 | /// |
341 | /// It is generally not safe to implement HMAC verification by comparing |
342 | /// the return value of `sign` to a tag. Use `verify` for verification |
343 | /// instead. |
344 | pub fn sign(self) -> Tag { |
345 | self.try_sign(cpu::features()) |
346 | .map_err(error::erase::<InputTooLongError>) |
347 | .unwrap() |
348 | } |
349 | |
350 | pub(crate) fn try_sign(self, cpu_features: cpu::Features) -> Result<Tag, InputTooLongError> { |
351 | // Consequently, `num_pending` is valid. |
352 | debug_assert_eq!(self.inner.algorithm(), self.outer.algorithm); |
353 | debug_assert!(self.inner.algorithm().output_len() < self.outer.algorithm.block_len()); |
354 | |
355 | let inner = self.inner.try_finish(cpu_features)?; |
356 | let inner = inner.as_ref(); |
357 | let num_pending = inner.len(); |
358 | let buffer = &mut [0u8; digest::MAX_BLOCK_LEN]; |
359 | const _BUFFER_IS_LARGE_ENOUGH_TO_HOLD_INNER: () = |
360 | assert!(digest::MAX_OUTPUT_LEN < digest::MAX_BLOCK_LEN); |
361 | buffer[..num_pending].copy_from_slice(inner); |
362 | |
363 | self.outer |
364 | .try_finish(buffer, num_pending, cpu_features) |
365 | .map(Tag) |
366 | .map_err(|err| match err { |
367 | FinishError::InputTooLong(i) => { |
368 | // Unreachable, as we gave the inner context exactly the |
369 | // same input we gave the outer context, and |
370 | // `inner.try_finish` already succeeded. However, it is |
371 | // quite difficult to prove this, and we already return |
372 | // `InputTooLongError`, so just forward it along. |
373 | i |
374 | } |
375 | FinishError::PendingNotAPartialBlock(_) => { |
376 | // Follows from the assertions above. |
377 | unreachable!() |
378 | } |
379 | }) |
380 | } |
381 | } |
382 | |
383 | /// Calculates the HMAC of `data` using the key `key` in one step. |
384 | /// |
385 | /// Use `Context` to calculate HMACs where the input is in multiple parts. |
386 | /// |
387 | /// It is generally not safe to implement HMAC verification by comparing the |
388 | /// return value of `sign` to a tag. Use `verify` for verification instead. |
389 | pub fn sign(key: &Key, data: &[u8]) -> Tag { |
390 | keyResult.sign(data, cpu::features()) |
391 | .map_err(op:error::erase::<InputTooLongError>) |
392 | .unwrap() |
393 | } |
394 | |
395 | /// Calculates the HMAC of `data` using the signing key `key`, and verifies |
396 | /// whether the resultant value equals `tag`, in one step. |
397 | /// |
398 | /// This is logically equivalent to, but more efficient than, constructing a |
399 | /// `Key` with the same value as `key` and then using `verify`. |
400 | /// |
401 | /// The verification will be done in constant time to prevent timing attacks. |
402 | pub fn verify(key: &Key, data: &[u8], tag: &[u8]) -> Result<(), error::Unspecified> { |
403 | key.verify(data, tag, cpu::features()) |
404 | .map_err(|_: VerifyError| error::Unspecified) |
405 | } |
406 | |
407 | enum VerifyError { |
408 | // Theoretically somebody could have calculated a valid tag with a gigantic |
409 | // input that we do not support. If we were to support every theoretically |
410 | // valid input length, for *every* digest algorithm, then we could argue |
411 | // that hitting the input length limit implies a mismatch since nobody |
412 | // could have calculated such a tag with the given input. |
413 | #[allow (dead_code)] |
414 | InputTooLongError(InputTooLongError), |
415 | |
416 | Mismatch, |
417 | } |
418 | |
419 | #[cfg (test)] |
420 | mod tests { |
421 | use crate::{hmac, rand}; |
422 | |
423 | // Make sure that `Key::generate` and `verify_with_own_key` aren't |
424 | // completely wacky. |
425 | #[test ] |
426 | pub fn hmac_signing_key_coverage() { |
427 | let rng = rand::SystemRandom::new(); |
428 | |
429 | const HELLO_WORLD_GOOD: &[u8] = b"hello, world" ; |
430 | const HELLO_WORLD_BAD: &[u8] = b"hello, worle" ; |
431 | |
432 | for algorithm in &[ |
433 | hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, |
434 | hmac::HMAC_SHA256, |
435 | hmac::HMAC_SHA384, |
436 | hmac::HMAC_SHA512, |
437 | ] { |
438 | let key = hmac::Key::generate(*algorithm, &rng).unwrap(); |
439 | let tag = hmac::sign(&key, HELLO_WORLD_GOOD); |
440 | assert!(hmac::verify(&key, HELLO_WORLD_GOOD, tag.as_ref()).is_ok()); |
441 | assert!(hmac::verify(&key, HELLO_WORLD_BAD, tag.as_ref()).is_err()) |
442 | } |
443 | } |
444 | } |
445 | |