Skip to main content

esp_hal/
hmac.rs

1//! # Hash-based Message Authentication Code (HMAC) Accelerator
2//!
3//! ## Overview
4//! HMAC is a secure authentication technique that verifies the authenticity and
5//! integrity of a message with a pre-shared key. This module provides hardware
6//! acceleration for SHA256-HMAC generation using a key burned into an eFuse
7//! block.
8//!
9//! Main features:
10//!
11//! - Standard HMAC-SHA-256 algorithm.
12//! - Hash result only accessible by configurable hardware peripheral (in downstream mode).
13//! - Compatible to challenge-response authentication algorithm.
14//! - Generates required keys for the Digital Signature (DS) peripheral (in downstream mode).
15//! - Re-enables soft-disabled JTAG (in downstream mode).
16//!
17//! ## Configuration
18//! The HMAC module can be used in two modes - in ”upstream” mode the HMAC
19//! message is supplied by the user and the calculation result is read back by
20//! the user. In ”downstream” mode the HMAC module is used as a Key Derivation
21//! Function (KDF) for other internal hardwares.
22//!
23//! ### HMAC padding
24//!
25//! The HMAC padding is handled by the driver. In downstream mode, users do not
26//! need to input any message or apply padding. The HMAC module uses a default
27//! 32-byte pattern of 0x00 for re-enabling JTAG and a 32-byte pattern of 0xff
28//! for deriving the AES key for the DS module.
29//!
30//! ## Examples
31//! Visit the [HMAC] example to learn how to use the HMAC accelerator
32//!
33//! [HMAC]: https://github.com/esp-rs/esp-hal/blob/main/examples/peripheral/hmac/src/main.rs
34
35use core::convert::Infallible;
36
37use crate::{
38    pac,
39    peripherals::{HMAC, SHA},
40    reg_access::{AlignmentHelper, SocDependentEndianess},
41    system::{
42        CryptoClockGuard,
43        GenericPeripheralGuard,
44        Peripheral as PeripheralEnable,
45        PeripheralClockControl,
46    },
47};
48
49const BLOCK_SIZE: usize = 64;
50// The last block ends with the message length.
51const LENGTH_OFFSET: usize = BLOCK_SIZE - size_of::<u64>();
52
53/// Provides an interface for interacting with the HMAC hardware peripheral.
54/// Computes HMACs for cryptographic purposes and ensures data integrity and authenticity.
55pub struct Hmac<'d> {
56    hmac: HMAC<'d>,
57    _sha: SHA<'d>,
58    alignment_helper: AlignmentHelper<SocDependentEndianess>,
59    block: [u8; BLOCK_SIZE],
60    block_len: usize,
61    block_written: bool,
62    byte_written: usize,
63    _sha_guard: GenericPeripheralGuard<{ PeripheralEnable::Sha as u8 }>,
64    _guard: GenericPeripheralGuard<{ PeripheralEnable::Hmac as u8 }>,
65    _clock_guard: CryptoClockGuard,
66}
67
68/// HMAC interface error
69#[derive(Debug, Clone, Copy, PartialEq)]
70#[cfg_attr(feature = "defmt", derive(defmt::Format))]
71pub enum Error {
72    /// Purpose of the selected block does not match the configured key purpose.
73    KeyPurposeMismatch,
74}
75
76/// The peripheral can be configured to deliver its output directly to
77/// software. It can also deliver to other peripherals.
78#[derive(Debug, Clone, Copy, PartialEq)]
79#[cfg_attr(feature = "defmt", derive(defmt::Format))]
80#[allow(clippy::enum_variant_names, reason = "peripheral is unstable")]
81pub enum HmacPurpose {
82    /// HMAC is used to re-enable JTAG after soft-disabling it.
83    ToJtag     = 6,
84    /// HMAC is provided to the digital signature peripheral to decrypt the
85    /// private key.
86    ToDs       = 7,
87    /// Provides a message and reads the result.
88    ToUser     = 8,
89    /// HMAC is used for both the digital signature and JTAG.
90    ToDsOrJtag = 5,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq)]
94#[cfg_attr(feature = "defmt", derive(defmt::Format))]
95/// Represents the key identifiers for the HMAC peripheral.
96pub enum KeyId {
97    /// Key 0.
98    Key0 = 0,
99    /// Key 1.
100    Key1 = 1,
101    /// Key 2.
102    Key2 = 2,
103    /// Key 3.
104    Key3 = 3,
105    /// Key 4.
106    Key4 = 4,
107    /// Key 5.
108    Key5 = 5,
109}
110
111impl<'d> Hmac<'d> {
112    #[procmacros::doc_replace]
113    /// Creates a new instance of the HMAC peripheral.
114    ///
115    /// The HMAC peripheral uses the SHA accelerator, so the driver owns the `SHA` peripheral and
116    /// turns on its clock. A program that creates a `Sha` or a `ShaBackend` while the driver is in
117    /// use does not compile.
118    ///
119    /// An unfinished HMAC corrupts the next SHA digest. To prevent this, the drop resets the HMAC
120    /// peripheral.
121    ///
122    /// # Examples
123    ///
124    /// Pass `SHA` with `reborrow` so that another driver can use it after the drop.
125    ///
126    /// ```rust, no_run
127    /// # {before_snippet}
128    /// use esp_hal::{hmac::Hmac, sha::Sha};
129    ///
130    /// let hmac = Hmac::new(peripherals.HMAC, peripherals.SHA.reborrow());
131    /// // Calculate the HMACs.
132    /// drop(hmac);
133    ///
134    /// let sha = Sha::new(peripherals.SHA);
135    /// # {after_snippet}
136    /// ```
137    pub fn new(hmac: HMAC<'d>, sha: SHA<'d>) -> Self {
138        let clock_guard = CryptoClockGuard::new();
139        let guard = GenericPeripheralGuard::new();
140        // The HMAC peripheral uses the SHA accelerator, so the SHA clock must be on.
141        // See <https://github.com/espressif/esp-idf/blob/383dda6c182/components/esp_security/src/esp_hmac.c#L73-L76>.
142        let sha_guard = GenericPeripheralGuard::new();
143
144        Self {
145            hmac,
146            _sha: sha,
147            alignment_helper: AlignmentHelper::default(),
148            block: [0; BLOCK_SIZE],
149            block_len: 0,
150            block_written: false,
151            byte_written: BLOCK_SIZE,
152            _sha_guard: sha_guard,
153            _guard: guard,
154            _clock_guard: clock_guard,
155        }
156    }
157
158    fn regs(&self) -> &pac::hmac::RegisterBlock {
159        self.hmac.register_block()
160    }
161
162    /// Enables the HMAC module.
163    pub fn init(&mut self) {
164        self.regs().set_start().write(|w| w.set_start().set_bit());
165        self.reset_message();
166    }
167
168    /// Configures HMAC keys and key purposes.
169    pub fn configure(&mut self, m: HmacPurpose, key_id: KeyId) -> nb::Result<(), Error> {
170        self.regs()
171            .set_para_purpose()
172            .write(|w| unsafe { w.purpose_set().bits(m as u8) });
173        self.regs()
174            .set_para_key()
175            .write(|w| unsafe { w.key_set().bits(key_id as u8) });
176        self.regs()
177            .set_para_finish()
178            .write(|w| w.set_para_end().set_bit());
179
180        let key_mismatch = self.regs().query_error().read().query_check().bit_is_set();
181        if key_mismatch {
182            return Err(nb::Error::Other(Error::KeyPurposeMismatch));
183        }
184
185        Ok(())
186    }
187
188    /// Processes the message block by block.
189    ///
190    /// Must be called as many times as necessary while `msg.len() > 0`.
191    pub fn update<'a>(&mut self, msg: &'a [u8]) -> nb::Result<&'a [u8], Infallible> {
192        if self.is_busy() {
193            return Err(nb::Error::WouldBlock);
194        }
195
196        let len = msg.len().min(BLOCK_SIZE - self.block_len);
197        let (data, remaining) = msg.split_at(len);
198        self.block[self.block_len..][..len].copy_from_slice(data);
199        self.block_len += len;
200        self.byte_written = self.byte_written.wrapping_add(len);
201
202        if self.block_len == BLOCK_SIZE {
203            self.write_block(false);
204        }
205
206        Ok(remaining)
207    }
208
209    /// Finalizes the HMAC computation and retrieves the resulting hash output.
210    pub fn finalize(&mut self, output: &mut [u8]) -> nb::Result<(), Infallible> {
211        if self.is_busy() {
212            return Err(nb::Error::WouldBlock);
213        }
214
215        let bit_len = self.byte_written as u64 * 8;
216
217        self.block[self.block_len] = 0x80;
218        self.block[self.block_len + 1..].fill(0);
219        if self.block_len >= LENGTH_OFFSET {
220            self.write_block(false);
221            self.block.fill(0);
222        }
223        self.block[LENGTH_OFFSET..].copy_from_slice(&bit_len.to_be_bytes());
224
225        let one_block = !self.block_written;
226        self.write_block(true);
227        while self.is_busy() {}
228
229        if one_block {
230            self.regs()
231                .one_block()
232                .write(|w| w.set_one_block().set_bit());
233
234            while self.is_busy() {}
235        }
236
237        self.alignment_helper.volatile_read_regset(
238            #[cfg(esp32s2)]
239            self.regs().rd_result_(0).as_ptr(),
240            #[cfg(not(esp32s2))]
241            self.regs().rd_result_mem(0).as_ptr(),
242            output,
243            core::cmp::min(output.len(), 32),
244        );
245
246        self.regs()
247            .set_result_finish()
248            .write(|w| w.set_result_end().set_bit());
249        self.reset_message();
250        Ok(())
251    }
252
253    fn is_busy(&mut self) -> bool {
254        self.regs().query_busy().read().busy_state().bit_is_set()
255    }
256
257    fn reset_message(&mut self) {
258        self.block_len = 0;
259        self.block_written = false;
260        self.byte_written = BLOCK_SIZE;
261    }
262
263    // The hardware must know whether a block is the last before the block is written.
264    fn write_block(&mut self, last: bool) {
265        while self.is_busy() {}
266
267        if self.block_written {
268            if last {
269                self.regs()
270                    .set_message_pad()
271                    .write(|w| w.set_text_pad().set_bit());
272            } else {
273                self.regs()
274                    .set_message_ing()
275                    .write(|w| w.set_text_ing().set_bit());
276            }
277            while self.is_busy() {}
278        }
279
280        self.alignment_helper.volatile_write_regset(
281            #[cfg(esp32s2)]
282            self.regs().wr_message_(0).as_ptr(),
283            #[cfg(not(esp32s2))]
284            self.regs().wr_message_mem(0).as_ptr(),
285            &self.block,
286            BLOCK_SIZE,
287        );
288        self.regs()
289            .set_message_one()
290            .write(|w| w.set_text_one().set_bit());
291
292        self.block_len = 0;
293        self.block_written = true;
294    }
295}
296
297impl Drop for Hmac<'_> {
298    fn drop(&mut self) {
299        // An unfinished HMAC corrupts the next SHA digest. A reset prevents this.
300        PeripheralClockControl::reset(PeripheralEnable::Hmac);
301    }
302}