esp_hal/
hmac.rs

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
//! # Hash-based Message Authentication Code (HMAC) Accelerator
//!
//! ## Overview
//! HMAC is a secure authentication technique that verifies the authenticity and
//! integrity of a message with a pre-shared key. This module provides hardware
//! acceleration for SHA256-HMAC generation using a key burned into an eFuse
//! block.
//!
//! Main features:
//!
//! - Standard HMAC-SHA-256 algorithm.
//! - Hash result only accessible by configurable hardware peripheral (in
//!   downstream mode).
//! - Compatible to challenge-response authentication algorithm.
//! - Generates required keys for the Digital Signature (DS) peripheral (in
//!   downstream mode).
//! - Re-enables soft-disabled JTAG (in downstream mode).
//!
//! ## Configuration
//! The HMAC module can be used in two modes - in ”upstream” mode the HMAC
//! message is supplied by the user and the calculation result is read back by
//! the user. In ”downstream” mode the HMAC module is used as a Key Derivation
//! Function (KDF) for other internal hardwares.
//!
//! ### HMAC padding
//!
//! The HMAC padding is handled by the driver. In downstream mode, users do not
//! need to input any message or apply padding. The HMAC module uses a default
//! 32-byte pattern of 0x00 for re-enabling JTAG and a 32-byte pattern of 0xff
//! for deriving the AES key for the DS module.
//!
//! ## Examples
//! Visit the [HMAC] example to learn how to use the HMAC accelerator
//!
//! [HMAC]: https://github.com/esp-rs/esp-hal/blob/main/examples/src/bin/hmac.rs

use core::convert::Infallible;

use crate::{
    pac,
    peripheral::{Peripheral, PeripheralRef},
    peripherals::HMAC,
    reg_access::{AlignmentHelper, SocDependentEndianess},
    system::{GenericPeripheralGuard, Peripheral as PeripheralEnable},
};

/// Provides an interface for interacting with the HMAC hardware peripheral.
/// It allows users to compute HMACs for cryptographic purposes, ensuring data
/// integrity and authenticity.
pub struct Hmac<'d> {
    hmac: PeripheralRef<'d, HMAC>,
    alignment_helper: AlignmentHelper<SocDependentEndianess>,
    byte_written: usize,
    next_command: NextCommand,
    _guard: GenericPeripheralGuard<{ PeripheralEnable::Hmac as u8 }>,
}

/// HMAC interface error
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
    /// It means the purpose of the selected block does not match the
    /// configured key purpose and the calculation will not proceed.
    KeyPurposeMismatch,
}

/// The peripheral can be configured to deliver its output directly to the
/// user. It can also deliver to other peripherals.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[allow(clippy::enum_variant_names, reason = "peripheral is unstable")]
pub enum HmacPurpose {
    /// HMAC is used to re-enable JTAG after soft-disabling it.
    ToJtag     = 6,
    /// HMAC is provided to the digital signature peripheral to decrypt the
    /// private key.
    ToDs       = 7,
    /// Let the user provide a message and read the result.
    ToUser     = 8,
    /// HMAC is used for both the digital signature or JTAG.
    ToDsOrJtag = 5,
}

#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
/// Represents the key identifiers for the HMAC peripheral.
pub enum KeyId {
    /// Key 0.
    Key0 = 0,
    /// Key 1.
    Key1 = 1,
    /// Key 2.
    Key2 = 2,
    /// Key 3.
    Key3 = 3,
    /// Key 4.
    Key4 = 4,
    /// Key 5.
    Key5 = 5,
}

enum NextCommand {
    None,
    MessageIng,
    MessagePad,
}

impl<'d> Hmac<'d> {
    /// Creates a new instance of the HMAC peripheral.
    pub fn new(hmac: impl Peripheral<P = HMAC> + 'd) -> Self {
        crate::into_ref!(hmac);

        let guard = GenericPeripheralGuard::new();

        Self {
            hmac,
            alignment_helper: AlignmentHelper::default(),
            byte_written: 64,
            next_command: NextCommand::None,
            _guard: guard,
        }
    }

    fn regs(&self) -> &pac::hmac::RegisterBlock {
        self.hmac.register_block()
    }

    /// Step 1. Enable HMAC module.
    ///
    /// Before these steps, the user shall set the peripheral clocks bits for
    /// HMAC and SHA peripherals and clear the corresponding peripheral
    /// reset bits.
    pub fn init(&mut self) {
        self.regs().set_start().write(|w| w.set_start().set_bit());
        self.alignment_helper.reset();
        self.byte_written = 64;
        self.next_command = NextCommand::None;
    }

    /// Step 2. Configure HMAC keys and key purposes.
    pub fn configure(&mut self, m: HmacPurpose, key_id: KeyId) -> nb::Result<(), Error> {
        self.regs()
            .set_para_purpose()
            .write(|w| unsafe { w.purpose_set().bits(m as u8) });
        self.regs()
            .set_para_key()
            .write(|w| unsafe { w.key_set().bits(key_id as u8) });
        self.regs()
            .set_para_finish()
            .write(|w| w.set_para_end().set_bit());

        if self.regs().query_error().read().query_check().bit_is_set() {
            return Err(nb::Error::Other(Error::KeyPurposeMismatch));
        }

        Ok(())
    }

    /// Process the msg block after block
    ///
    /// Call this function as many times as necessary (msg.len() > 0)
    pub fn update<'a>(&mut self, msg: &'a [u8]) -> nb::Result<&'a [u8], Infallible> {
        if self.is_busy() {
            return Err(nb::Error::WouldBlock);
        }

        self.next_command();

        let remaining = self.write_data(msg).unwrap();

        Ok(remaining)
    }

    /// Finalizes the HMAC computation and retrieves the resulting hash output.
    pub fn finalize(&mut self, output: &mut [u8]) -> nb::Result<(), Infallible> {
        if self.is_busy() {
            return Err(nb::Error::WouldBlock);
        }

        self.next_command();

        let msg_len = self.byte_written as u64;

        nb::block!(self.write_data(&[0x80])).unwrap();
        nb::block!(self.flush_data()).unwrap();
        self.next_command();
        debug_assert!(self.byte_written % 4 == 0);

        self.padding(msg_len);

        // Checking if the message is one block including padding
        if msg_len < 64 + 56 {
            self.regs()
                .one_block()
                .write(|w| w.set_one_block().set_bit());

            while self.is_busy() {}
        }

        self.alignment_helper.volatile_read_regset(
            #[cfg(esp32s2)]
            self.regs().rd_result_(0).as_ptr(),
            #[cfg(not(esp32s2))]
            self.regs().rd_result_mem(0).as_ptr(),
            output,
            core::cmp::min(output.len(), 32) / self.alignment_helper.align_size(),
        );

        self.regs()
            .set_result_finish()
            .write(|w| w.set_result_end().set_bit());
        self.byte_written = 64;
        self.next_command = NextCommand::None;
        Ok(())
    }

    fn is_busy(&mut self) -> bool {
        self.regs().query_busy().read().busy_state().bit_is_set()
    }

    fn next_command(&mut self) {
        match self.next_command {
            NextCommand::MessageIng => {
                self.regs()
                    .set_message_ing()
                    .write(|w| w.set_text_ing().set_bit());
            }
            NextCommand::MessagePad => {
                self.regs()
                    .set_message_pad()
                    .write(|w| w.set_text_pad().set_bit());
            }
            NextCommand::None => {}
        }
        self.next_command = NextCommand::None;
    }

    fn write_data<'a>(&mut self, incoming: &'a [u8]) -> nb::Result<&'a [u8], Infallible> {
        let mod_length = self.byte_written % 64;

        let (remaining, bound_reached) = self.alignment_helper.aligned_volatile_copy(
            #[cfg(esp32s2)]
            self.regs().wr_message_(0).as_ptr(),
            #[cfg(not(esp32s2))]
            self.regs().wr_message_mem(0).as_ptr(),
            incoming,
            64 / self.alignment_helper.align_size(),
            mod_length / self.alignment_helper.align_size(),
        );

        self.byte_written = self
            .byte_written
            .wrapping_add(incoming.len() - remaining.len());

        if bound_reached {
            self.regs()
                .set_message_one()
                .write(|w| w.set_text_one().set_bit());

            if remaining.len() >= 56 {
                self.next_command = NextCommand::MessageIng;
            } else {
                self.next_command = NextCommand::MessagePad;
            }
        }

        Ok(remaining)
    }

    fn flush_data(&mut self) -> nb::Result<(), Infallible> {
        if self.is_busy() {
            return Err(nb::Error::WouldBlock);
        }

        let flushed = self.alignment_helper.flush_to(
            #[cfg(esp32s2)]
            self.regs().wr_message_(0).as_ptr(),
            #[cfg(not(esp32s2))]
            self.regs().wr_message_mem(0).as_ptr(),
            (self.byte_written % 64) / self.alignment_helper.align_size(),
        );

        self.byte_written = self.byte_written.wrapping_add(flushed);
        if flushed > 0 && self.byte_written % 64 == 0 {
            self.regs()
                .set_message_one()
                .write(|w| w.set_text_one().set_bit());
            while self.is_busy() {}
            self.next_command = NextCommand::MessagePad;
        }

        Ok(())
    }

    fn padding(&mut self, msg_len: u64) {
        let mod_cursor = self.byte_written % 64;

        // The padding will be spanned over 2 blocks
        if mod_cursor > 56 {
            let pad_len = 64 - mod_cursor;
            self.alignment_helper.volatile_write(
                #[cfg(esp32s2)]
                self.regs().wr_message_(0).as_ptr(),
                #[cfg(not(esp32s2))]
                self.regs().wr_message_mem(0).as_ptr(),
                0_u8,
                pad_len / self.alignment_helper.align_size(),
                mod_cursor / self.alignment_helper.align_size(),
            );
            self.regs()
                .set_message_one()
                .write(|w| w.set_text_one().set_bit());
            self.byte_written = self.byte_written.wrapping_add(pad_len);
            debug_assert!(self.byte_written % 64 == 0);
            while self.is_busy() {}
            self.next_command = NextCommand::MessagePad;
            self.next_command();
        }

        let mod_cursor = self.byte_written % 64;
        let pad_len = 64 - mod_cursor - core::mem::size_of::<u64>();

        self.alignment_helper.volatile_write(
            #[cfg(esp32s2)]
            self.regs().wr_message_(0).as_ptr(),
            #[cfg(not(esp32s2))]
            self.regs().wr_message_mem(0).as_ptr(),
            0_u8,
            pad_len / self.alignment_helper.align_size(),
            mod_cursor / self.alignment_helper.align_size(),
        );

        self.byte_written = self.byte_written.wrapping_add(pad_len);

        assert_eq!(self.byte_written % 64, 64 - core::mem::size_of::<u64>());

        // Add padded key
        let len_mem = (msg_len * 8).to_be_bytes();

        self.alignment_helper.aligned_volatile_copy(
            #[cfg(esp32s2)]
            self.regs().wr_message_(0).as_ptr(),
            #[cfg(not(esp32s2))]
            self.regs().wr_message_mem(0).as_ptr(),
            &len_mem,
            64 / self.alignment_helper.align_size(),
            (64 - core::mem::size_of::<u64>()) / self.alignment_helper.align_size(),
        );
        self.regs()
            .set_message_one()
            .write(|w| w.set_text_one().set_bit());

        while self.is_busy() {}
    }
}