Skip to main content

at_cryptoauth/
tls.rs

1//! TLS integration with embedded-tls via ATECC608 hardware verification.
2//!
3//! Provides [`AteccProvider`] implementing [`embedded_tls::CryptoProvider`] with
4//! hardware-backed ECDSA verification and signing through the ATECC608 secure element.
5
6use crate::AtCaClient;
7use crate::cert::compressed::CertificateDefinition;
8use crate::command::PublicKey;
9use crate::memory::Slot;
10
11use der::asn1::{
12    AnyRef, BitStringRef, GeneralizedTime, IntRef, ObjectIdentifier, SequenceOf, SetOf, UtcTime,
13};
14use der::{Choice, Decode, Enumerated, Reader, Sequence, SliceReader, ValueOrd};
15use embassy_sync::blocking_mutex::raw::RawMutex;
16use embedded_tls::{
17    Aes128GcmSha256, Certificate, CertificateEntryRef, CertificateRef, CertificateVerifyRef,
18    NoVerify, SignatureScheme, TlsError, TlsVerifier,
19};
20use heapless::Vec;
21use sha2::Digest as _;
22
23use core::cmp::Ordering;
24
25// ---------------------------------------------------------------------------
26// X.509 DER parsing types (local copy — embedded-tls's are private/feature-gated)
27// ---------------------------------------------------------------------------
28
29const COMMON_NAME_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.5.4.3");
30
31const ECDSA_SHA256_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
32
33#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Sequence, ValueOrd)]
34struct AlgorithmIdentifier<'a> {
35    oid: ObjectIdentifier,
36    parameters: Option<AnyRef<'a>>,
37}
38
39#[derive(Debug, Clone, Default, PartialEq, Eq, Copy, Enumerated)]
40#[asn1(type = "INTEGER")]
41#[repr(u8)]
42enum Version {
43    #[default]
44    V1 = 0,
45    V2 = 1,
46    V3 = 2,
47}
48
49impl ValueOrd for Version {
50    fn value_cmp(&self, other: &Self) -> der::Result<Ordering> {
51        (*self as u8).value_cmp(&(*other as u8))
52    }
53}
54
55#[derive(Debug, Choice, ValueOrd)]
56enum Time {
57    #[asn1(type = "UTCTime")]
58    UtcTime(UtcTime),
59    #[asn1(type = "GeneralizedTime")]
60    GeneralTime(GeneralizedTime),
61}
62
63#[derive(Debug, Sequence, ValueOrd)]
64struct Validity {
65    not_before: Time,
66    not_after: Time,
67}
68
69#[derive(Debug, Sequence, ValueOrd)]
70struct AttributeTypeAndValue<'a> {
71    oid: ObjectIdentifier,
72    value: AnyRef<'a>,
73}
74
75#[derive(Debug, Sequence, ValueOrd)]
76struct SubjectPublicKeyInfoRef<'a> {
77    algorithm: AlgorithmIdentifier<'a>,
78    public_key: BitStringRef<'a>,
79}
80
81#[derive(Debug, Sequence, ValueOrd)]
82struct TbsCertificate<'a> {
83    #[asn1(context_specific = "0", default = "Default::default")]
84    version: Version,
85
86    serial_number: IntRef<'a>,
87    signature: AlgorithmIdentifier<'a>,
88    issuer: SequenceOf<SetOf<AttributeTypeAndValue<'a>, 1>, 7>,
89
90    validity: Validity,
91    subject: SequenceOf<SetOf<AttributeTypeAndValue<'a>, 1>, 7>,
92    subject_public_key_info: SubjectPublicKeyInfoRef<'a>,
93
94    #[asn1(context_specific = "1", tag_mode = "IMPLICIT", optional = "true")]
95    issuer_unique_id: Option<BitStringRef<'a>>,
96
97    #[asn1(context_specific = "2", tag_mode = "IMPLICIT", optional = "true")]
98    subject_unique_id: Option<BitStringRef<'a>>,
99
100    #[asn1(context_specific = "3", tag_mode = "EXPLICIT", optional = "true")]
101    extensions: Option<AnyRef<'a>>,
102}
103
104#[derive(Sequence, ValueOrd)]
105struct DecodedCertificate<'a> {
106    tbs_certificate: TbsCertificate<'a>,
107    signature_algorithm: AlgorithmIdentifier<'a>,
108    signature: BitStringRef<'a>,
109}
110
111/// Extract the TBS (to-be-signed) portion as raw TLV bytes from a DER certificate.
112fn get_certificate_tlv_bytes(input: &[u8]) -> Result<&[u8], TlsError> {
113    let mut reader = SliceReader::new(input).map_err(|_| TlsError::DecodeError)?;
114    let top_header = der::Header::decode(&mut reader).map_err(|_| TlsError::DecodeError)?;
115    top_header
116        .tag
117        .assert_eq(der::Tag::Sequence)
118        .map_err(|_| TlsError::DecodeError)?;
119
120    reader.tlv_bytes().map_err(|_| TlsError::DecodeError)
121}
122
123/// Extract the Common Name from a certificate's subject field.
124fn extract_common_name<'a>(
125    subject: &SequenceOf<SetOf<AttributeTypeAndValue<'a>, 1>, 7>,
126) -> Option<heapless::String<64>> {
127    for elems in subject.iter() {
128        if let Some(attr) = elems.get(0)
129            && attr.oid == COMMON_NAME_OID
130        {
131            let mut v: Vec<u8, 64> = Vec::new();
132            v.extend_from_slice(attr.value.value()).ok()?;
133            return heapless::String::from_utf8(v).ok();
134        }
135    }
136    None
137}
138
139/// Convert a SEC1 uncompressed public key (65 bytes, 0x04 prefix) to raw X||Y (64 bytes).
140fn sec1_to_raw_pubkey(sec1: &[u8]) -> Result<PublicKey, TlsError> {
141    if sec1.len() != 65 || sec1[0] != 0x04 {
142        return Err(TlsError::DecodeError);
143    }
144    PublicKey::try_from(&sec1[1..]).map_err(|_| TlsError::DecodeError)
145}
146
147// ---------------------------------------------------------------------------
148// Flexible certificate and CA key sources
149// ---------------------------------------------------------------------------
150
151/// Source for the client certificate presented during mutual TLS.
152pub enum CertSource<'a> {
153    /// Pre-built DER-encoded X.509 certificate.
154    Der(&'a [u8]),
155    /// Compressed certificate reconstructed from ATECC608 at handshake time.
156    Compressed(CertificateDefinition<'a>),
157    /// Certificate loaded on-demand via a loader function.
158    /// The function receives a buffer and returns the number of DER bytes
159    /// written, or `None` on failure.
160    Lazy(fn(&mut [u8]) -> Option<usize>),
161}
162
163impl<'a> From<&'a [u8]> for CertSource<'a> {
164    fn from(der: &'a [u8]) -> Self {
165        Self::Der(der)
166    }
167}
168
169impl<'a> From<CertificateDefinition<'a>> for CertSource<'a> {
170    fn from(def: CertificateDefinition<'a>) -> Self {
171        Self::Compressed(def)
172    }
173}
174
175impl From<fn(&mut [u8]) -> Option<usize>> for CertSource<'_> {
176    fn from(loader: fn(&mut [u8]) -> Option<usize>) -> Self {
177        Self::Lazy(loader)
178    }
179}
180
181/// Source for the root CA public key used to verify the server certificate chain.
182pub enum RootCaSource {
183    /// Raw 64-byte X||Y public key (provided directly or extracted from DER).
184    Key(PublicKey),
185    /// Public key read from an ATECC slot at verification time.
186    Stored(Slot),
187}
188
189impl From<PublicKey> for RootCaSource {
190    fn from(key: PublicKey) -> Self {
191        Self::Key(key)
192    }
193}
194
195impl From<Slot> for RootCaSource {
196    fn from(slot: Slot) -> Self {
197        Self::Stored(slot)
198    }
199}
200
201impl TryFrom<&[u8]> for RootCaSource {
202    type Error = TlsError;
203
204    /// Parse a DER-encoded X.509 certificate and extract the subject public key.
205    fn try_from(der: &[u8]) -> Result<Self, TlsError> {
206        let parsed = DecodedCertificate::from_der(der).map_err(|_| TlsError::DecodeError)?;
207        let spki_bytes = parsed
208            .tbs_certificate
209            .subject_public_key_info
210            .public_key
211            .as_bytes()
212            .ok_or(TlsError::DecodeError)?;
213        Ok(Self::Key(sec1_to_raw_pubkey(spki_bytes)?))
214    }
215}
216
217// ---------------------------------------------------------------------------
218// AteccVerifier
219// ---------------------------------------------------------------------------
220
221pub struct AteccVerifier<'a, M: RawMutex, PHY> {
222    atca: &'a AtCaClient<M, PHY>,
223    ca_pubkey_source: RootCaSource,
224    host: Option<heapless::String<64>>,
225    certificate_transcript: Option<[u8; 32]>,
226    server_public_key: Option<PublicKey>,
227}
228
229impl<'a, M: RawMutex, PHY> AteccVerifier<'a, M, PHY> {
230    fn new(atca: &'a AtCaClient<M, PHY>, ca_pubkey_source: impl Into<RootCaSource>) -> Self {
231        Self {
232            atca,
233            ca_pubkey_source: ca_pubkey_source.into(),
234            host: None,
235            certificate_transcript: None,
236            server_public_key: None,
237        }
238    }
239}
240
241impl<M, PHY> TlsVerifier<Aes128GcmSha256> for AteccVerifier<'_, M, PHY>
242where
243    M: RawMutex,
244    PHY: embedded_hal::i2c::I2c,
245{
246    fn set_hostname_verification(&mut self, hostname: &str) -> Result<(), TlsError> {
247        self.host.replace(
248            heapless::String::try_from(hostname).map_err(|_| TlsError::InsufficientSpace)?,
249        );
250        Ok(())
251    }
252
253    fn verify_certificate(
254        &mut self,
255        transcript: &sha2::Sha256,
256        cert: CertificateRef,
257    ) -> Result<(), TlsError> {
258        // Resolve CA public key from the configured source
259        let mut ca_pubkey = match &self.ca_pubkey_source {
260            RootCaSource::Key(key) => *key,
261            RootCaSource::Stored(slot) => self
262                .atca
263                .memory()
264                .pubkey_blocking(*slot)
265                .map_err(|_| TlsError::InvalidCertificate)?,
266        };
267
268        // Trust is anchored on this configured key, not on a server-presented
269        // copy of the root. Kept separate from `ca_pubkey`, which mutates as we
270        // descend the chain.
271        let anchor_pubkey = ca_pubkey;
272
273        let mut cn = None;
274
275        // Walk the chain from the entry closest to CA (last) down to the leaf (first).
276        // Each entry is verified against the current verifier public key.
277        let num_entries = cert.entries.len();
278        for i in (0..num_entries).rev() {
279            let cert_data = match &cert.entries[i] {
280                CertificateEntryRef::X509(data) => *data,
281                _ => return Err(TlsError::DecodeError),
282            };
283
284            let parsed =
285                DecodedCertificate::from_der(cert_data).map_err(|_| TlsError::DecodeError)?;
286
287            // Extract this cert's public key up front so a server-presented copy
288            // of the trust anchor can be recognised before any verification.
289            let spki_bytes = parsed
290                .tbs_certificate
291                .subject_public_key_info
292                .public_key
293                .as_bytes()
294                .ok_or(TlsError::DecodeError)?;
295            let cert_pubkey = sec1_to_raw_pubkey(spki_bytes)?;
296
297            // A server MAY include the (cross-signed) root in the chain
298            // (RFC 8446 4.4.2). We already trust the anchor by its public key, so
299            // skip a presented copy of it rather than verifying it. The
300            // cross-signed Amazon Root CA 3 is RSA-signed and would otherwise
301            // trip the ECDSA-only check below.
302            if cert_pubkey.as_ref() == anchor_pubkey.as_ref() {
303                continue;
304            }
305
306            // Only ECDSA P-256 SHA-256 is supported by the ATECC608
307            if parsed.signature_algorithm.oid != ECDSA_SHA256_OID {
308                return Err(TlsError::InvalidSignatureScheme);
309            }
310
311            // Hash the TBS data with software SHA-256
312            let tbs_data = get_certificate_tlv_bytes(cert_data)?;
313            let hash = sha2::Sha256::digest(tbs_data);
314
315            // Convert hash to ATECC Digest
316            let digest =
317                crate::Digest::try_from(hash.as_slice()).map_err(|_| TlsError::CryptoError)?;
318
319            // Convert DER signature to p256::ecdsa::Signature (raw R||S internally)
320            let sig_bytes = parsed.signature.as_bytes().ok_or(TlsError::DecodeError)?;
321            let signature = p256::ecdsa::Signature::from_der(sig_bytes)
322                .map_err(|_| TlsError::InvalidSignature)?;
323
324            // Verify using ATECC hardware
325            self.atca
326                .verify_external_blocking(&digest, &signature, &ca_pubkey)
327                .map_err(|_| TlsError::InvalidCertificate)?;
328
329            if i == 0 {
330                // Leaf certificate — extract CN and store server public key
331                cn = extract_common_name(&parsed.tbs_certificate.subject);
332                self.server_public_key = Some(cert_pubkey);
333            } else {
334                // Intermediate — use its public key to verify the next cert down
335                ca_pubkey = cert_pubkey;
336            }
337        }
338
339        // Hostname verification (supports leading wildcard, e.g. *.example.com)
340        if let Some(ref host) = self.host {
341            let ok = match cn {
342                Some(ref cn) => {
343                    if let Some(wildcard_rest) = cn.strip_prefix("*.") {
344                        // Wildcard: host must have at least one label before the
345                        // matching suffix, and must not itself be a wildcard.
346                        match host.find('.') {
347                            Some(dot) => host[dot + 1..] == *wildcard_rest,
348                            None => false,
349                        }
350                    } else {
351                        host.as_str() == cn.as_str()
352                    }
353                }
354                None => false,
355            };
356            if !ok {
357                return Err(TlsError::InvalidCertificate);
358            }
359        }
360
361        self.certificate_transcript = Some(transcript.clone().finalize().into());
362        Ok(())
363    }
364
365    fn verify_signature(&mut self, verify: CertificateVerifyRef) -> Result<(), TlsError> {
366        if verify.signature_scheme != SignatureScheme::EcdsaSecp256r1Sha256 {
367            return Err(TlsError::InvalidSignatureScheme);
368        }
369
370        let server_pubkey = self
371            .server_public_key
372            .as_ref()
373            .ok_or(TlsError::InvalidCertificate)?;
374
375        // Build the verification message per RFC 8446 §4.4.3
376        let handshake_hash = self
377            .certificate_transcript
378            .take()
379            .ok_or(TlsError::InvalidHandshake)?;
380
381        let ctx_str = b"TLS 1.3, server CertificateVerify\x00";
382        let mut msg: Vec<u8, 146> = Vec::new();
383        msg.resize(64, 0x20)
384            .map_err(|_| TlsError::InsufficientSpace)?;
385        msg.extend_from_slice(ctx_str)
386            .map_err(|_| TlsError::InsufficientSpace)?;
387        msg.extend_from_slice(&handshake_hash)
388            .map_err(|_| TlsError::InsufficientSpace)?;
389
390        // Hash the verification message with software SHA-256
391        let hash = sha2::Sha256::digest(&msg);
392        let digest = crate::Digest::try_from(hash.as_slice()).map_err(|_| TlsError::CryptoError)?;
393
394        // Convert DER signature
395        let signature = p256::ecdsa::Signature::from_der(verify.signature)
396            .map_err(|_| TlsError::InvalidSignature)?;
397
398        // Verify using ATECC hardware
399        self.atca
400            .verify_external_blocking(&digest, &signature, server_pubkey)
401            .map_err(|_| TlsError::InvalidSignature)?;
402
403        Ok(())
404    }
405}
406
407// ---------------------------------------------------------------------------
408// Verifier — dispatches to AteccVerifier or NoVerify
409// ---------------------------------------------------------------------------
410
411#[allow(clippy::large_enum_variant)]
412enum Verifier<'a, M: RawMutex, PHY> {
413    Atecc(AteccVerifier<'a, M, PHY>),
414    NoVerify(NoVerify),
415}
416
417impl<M, PHY> TlsVerifier<Aes128GcmSha256> for Verifier<'_, M, PHY>
418where
419    M: RawMutex,
420    PHY: embedded_hal::i2c::I2c,
421{
422    fn set_hostname_verification(&mut self, hostname: &str) -> Result<(), TlsError> {
423        match self {
424            Self::Atecc(v) => v.set_hostname_verification(hostname),
425            Self::NoVerify(v) => {
426                <NoVerify as TlsVerifier<Aes128GcmSha256>>::set_hostname_verification(v, hostname)
427            }
428        }
429    }
430
431    fn verify_certificate(
432        &mut self,
433        transcript: &sha2::Sha256,
434        cert: CertificateRef,
435    ) -> Result<(), TlsError> {
436        match self {
437            Self::Atecc(v) => v.verify_certificate(transcript, cert),
438            Self::NoVerify(v) => {
439                <NoVerify as TlsVerifier<Aes128GcmSha256>>::verify_certificate(v, transcript, cert)
440            }
441        }
442    }
443
444    fn verify_signature(&mut self, verify: CertificateVerifyRef) -> Result<(), TlsError> {
445        match self {
446            Self::Atecc(v) => v.verify_signature(verify),
447            Self::NoVerify(v) => {
448                <NoVerify as TlsVerifier<Aes128GcmSha256>>::verify_signature(v, verify)
449            }
450        }
451    }
452}
453
454// ---------------------------------------------------------------------------
455// AteccProvider
456// ---------------------------------------------------------------------------
457
458pub struct AteccProvider<'a, M: RawMutex, PHY, const CERT_SIZE: usize = 0> {
459    atca: &'a AtCaClient<M, PHY>,
460    sign_key: Slot,
461    client_cert_source: Option<CertSource<'a>>,
462    verifier: Verifier<'a, M, PHY>,
463}
464
465impl<'a, M: RawMutex, PHY> AteccProvider<'a, M, PHY, 0> {
466    pub fn new(
467        atca: &'a AtCaClient<M, PHY>,
468        sign_key: Slot,
469        ca_pubkey_source: impl Into<RootCaSource>,
470    ) -> Self {
471        Self {
472            atca,
473            sign_key,
474            client_cert_source: None,
475            verifier: Verifier::Atecc(AteccVerifier::new(atca, ca_pubkey_source)),
476        }
477    }
478
479    /// Create a provider that skips server certificate verification.
480    ///
481    /// Useful for development, testing, or connecting to servers with
482    /// self-signed certificates. **Not recommended for production use.**
483    pub fn new_unverified(atca: &'a AtCaClient<M, PHY>, sign_key: Slot) -> Self {
484        Self {
485            atca,
486            sign_key,
487            client_cert_source: None,
488            verifier: Verifier::NoVerify(NoVerify),
489        }
490    }
491
492    /// Enable client certificate authentication for mutual TLS.
493    ///
494    /// `CERT_SIZE` controls the temporary stack buffer used when
495    /// reconstructing a compressed certificate, or copying a DER certificate.
496    pub fn with_client_cert<const N: usize>(
497        self,
498        cert: impl Into<CertSource<'a>>,
499    ) -> AteccProvider<'a, M, PHY, N> {
500        AteccProvider {
501            atca: self.atca,
502            sign_key: self.sign_key,
503            client_cert_source: Some(cert.into()),
504            verifier: self.verifier,
505        }
506    }
507}
508
509impl<'a, M, PHY, const CERT_SIZE: usize> embedded_tls::CryptoProvider
510    for AteccProvider<'a, M, PHY, CERT_SIZE>
511where
512    M: RawMutex,
513    PHY: embedded_hal::i2c::I2c,
514{
515    type CipherSuite = Aes128GcmSha256;
516    type Signature = p256::ecdsa::DerSignature;
517
518    fn rng(&mut self) -> impl signature::rand_core::CryptoRngCore {
519        self.atca.random()
520    }
521
522    fn verifier(&mut self) -> Result<&mut impl TlsVerifier<Self::CipherSuite>, TlsError> {
523        Ok(&mut self.verifier)
524    }
525
526    fn signer(
527        &mut self,
528    ) -> Result<(impl signature::SignerMut<Self::Signature>, SignatureScheme), TlsError> {
529        Ok((
530            self.atca.signer(self.sign_key),
531            SignatureScheme::EcdsaSecp256r1Sha256,
532        ))
533    }
534
535    fn client_cert(&mut self) -> Option<Certificate<impl AsRef<[u8]>>> {
536        let source = self.client_cert_source.as_ref()?;
537        match source {
538            CertSource::Der(der) => Some(Certificate::X509(
539                heapless::Vec::<u8, CERT_SIZE>::from_slice(der).ok()?,
540            )),
541            CertSource::Compressed(def) => {
542                let mut buf = [0u8; CERT_SIZE];
543                let len = self
544                    .atca
545                    .memory()
546                    .read_certificate_blocking(def, &mut buf)
547                    .ok()?;
548                Some(Certificate::X509(
549                    heapless::Vec::<u8, CERT_SIZE>::from_slice(&buf[..len]).ok()?,
550                ))
551            }
552            CertSource::Lazy(loader) => {
553                let mut buf = [0u8; CERT_SIZE];
554                let len = loader(&mut buf)?;
555                Some(Certificate::X509(
556                    heapless::Vec::<u8, CERT_SIZE>::from_slice(&buf[..len]).ok()?,
557                ))
558            }
559        }
560    }
561}