1use super::client::{AtCaClient, Memory, Sha};
10use super::error::Error;
11use super::memory::{Size, Slot, Zone};
12use embassy_sync::blocking_mutex::raw::RawMutex;
13use signature::digest::{
14 FixedOutput, OutputSizeUser, Reset, Update, consts::U32, generic_array::GenericArray,
15};
16
17pub const AUTH_PRIVATE_KEY: Slot = Slot::PrivateKey00;
18pub const SIGN_PRIVATE_KEY: Slot = Slot::PrivateKey01;
19pub const USER_PRIVATE_KEY1: Slot = Slot::PrivateKey02;
20pub const USER_PRIVATE_KEY2: Slot = Slot::PrivateKey03;
21pub const USER_PRIVATE_KEY3: Slot = Slot::PrivateKey04;
22pub const IO_PROTECTION_KEY: Slot = Slot::PrivateKey06;
23pub const AES_KEY: Slot = Slot::Certificate09;
24pub const DEVICE_CERTIFICATE: Slot = Slot::Certificate0a;
25pub const SIGNER_PUBLIC_KEY: Slot = Slot::Certificate0b;
26pub const SIGNER_CERTIFICATE: Slot = Slot::Certificate0c;
27
28pub struct Hasher<'a, M: RawMutex, PHY>(Sha<'a, M, PHY>);
29impl<'a, M: RawMutex, PHY> From<Sha<'a, M, PHY>> for Hasher<'a, M, PHY> {
30 fn from(sha: Sha<'a, M, PHY>) -> Self {
31 Self(sha)
32 }
33}
34
35impl<'a, M, PHY> Update for Hasher<'a, M, PHY>
36where
37 PHY: embedded_hal::i2c::I2c,
38 M: RawMutex,
39{
40 fn update(&mut self, data: &[u8]) {
41 self.0.update(data)
42 }
43}
44
45impl<'a, M: RawMutex, PHY> OutputSizeUser for Hasher<'a, M, PHY> {
46 type OutputSize = U32;
47}
48
49impl<'a, M, PHY> FixedOutput for Hasher<'a, M, PHY>
50where
51 PHY: embedded_hal::i2c::I2c,
52 M: RawMutex,
53{
54 fn finalize_into(self, out: &mut GenericArray<u8, Self::OutputSize>) {
55 let digest = self
56 .0
57 .finalize_blocking()
58 .expect("finalize operation failed");
59 out.as_mut_slice().copy_from_slice(digest.as_ref());
60 }
61}
62
63impl<'a, M, PHY> Reset for Hasher<'a, M, PHY>
64where
65 PHY: embedded_hal::i2c::I2c,
66 M: RawMutex,
67{
68 fn reset(&mut self) {}
69}
70
71pub struct TrustAndGo<'a, M: RawMutex, PHY> {
72 pub(crate) atca: &'a AtCaClient<M, PHY>,
73}
74
75impl<'a, M: RawMutex, PHY> TrustAndGo<'a, M, PHY> {
76 const TNG_TLS_SLOT_CONFIG_DATA: [u8; Size::Block as usize] = [
78 0x85, 0x00, 0x82, 0x00, 0x85, 0x20, 0x85, 0x20, 0x85, 0x20, 0x8f, 0x8f, 0x8f, 0x0f, 0xaf, 0x8f, 0x0f, 0x0f, 0x8f, 0x0f, 0x0f, 0x8f, 0x0f, 0x8f, 0x0f, 0x8f, 0x00, 0x00, 0x00, 0x00, 0xaf, 0x8f, ];
92
93 const TNG_TLS_CHIP_OPTIONS: [u8; Size::Word as usize] = [
94 0xff, 0xff, 0x60, 0x0e,
96 ];
97
98 const TNG_TLS_KEY_CONFIG_DATA: [u8; Size::Block as usize] = [
99 0x53, 0x00, 0x53, 0x00, 0x73, 0x00, 0x73, 0x00, 0x73, 0x00, 0x1c, 0x00, 0x7c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x1a, 0x00, 0x1c, 0x00, 0x10, 0x00, 0x1c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x1c, 0x00, ];
113}
114
115impl<'a, M, PHY> TrustAndGo<'a, M, PHY>
117where
118 PHY: embedded_hal_async::i2c::I2c,
119 M: RawMutex,
120{
121 pub async fn configure_permissions(&mut self) -> Result<(), Error> {
123 for (i, word) in Self::TNG_TLS_SLOT_CONFIG_DATA
124 .chunks(Size::Word.len())
125 .enumerate()
126 {
127 let index = Memory::<M, PHY>::SLOT_CONFIG_INDEX + i * Size::Word.len();
128 let (block, offset, _) = Zone::locate_index(index);
129 self.atca
130 .memory()
131 .write_config(Size::Word, block, offset, word)
132 .await?
133 }
134
135 Ok(())
136 }
137
138 pub async fn configure_chip_options(&mut self) -> Result<(), Error> {
140 let (block, offset, _) = Zone::locate_index(Memory::<M, PHY>::CHIP_OPTIONS_INDEX);
141 self.atca
142 .memory()
143 .write_config(Size::Word, block, offset, &Self::TNG_TLS_CHIP_OPTIONS)
144 .await
145 }
146
147 pub async fn configure_key_types(&mut self) -> Result<(), Error> {
149 let (block, offset, _) = Zone::locate_index(Memory::<M, PHY>::KEY_CONFIG_INDEX);
150 self.atca
151 .memory()
152 .write_config(Size::Block, block, offset, &Self::TNG_TLS_KEY_CONFIG_DATA)
153 .await
154 }
155}
156
157impl<'a, M, PHY> TrustAndGo<'a, M, PHY>
158where
159 PHY: embedded_hal::i2c::I2c,
160 M: RawMutex,
161{
162 pub fn configure_permissions_blocking(&mut self) -> Result<(), Error> {
164 for (i, word) in Self::TNG_TLS_SLOT_CONFIG_DATA
165 .chunks(Size::Word.len())
166 .enumerate()
167 {
168 let index = Memory::<M, PHY>::SLOT_CONFIG_INDEX + i * Size::Word.len();
169 let (block, offset, _) = Zone::locate_index(index);
170 self.atca
171 .memory()
172 .write_config_blocking(Size::Word, block, offset, word)?
173 }
174
175 Ok(())
176 }
177
178 pub fn configure_chip_options_blocking(&mut self) -> Result<(), Error> {
180 let (block, offset, _) = Zone::locate_index(Memory::<M, PHY>::CHIP_OPTIONS_INDEX);
181 self.atca.memory().write_config_blocking(
182 Size::Word,
183 block,
184 offset,
185 &Self::TNG_TLS_CHIP_OPTIONS,
186 )
187 }
188
189 pub fn configure_key_types_blocking(&mut self) -> Result<(), Error> {
191 let (block, offset, _) = Zone::locate_index(Memory::<M, PHY>::KEY_CONFIG_INDEX);
192 self.atca.memory().write_config_blocking(
193 Size::Block,
194 block,
195 offset,
196 &Self::TNG_TLS_KEY_CONFIG_DATA,
197 )
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204 use crate::command::OpCode;
205 use OpCode::*;
206 use core::convert::TryInto;
207 use core::ops::Deref;
208 use embassy_sync::blocking_mutex::raw::NoopRawMutex;
209 use heapless::Vec;
210 const KEY_TYPE_P256: u16 = 0x04; const KEY_TYPE_AES: u16 = 0x06; const KEY_TYPE_SHA: u16 = 0x07; struct Provision {
215 key_id: Slot,
216 permission: u16,
217 key_config: u16,
218 }
219
220 impl Provision {
221 fn new(key_id: Slot) -> Self {
222 let permission = permission(key_id);
223 let key_config = key_config(key_id);
224 Self {
225 key_id,
226 permission,
227 key_config,
228 }
229 }
230
231 fn is_private(&self) -> bool {
232 self.key_config & 0x01 != 0x00
233 }
234
235 fn key_type(&self) -> u16 {
236 (self.key_config >> 2) & 0x07
237 }
238
239 fn read_key(&self) -> u16 {
240 self.permission & 0x0f
241 }
242
243 fn encrypt_read(&self) -> bool {
244 (self.permission >> 6) & 0x01 != 0x00
245 }
246
247 fn is_secret(&self) -> bool {
248 (self.permission >> 7) & 0x01 != 0x00
249 }
250
251 fn write_config(&self) -> u16 {
252 (self.permission >> 12) & 0x0f
253 }
254
255 fn read_permission(&self) -> &str {
256 match (self.is_secret(), self.encrypt_read()) {
257 (false, false) => "Clear text",
258 (true, false) => "Never",
259 (true, true) => "Encrypted",
260 _ => panic!("Prohibited"),
261 }
262 }
263
264 fn write_permission(&self) -> &str {
265 match self.write_config() {
266 0x00 => "Clear text",
267 0x01 => "PubInvalid",
268 x if (x >> 1) == 0x01 => "Never",
269 x if (x >> 2) == 0x02 => "Never",
270 x if (x >> 2) & 0x01 == 0x01 => "Encrypted",
271 _ => panic!("Prohibited"),
272 }
273 }
274
275 fn require_nonce(&self) -> bool {
277 (self.key_config >> 6) & 0x01 != 0x00
278 }
279
280 fn creation_commands(&self) -> Vec<OpCode, 5> {
282 let mut commands = Vec::<OpCode, 5>::new();
283 if self.key_id.is_private_key() && self.key_type() == KEY_TYPE_P256 && self.is_secret()
284 {
285 if (self.write_config() >> 1) & 0x01 == 0x01 {
286 commands.push(GenKey).unwrap();
287 commands.push(DeriveKey).unwrap();
288 }
289 if (self.write_config() >> 2) & 0x01 == 0x01 {
290 commands.push(PrivWrite).unwrap();
291 }
292 }
293 commands
294 }
295
296 #[allow(dead_code)]
298 fn operation_commands(&self) -> &[OpCode] {
299 let mut commands = Vec::<OpCode, 5>::new();
300 if self.key_id.is_private_key() {
301 if (self.read_key() >> 2) & 0x01 == 0x01 {
302 commands.push(Ecdh).unwrap();
303 }
304 if self.is_secret() && self.key_type() == KEY_TYPE_P256 {
305 commands.push(Sign).unwrap();
306 }
307 unimplemented!()
308 } else {
309 unimplemented!()
310 }
311 }
312 }
313
314 fn permission(key_id: Slot) -> u16 {
315 let data = &TrustAndGo::<NoopRawMutex, ()>::TNG_TLS_SLOT_CONFIG_DATA;
316 let index = key_id as usize * 2;
317 let range = index..index + 2;
318 data[range]
319 .try_into()
320 .map(u16::from_le_bytes)
321 .unwrap_or_else(|_| unreachable!())
322 }
323
324 fn key_config(key_id: Slot) -> u16 {
325 let data = &TrustAndGo::<NoopRawMutex, ()>::TNG_TLS_KEY_CONFIG_DATA;
326 let index = key_id as usize * 2;
327 let range = index..index + 2;
328 data[range]
329 .try_into()
330 .map(u16::from_le_bytes)
331 .unwrap_or_else(|_| unreachable!())
332 }
333
334 #[test]
338 fn provision() {
339 let auth_priv = Provision::new(AUTH_PRIVATE_KEY);
340 assert_eq!(true, auth_priv.is_private());
341 assert_eq!(KEY_TYPE_P256, auth_priv.key_type());
342 assert_eq!(true, auth_priv.require_nonce());
343 assert_eq!(0x05, auth_priv.read_key());
344 assert_eq!("Clear text", auth_priv.write_permission());
345 assert_eq!(0, auth_priv.creation_commands().len());
346
347 let sign_priv = Provision::new(SIGN_PRIVATE_KEY);
348 assert_eq!(true, sign_priv.is_private());
349 assert_eq!(KEY_TYPE_P256, sign_priv.key_type());
350 assert_eq!(true, sign_priv.require_nonce());
351 assert_eq!(0x02, sign_priv.read_key());
352 assert_eq!("Clear text", sign_priv.write_permission());
353 assert_eq!(0, sign_priv.creation_commands().len());
354
355 for key_id in [USER_PRIVATE_KEY1, USER_PRIVATE_KEY2, USER_PRIVATE_KEY3].iter() {
356 let user_priv = Provision::new(*key_id);
357 assert_eq!(true, user_priv.is_private());
358 assert_eq!(KEY_TYPE_P256, user_priv.key_type());
359 assert_eq!(true, user_priv.require_nonce());
360 assert_eq!(0x05, user_priv.read_key());
361 assert_eq!("Never", user_priv.write_permission());
362 assert_eq!(&[GenKey, DeriveKey], user_priv.creation_commands().deref());
363 }
364
365 let io_protect = Provision::new(IO_PROTECTION_KEY);
366 assert_eq!(KEY_TYPE_SHA, io_protect.key_type());
367 assert_eq!("Clear text", io_protect.write_permission());
368 assert_eq!(true, io_protect.require_nonce());
369 assert_eq!(0, io_protect.creation_commands().len());
370
371 let aes_key = Provision::new(AES_KEY);
372 assert_eq!(KEY_TYPE_AES, aes_key.key_type());
373 assert_eq!("Never", aes_key.read_permission());
374 assert_eq!("Clear text", aes_key.write_permission());
375 assert_eq!(0x00, aes_key.write_config());
376
377 let device_cert = Provision::new(DEVICE_CERTIFICATE);
378 assert_eq!(KEY_TYPE_SHA, device_cert.key_type());
379 assert_eq!("Clear text", device_cert.read_permission());
380 assert_eq!("Never", device_cert.write_permission());
381 assert_eq!(0x08, device_cert.write_config());
382
383 let signer_pub = Provision::new(SIGNER_PUBLIC_KEY);
384 assert_eq!(KEY_TYPE_P256, signer_pub.key_type());
385 assert_eq!("Clear text", signer_pub.read_permission());
386 assert_eq!("Never", signer_pub.write_permission());
387 assert_eq!(0x08, signer_pub.write_config());
388
389 let signer_cert = Provision::new(SIGNER_CERTIFICATE);
390 assert_eq!(KEY_TYPE_SHA, signer_cert.key_type());
391 assert_eq!("Clear text", signer_cert.read_permission());
392 assert_eq!("Never", signer_cert.write_permission());
393 assert_eq!(0x08, signer_cert.write_config());
394 }
395}