Skip to main content

at_cryptoauth/
memory.rs

1use super::error::{Error, ErrorKind};
2use core::ops::{Range, RangeInclusive};
3use core::slice::from_ref;
4/// Zone bit 7 set: Access 32 bytes, otherwise 4 bytes.
5const ZONE_READWRITE_32: u8 = 0x80;
6
7/// A unit of data exchange is either 4 or 32 bytes.
8#[derive(Copy, Clone, Debug)]
9pub enum Size {
10    Word = 0x04,
11    Block = 0x20,
12}
13
14impl Size {
15    pub(crate) const fn len(&self) -> usize {
16        match self {
17            Self::Word => Self::Word as usize,
18            Self::Block => Self::Block as usize,
19        }
20    }
21}
22
23#[derive(Copy, Clone, Debug)]
24pub enum Zone {
25    Config = 0x00,
26    Otp = 0x01,
27    Data = 0x02,
28}
29
30impl Zone {
31    // A helper method to translate a global index into block and offset.
32    pub fn locate_index(index: usize) -> (u8, u8, u8) {
33        let block = index / Size::Block.len();
34        let offset = index % Size::Block.len() / Size::Word.len();
35        let position = index % Size::Word.len();
36        (block as u8, offset as u8, position as u8)
37    }
38
39    pub(crate) fn get_slot_addr(&self, slot: Slot, block: u8) -> Result<u16, Error> {
40        match self {
41            Self::Data if slot.is_private_key() && block == 0 => Ok((slot as u16) << 3),
42            Self::Data if slot.is_data() && block <= 12 => {
43                Ok((slot as u16) << 3 | (block as u16) << 8)
44            }
45            Self::Data if slot.is_certificate() && block <= 2 => {
46                Ok((slot as u16) << 3 | (block as u16) << 8)
47            }
48            _ => Err(ErrorKind::BadParam.into()),
49        }
50    }
51
52    pub(crate) fn get_addr(&self, block: u8, offset: u8) -> Result<u16, Error> {
53        if block.leading_zeros() < 3 || offset.leading_zeros() < 4 {
54            return Err(ErrorKind::BadParam.into());
55        }
56        let block = (block as u16) << 3;
57        let offset = (offset & 0x07) as u16;
58        let addr = block | offset;
59        match self {
60            Self::Config | Self::Otp => Ok(addr),
61            // Use get_slot_addr instead.
62            Self::Data => Err(ErrorKind::BadParam.into()),
63        }
64    }
65
66    pub(crate) fn encode(&self, size: Size) -> u8 {
67        match size {
68            Size::Word => *self as u8,
69            Size::Block => *self as u8 | ZONE_READWRITE_32,
70        }
71    }
72}
73
74#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
75#[cfg_attr(feature = "defmt", derive(defmt::Format))]
76pub enum Slot {
77    /// PrivateKey0x contains 36 bytes, taking 2 block reads.
78    PrivateKey00 = 0x00,
79    PrivateKey01 = 0x01,
80    PrivateKey02 = 0x02,
81    PrivateKey03 = 0x03,
82    PrivateKey04 = 0x04,
83    PrivateKey05 = 0x05,
84    PrivateKey06 = 0x06,
85    PrivateKey07 = 0x07,
86    /// Data08 contains 416 bytes, taking 13 block reads.
87    Data08 = 0x08,
88    /// Certificate0x contains 72 bytes, taking 3 block reads.
89    Certificate09 = 0x09,
90    Certificate0a = 0x0a,
91    Certificate0b = 0x0b,
92    Certificate0c = 0x0c,
93    Certificate0d = 0x0d,
94    Certificate0e = 0x0e,
95    Certificate0f = 0x0f,
96}
97
98impl Slot {
99    /// Check if a slot can store private keys.
100    pub fn is_private_key(&self) -> bool {
101        *self <= Self::PrivateKey07
102    }
103
104    /// Check if a slot is the Data08 slot.
105    pub fn is_data(&self) -> bool {
106        *self == Self::Data08
107    }
108
109    /// Check if a slot can store certificates.
110    pub fn is_certificate(&self) -> bool {
111        Self::Certificate09 <= *self
112    }
113
114    pub fn keys() -> KeysIter {
115        KeysIter(0x00..=0x0f)
116    }
117}
118
119/// Superset of [`Slot`] where `Data08(u8)` carries a block index.
120///
121/// Used in [`SerialSource::Stored`] to identify exactly where a serial number
122/// is stored within the Data08 slot.
123#[derive(Copy, Clone, Debug, PartialEq, Eq)]
124#[cfg_attr(feature = "defmt", derive(defmt::Format))]
125pub enum SlotAddress {
126    PrivateKey00,
127    PrivateKey01,
128    PrivateKey02,
129    PrivateKey03,
130    PrivateKey04,
131    PrivateKey05,
132    PrivateKey06,
133    PrivateKey07,
134    /// Data08 block index (0-12). Each block is 32 bytes.
135    Data08(u8),
136    Certificate09,
137    Certificate0a,
138    Certificate0b,
139    Certificate0c,
140    Certificate0d,
141    Certificate0e,
142    Certificate0f,
143}
144
145impl From<SlotAddress> for Slot {
146    fn from(addr: SlotAddress) -> Self {
147        match addr {
148            SlotAddress::PrivateKey00 => Slot::PrivateKey00,
149            SlotAddress::PrivateKey01 => Slot::PrivateKey01,
150            SlotAddress::PrivateKey02 => Slot::PrivateKey02,
151            SlotAddress::PrivateKey03 => Slot::PrivateKey03,
152            SlotAddress::PrivateKey04 => Slot::PrivateKey04,
153            SlotAddress::PrivateKey05 => Slot::PrivateKey05,
154            SlotAddress::PrivateKey06 => Slot::PrivateKey06,
155            SlotAddress::PrivateKey07 => Slot::PrivateKey07,
156            SlotAddress::Data08(_) => Slot::Data08,
157            SlotAddress::Certificate09 => Slot::Certificate09,
158            SlotAddress::Certificate0a => Slot::Certificate0a,
159            SlotAddress::Certificate0b => Slot::Certificate0b,
160            SlotAddress::Certificate0c => Slot::Certificate0c,
161            SlotAddress::Certificate0d => Slot::Certificate0d,
162            SlotAddress::Certificate0e => Slot::Certificate0e,
163            SlotAddress::Certificate0f => Slot::Certificate0f,
164        }
165    }
166}
167
168impl SlotAddress {
169    /// Get the block index for Data08 addresses, or 0 for all other slots.
170    pub fn block(&self) -> u8 {
171        match self {
172            SlotAddress::Data08(block) => *block,
173            _ => 0,
174        }
175    }
176}
177
178pub struct KeysIter(RangeInclusive<usize>);
179
180impl Iterator for KeysIter {
181    type Item = Slot;
182    fn next(&mut self) -> Option<Self::Item> {
183        use Slot::*;
184        self.0.next().and_then(|i| match i {
185            x if x == PrivateKey00 as usize => PrivateKey00.into(),
186            x if x == PrivateKey01 as usize => PrivateKey01.into(),
187            x if x == PrivateKey02 as usize => PrivateKey02.into(),
188            x if x == PrivateKey03 as usize => PrivateKey03.into(),
189            x if x == PrivateKey04 as usize => PrivateKey04.into(),
190            x if x == PrivateKey05 as usize => PrivateKey05.into(),
191            x if x == PrivateKey06 as usize => PrivateKey06.into(),
192            x if x == PrivateKey07 as usize => PrivateKey07.into(),
193            x if x == Data08 as usize => Data08.into(),
194            x if x == Certificate09 as usize => Certificate09.into(),
195            x if x == Certificate0a as usize => Certificate0a.into(),
196            x if x == Certificate0b as usize => Certificate0b.into(),
197            x if x == Certificate0c as usize => Certificate0c.into(),
198            x if x == Certificate0d as usize => Certificate0d.into(),
199            x if x == Certificate0e as usize => Certificate0e.into(),
200            x if x == Certificate0f as usize => Certificate0f.into(),
201            _ => None,
202        })
203    }
204}
205
206/// Iterator for 64-byte public key storage layout in certificate slots
207///
208/// Public keys are stored with specific byte ranges in each block to avoid
209/// reserved areas.
210pub(crate) struct CertificateRepr(RangeInclusive<usize>);
211
212impl CertificateRepr {
213    pub(crate) fn new() -> Self {
214        Self(0..=2)
215    }
216}
217
218impl Iterator for CertificateRepr {
219    type Item = &'static [Range<usize>];
220    fn next(&mut self) -> Option<Self::Item> {
221        self.0.next().and_then(|i| match i {
222            0 => from_ref(&(0x04..0x20)).into(),
223            1 => [0x00..0x04, 0x08..0x20].as_ref().into(),
224            2 => from_ref(&(0x00..0x08)).into(),
225            _ => None,
226        })
227    }
228}
229
230/// Iterator for 72-byte compressed certificate storage in certificate slots.
231///
232/// Unlike public keys (which use a padded layout with reserved bytes per block),
233/// compressed certificates use straight linear storage across the 72-byte slot:
234/// Block 0: bytes 0-31 = 32 bytes -> cert[0:32]
235/// Block 1: bytes 0-31 = 32 bytes -> cert[32:64]
236/// Block 2: bytes 0-7  = 8 bytes  -> cert[64:72]
237pub(crate) struct CompressedCertRepr(RangeInclusive<usize>);
238
239impl CompressedCertRepr {
240    pub(crate) fn new() -> Self {
241        Self(0..=2)
242    }
243}
244
245impl Iterator for CompressedCertRepr {
246    type Item = &'static [Range<usize>];
247    fn next(&mut self) -> Option<Self::Item> {
248        self.0.next().and_then(|i| match i {
249            0 => from_ref(&(0x00..0x20)).into(),
250            1 => from_ref(&(0x00..0x20)).into(),
251            2 => from_ref(&(0x00..0x08)).into(),
252            _ => None,
253        })
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use crate::client::Memory;
261    use Slot::*;
262    use Zone::*;
263    use core::convert::identity;
264    use core::iter::repeat;
265    use embassy_sync::blocking_mutex::raw::NoopRawMutex;
266    use heapless::Vec;
267
268    #[test]
269    fn locate_index() {
270        assert_eq!(
271            (0, 5, 0),
272            Zone::locate_index(Memory::<NoopRawMutex, ()>::SLOT_CONFIG_INDEX)
273        );
274        assert_eq!(
275            (2, 6, 2),
276            Zone::locate_index(Memory::<NoopRawMutex, ()>::CHIP_OPTIONS_INDEX)
277        );
278        assert_eq!(
279            (3, 0, 0),
280            Zone::locate_index(Memory::<NoopRawMutex, ()>::KEY_CONFIG_INDEX)
281        );
282    }
283
284    #[test]
285    fn get_slot_addr() {
286        assert_eq!(0x0038, Data.get_slot_addr(PrivateKey07, 0).unwrap());
287        for (&addr, block) in [0x0078, 0x0178, 0x0278].iter().zip(0..=2) {
288            let result = Data.get_slot_addr(Certificate0f, block).unwrap();
289            assert_eq!(addr, result);
290        }
291    }
292
293    #[test]
294    fn get_slot_addr_data08() {
295        // Data08 block 0
296        assert_eq!(0x0040, Data.get_slot_addr(Data08, 0).unwrap());
297        // Data08 block 12 (max)
298        assert_eq!(0x0C40, Data.get_slot_addr(Data08, 12).unwrap());
299        // Data08 block 13 should fail
300        assert!(Data.get_slot_addr(Data08, 13).is_err());
301    }
302
303    #[test]
304    fn get_addr() {
305        assert_eq!(0x0005, Config.get_addr(0, 5).unwrap());
306        assert_eq!(0x0016, Config.get_addr(2, 6).unwrap());
307        assert_eq!(0x0018, Config.get_addr(3, 0).unwrap());
308    }
309
310    #[test]
311    fn certificate_representation() {
312        let slot_buffer = repeat(0)
313            .take(4)
314            .chain(0x00..0x20)
315            .chain(repeat(0).take(4))
316            .chain(0x20..0x40)
317            .chain(repeat(0).take(24))
318            .collect::<Vec<u8, 96>>();
319        assert_eq!(Size::Block.len() * 3, slot_buffer.len());
320        slot_buffer
321            .chunks(Size::Block.len())
322            .zip(CertificateRepr::new())
323            .scan(0, |i, (chunk, ranges)| {
324                for range in ranges {
325                    for j in &chunk[range.clone()] {
326                        assert_eq!(i, j);
327                        *i += 1;
328                    }
329                }
330                Some(())
331            })
332            .for_each(identity)
333    }
334}