at-cryptoauth 0.6.0

Driver for ATECC608 Crypto Authentication secure elements
Documentation
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! TLS integration with embedded-tls via ATECC608 hardware verification.
//!
//! Provides [`AteccProvider`] implementing [`embedded_tls::CryptoProvider`] with
//! hardware-backed ECDSA verification and signing through the ATECC608 secure element.

use crate::AtCaClient;
use crate::cert::compressed::CertificateDefinition;
use crate::command::PublicKey;
use crate::memory::Slot;

use der::asn1::{
    AnyRef, BitStringRef, GeneralizedTime, IntRef, ObjectIdentifier, SequenceOf, SetOf, UtcTime,
};
use der::{Choice, Decode, Enumerated, Reader, Sequence, SliceReader, ValueOrd};
use embassy_sync::blocking_mutex::raw::RawMutex;
use embedded_tls::{
    Aes128GcmSha256, Certificate, CertificateEntryRef, CertificateRef, CertificateVerifyRef,
    NoVerify, SignatureScheme, TlsError, TlsVerifier,
};
use heapless::Vec;
use sha2::Digest as _;

use core::cmp::Ordering;

// ---------------------------------------------------------------------------
// X.509 DER parsing types (local copy — embedded-tls's are private/feature-gated)
// ---------------------------------------------------------------------------

const COMMON_NAME_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.3");

const ECDSA_SHA256_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");

#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Sequence, ValueOrd)]
struct AlgorithmIdentifier<'a> {
    oid: ObjectIdentifier,
    parameters: Option<AnyRef<'a>>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Copy, Enumerated)]
#[asn1(type = "INTEGER")]
#[repr(u8)]
enum Version {
    #[default]
    V1 = 0,
    V2 = 1,
    V3 = 2,
}

impl ValueOrd for Version {
    fn value_cmp(&self, other: &Self) -> der::Result<Ordering> {
        (*self as u8).value_cmp(&(*other as u8))
    }
}

#[derive(Debug, Choice, ValueOrd)]
enum Time {
    #[asn1(type = "UTCTime")]
    UtcTime(UtcTime),
    #[asn1(type = "GeneralizedTime")]
    GeneralTime(GeneralizedTime),
}

#[derive(Debug, Sequence, ValueOrd)]
struct Validity {
    not_before: Time,
    not_after: Time,
}

#[derive(Debug, Sequence, ValueOrd)]
struct AttributeTypeAndValue<'a> {
    oid: ObjectIdentifier,
    value: AnyRef<'a>,
}

#[derive(Debug, Sequence, ValueOrd)]
struct SubjectPublicKeyInfoRef<'a> {
    algorithm: AlgorithmIdentifier<'a>,
    public_key: BitStringRef<'a>,
}

#[derive(Debug, Sequence, ValueOrd)]
struct TbsCertificate<'a> {
    #[asn1(context_specific = "0", default = "Default::default")]
    version: Version,

    serial_number: IntRef<'a>,
    signature: AlgorithmIdentifier<'a>,
    issuer: SequenceOf<SetOf<AttributeTypeAndValue<'a>, 1>, 7>,

    validity: Validity,
    subject: SequenceOf<SetOf<AttributeTypeAndValue<'a>, 1>, 7>,
    subject_public_key_info: SubjectPublicKeyInfoRef<'a>,

    #[asn1(context_specific = "1", tag_mode = "IMPLICIT", optional = "true")]
    issuer_unique_id: Option<BitStringRef<'a>>,

    #[asn1(context_specific = "2", tag_mode = "IMPLICIT", optional = "true")]
    subject_unique_id: Option<BitStringRef<'a>>,

    #[asn1(context_specific = "3", tag_mode = "EXPLICIT", optional = "true")]
    extensions: Option<AnyRef<'a>>,
}

#[derive(Sequence, ValueOrd)]
struct DecodedCertificate<'a> {
    tbs_certificate: TbsCertificate<'a>,
    signature_algorithm: AlgorithmIdentifier<'a>,
    signature: BitStringRef<'a>,
}

/// Extract the TBS (to-be-signed) portion as raw TLV bytes from a DER certificate.
fn get_certificate_tlv_bytes(input: &[u8]) -> Result<&[u8], TlsError> {
    let mut reader = SliceReader::new(input).map_err(|_| TlsError::DecodeError)?;
    let top_header = der::Header::decode(&mut reader).map_err(|_| TlsError::DecodeError)?;
    top_header
        .tag
        .assert_eq(der::Tag::Sequence)
        .map_err(|_| TlsError::DecodeError)?;

    reader.tlv_bytes().map_err(|_| TlsError::DecodeError)
}

/// Extract the Common Name from a certificate's subject field.
fn extract_common_name<'a>(
    subject: &SequenceOf<SetOf<AttributeTypeAndValue<'a>, 1>, 7>,
) -> Option<heapless::String<64>> {
    for elems in subject.iter() {
        if let Some(attr) = elems.get(0)
            && attr.oid == COMMON_NAME_OID
        {
            let mut v: Vec<u8, 64> = Vec::new();
            v.extend_from_slice(attr.value.value()).ok()?;
            return heapless::String::from_utf8(v).ok();
        }
    }
    None
}

/// Convert a SEC1 uncompressed public key (65 bytes, 0x04 prefix) to raw X||Y (64 bytes).
fn sec1_to_raw_pubkey(sec1: &[u8]) -> Result<PublicKey, TlsError> {
    if sec1.len() != 65 || sec1[0] != 0x04 {
        return Err(TlsError::DecodeError);
    }
    PublicKey::try_from(&sec1[1..]).map_err(|_| TlsError::DecodeError)
}

// ---------------------------------------------------------------------------
// Flexible certificate and CA key sources
// ---------------------------------------------------------------------------

/// Source for the client certificate presented during mutual TLS.
pub enum CertSource<'a> {
    /// Pre-built DER-encoded X.509 certificate.
    Der(&'a [u8]),
    /// Compressed certificate reconstructed from ATECC608 at handshake time.
    Compressed(CertificateDefinition<'a>),
    /// Certificate loaded on-demand via a loader function.
    /// The function receives a buffer and returns the number of DER bytes
    /// written, or `None` on failure.
    Lazy(fn(&mut [u8]) -> Option<usize>),
}

impl<'a> From<&'a [u8]> for CertSource<'a> {
    fn from(der: &'a [u8]) -> Self {
        Self::Der(der)
    }
}

impl<'a> From<CertificateDefinition<'a>> for CertSource<'a> {
    fn from(def: CertificateDefinition<'a>) -> Self {
        Self::Compressed(def)
    }
}

impl From<fn(&mut [u8]) -> Option<usize>> for CertSource<'_> {
    fn from(loader: fn(&mut [u8]) -> Option<usize>) -> Self {
        Self::Lazy(loader)
    }
}

/// Source for the root CA public key used to verify the server certificate chain.
pub enum RootCaSource {
    /// Raw 64-byte X||Y public key (provided directly or extracted from DER).
    Key(PublicKey),
    /// Public key read from an ATECC slot at verification time.
    Stored(Slot),
}

impl From<PublicKey> for RootCaSource {
    fn from(key: PublicKey) -> Self {
        Self::Key(key)
    }
}

impl From<Slot> for RootCaSource {
    fn from(slot: Slot) -> Self {
        Self::Stored(slot)
    }
}

impl TryFrom<&[u8]> for RootCaSource {
    type Error = TlsError;

    /// Parse a DER-encoded X.509 certificate and extract the subject public key.
    fn try_from(der: &[u8]) -> Result<Self, TlsError> {
        let parsed = DecodedCertificate::from_der(der).map_err(|_| TlsError::DecodeError)?;
        let spki_bytes = parsed
            .tbs_certificate
            .subject_public_key_info
            .public_key
            .as_bytes()
            .ok_or(TlsError::DecodeError)?;
        Ok(Self::Key(sec1_to_raw_pubkey(spki_bytes)?))
    }
}

// ---------------------------------------------------------------------------
// AteccVerifier
// ---------------------------------------------------------------------------

pub struct AteccVerifier<'a, M: RawMutex, PHY> {
    atca: &'a AtCaClient<M, PHY>,
    ca_pubkey_source: RootCaSource,
    host: Option<heapless::String<64>>,
    certificate_transcript: Option<[u8; 32]>,
    server_public_key: Option<PublicKey>,
}

impl<'a, M: RawMutex, PHY> AteccVerifier<'a, M, PHY> {
    fn new(atca: &'a AtCaClient<M, PHY>, ca_pubkey_source: impl Into<RootCaSource>) -> Self {
        Self {
            atca,
            ca_pubkey_source: ca_pubkey_source.into(),
            host: None,
            certificate_transcript: None,
            server_public_key: None,
        }
    }
}

impl<M, PHY> TlsVerifier<Aes128GcmSha256> for AteccVerifier<'_, M, PHY>
where
    M: RawMutex,
    PHY: embedded_hal::i2c::I2c,
{
    fn set_hostname_verification(&mut self, hostname: &str) -> Result<(), TlsError> {
        self.host.replace(
            heapless::String::try_from(hostname).map_err(|_| TlsError::InsufficientSpace)?,
        );
        Ok(())
    }

    fn verify_certificate(
        &mut self,
        transcript: &sha2::Sha256,
        cert: CertificateRef,
    ) -> Result<(), TlsError> {
        // Resolve CA public key from the configured source
        let mut ca_pubkey = match &self.ca_pubkey_source {
            RootCaSource::Key(key) => *key,
            RootCaSource::Stored(slot) => self
                .atca
                .memory()
                .pubkey_blocking(*slot)
                .map_err(|_| TlsError::InvalidCertificate)?,
        };

        // Trust is anchored on this configured key, not on a server-presented
        // copy of the root. Kept separate from `ca_pubkey`, which mutates as we
        // descend the chain.
        let anchor_pubkey = ca_pubkey;

        let mut cn = None;

        // Walk the chain from the entry closest to CA (last) down to the leaf (first).
        // Each entry is verified against the current verifier public key.
        let num_entries = cert.entries.len();
        for i in (0..num_entries).rev() {
            let cert_data = match &cert.entries[i] {
                CertificateEntryRef::X509(data) => *data,
                _ => return Err(TlsError::DecodeError),
            };

            let parsed =
                DecodedCertificate::from_der(cert_data).map_err(|_| TlsError::DecodeError)?;

            // Extract this cert's public key up front so a server-presented copy
            // of the trust anchor can be recognised before any verification.
            let spki_bytes = parsed
                .tbs_certificate
                .subject_public_key_info
                .public_key
                .as_bytes()
                .ok_or(TlsError::DecodeError)?;
            let cert_pubkey = sec1_to_raw_pubkey(spki_bytes)?;

            // A server MAY include the (cross-signed) root in the chain
            // (RFC 8446 4.4.2). We already trust the anchor by its public key, so
            // skip a presented copy of it rather than verifying it. The
            // cross-signed Amazon Root CA 3 is RSA-signed and would otherwise
            // trip the ECDSA-only check below.
            if cert_pubkey.as_ref() == anchor_pubkey.as_ref() {
                continue;
            }

            // Only ECDSA P-256 SHA-256 is supported by the ATECC608
            if parsed.signature_algorithm.oid != ECDSA_SHA256_OID {
                return Err(TlsError::InvalidSignatureScheme);
            }

            // Hash the TBS data with software SHA-256
            let tbs_data = get_certificate_tlv_bytes(cert_data)?;
            let hash = sha2::Sha256::digest(tbs_data);

            // Convert hash to ATECC Digest
            let digest =
                crate::Digest::try_from(hash.as_slice()).map_err(|_| TlsError::CryptoError)?;

            // Convert DER signature to p256::ecdsa::Signature (raw R||S internally)
            let sig_bytes = parsed.signature.as_bytes().ok_or(TlsError::DecodeError)?;
            let signature = p256::ecdsa::Signature::from_der(sig_bytes)
                .map_err(|_| TlsError::InvalidSignature)?;

            // Verify using ATECC hardware
            self.atca
                .verify_external_blocking(&digest, &signature, &ca_pubkey)
                .map_err(|_| TlsError::InvalidCertificate)?;

            if i == 0 {
                // Leaf certificate — extract CN and store server public key
                cn = extract_common_name(&parsed.tbs_certificate.subject);
                self.server_public_key = Some(cert_pubkey);
            } else {
                // Intermediate — use its public key to verify the next cert down
                ca_pubkey = cert_pubkey;
            }
        }

        // Hostname verification (supports leading wildcard, e.g. *.example.com)
        if let Some(ref host) = self.host {
            let ok = match cn {
                Some(ref cn) => {
                    if let Some(wildcard_rest) = cn.strip_prefix("*.") {
                        // Wildcard: host must have at least one label before the
                        // matching suffix, and must not itself be a wildcard.
                        match host.find('.') {
                            Some(dot) => host[dot + 1..] == *wildcard_rest,
                            None => false,
                        }
                    } else {
                        host.as_str() == cn.as_str()
                    }
                }
                None => false,
            };
            if !ok {
                return Err(TlsError::InvalidCertificate);
            }
        }

        self.certificate_transcript = Some(transcript.clone().finalize().into());
        Ok(())
    }

    fn verify_signature(&mut self, verify: CertificateVerifyRef) -> Result<(), TlsError> {
        if verify.signature_scheme != SignatureScheme::EcdsaSecp256r1Sha256 {
            return Err(TlsError::InvalidSignatureScheme);
        }

        let server_pubkey = self
            .server_public_key
            .as_ref()
            .ok_or(TlsError::InvalidCertificate)?;

        // Build the verification message per RFC 8446 §4.4.3
        let handshake_hash = self
            .certificate_transcript
            .take()
            .ok_or(TlsError::InvalidHandshake)?;

        let ctx_str = b"TLS 1.3, server CertificateVerify\x00";
        let mut msg: Vec<u8, 146> = Vec::new();
        msg.resize(64, 0x20)
            .map_err(|_| TlsError::InsufficientSpace)?;
        msg.extend_from_slice(ctx_str)
            .map_err(|_| TlsError::InsufficientSpace)?;
        msg.extend_from_slice(&handshake_hash)
            .map_err(|_| TlsError::InsufficientSpace)?;

        // Hash the verification message with software SHA-256
        let hash = sha2::Sha256::digest(&msg);
        let digest = crate::Digest::try_from(hash.as_slice()).map_err(|_| TlsError::CryptoError)?;

        // Convert DER signature
        let signature = p256::ecdsa::Signature::from_der(verify.signature)
            .map_err(|_| TlsError::InvalidSignature)?;

        // Verify using ATECC hardware
        self.atca
            .verify_external_blocking(&digest, &signature, server_pubkey)
            .map_err(|_| TlsError::InvalidSignature)?;

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Verifier — dispatches to AteccVerifier or NoVerify
// ---------------------------------------------------------------------------

#[allow(clippy::large_enum_variant)]
enum Verifier<'a, M: RawMutex, PHY> {
    Atecc(AteccVerifier<'a, M, PHY>),
    NoVerify(NoVerify),
}

impl<M, PHY> TlsVerifier<Aes128GcmSha256> for Verifier<'_, M, PHY>
where
    M: RawMutex,
    PHY: embedded_hal::i2c::I2c,
{
    fn set_hostname_verification(&mut self, hostname: &str) -> Result<(), TlsError> {
        match self {
            Self::Atecc(v) => v.set_hostname_verification(hostname),
            Self::NoVerify(v) => {
                <NoVerify as TlsVerifier<Aes128GcmSha256>>::set_hostname_verification(v, hostname)
            }
        }
    }

    fn verify_certificate(
        &mut self,
        transcript: &sha2::Sha256,
        cert: CertificateRef,
    ) -> Result<(), TlsError> {
        match self {
            Self::Atecc(v) => v.verify_certificate(transcript, cert),
            Self::NoVerify(v) => {
                <NoVerify as TlsVerifier<Aes128GcmSha256>>::verify_certificate(v, transcript, cert)
            }
        }
    }

    fn verify_signature(&mut self, verify: CertificateVerifyRef) -> Result<(), TlsError> {
        match self {
            Self::Atecc(v) => v.verify_signature(verify),
            Self::NoVerify(v) => {
                <NoVerify as TlsVerifier<Aes128GcmSha256>>::verify_signature(v, verify)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// AteccProvider
// ---------------------------------------------------------------------------

pub struct AteccProvider<'a, M: RawMutex, PHY, const CERT_SIZE: usize = 0> {
    atca: &'a AtCaClient<M, PHY>,
    sign_key: Slot,
    client_cert_source: Option<CertSource<'a>>,
    verifier: Verifier<'a, M, PHY>,
}

impl<'a, M: RawMutex, PHY> AteccProvider<'a, M, PHY, 0> {
    pub fn new(
        atca: &'a AtCaClient<M, PHY>,
        sign_key: Slot,
        ca_pubkey_source: impl Into<RootCaSource>,
    ) -> Self {
        Self {
            atca,
            sign_key,
            client_cert_source: None,
            verifier: Verifier::Atecc(AteccVerifier::new(atca, ca_pubkey_source)),
        }
    }

    /// Create a provider that skips server certificate verification.
    ///
    /// Useful for development, testing, or connecting to servers with
    /// self-signed certificates. **Not recommended for production use.**
    pub fn new_unverified(atca: &'a AtCaClient<M, PHY>, sign_key: Slot) -> Self {
        Self {
            atca,
            sign_key,
            client_cert_source: None,
            verifier: Verifier::NoVerify(NoVerify),
        }
    }

    /// Enable client certificate authentication for mutual TLS.
    ///
    /// `CERT_SIZE` controls the temporary stack buffer used when
    /// reconstructing a compressed certificate, or copying a DER certificate.
    pub fn with_client_cert<const N: usize>(
        self,
        cert: impl Into<CertSource<'a>>,
    ) -> AteccProvider<'a, M, PHY, N> {
        AteccProvider {
            atca: self.atca,
            sign_key: self.sign_key,
            client_cert_source: Some(cert.into()),
            verifier: self.verifier,
        }
    }
}

impl<'a, M, PHY, const CERT_SIZE: usize> embedded_tls::CryptoProvider
    for AteccProvider<'a, M, PHY, CERT_SIZE>
where
    M: RawMutex,
    PHY: embedded_hal::i2c::I2c,
{
    type CipherSuite = Aes128GcmSha256;
    type Signature = p256::ecdsa::DerSignature;

    fn rng(&mut self) -> impl signature::rand_core::CryptoRngCore {
        self.atca.random()
    }

    fn verifier(&mut self) -> Result<&mut impl TlsVerifier<Self::CipherSuite>, TlsError> {
        Ok(&mut self.verifier)
    }

    fn signer(
        &mut self,
    ) -> Result<(impl signature::SignerMut<Self::Signature>, SignatureScheme), TlsError> {
        Ok((
            self.atca.signer(self.sign_key),
            SignatureScheme::EcdsaSecp256r1Sha256,
        ))
    }

    fn client_cert(&mut self) -> Option<Certificate<impl AsRef<[u8]>>> {
        let source = self.client_cert_source.as_ref()?;
        match source {
            CertSource::Der(der) => Some(Certificate::X509(
                heapless::Vec::<u8, CERT_SIZE>::from_slice(der).ok()?,
            )),
            CertSource::Compressed(def) => {
                let mut buf = [0u8; CERT_SIZE];
                let len = self
                    .atca
                    .memory()
                    .read_certificate_blocking(def, &mut buf)
                    .ok()?;
                Some(Certificate::X509(
                    heapless::Vec::<u8, CERT_SIZE>::from_slice(&buf[..len]).ok()?,
                ))
            }
            CertSource::Lazy(loader) => {
                let mut buf = [0u8; CERT_SIZE];
                let len = loader(&mut buf)?;
                Some(Certificate::X509(
                    heapless::Vec::<u8, CERT_SIZE>::from_slice(&buf[..len]).ok()?,
                ))
            }
        }
    }
}