Skip to main content

hazard3_boot/
verification.rs

1use embedded_storage::nor_flash::{NorFlashError, NorFlashErrorKind};
2
3#[derive(Debug)]
4pub enum VerificationError {
5    Flash(NorFlashErrorKind),
6    Signature(hazard3_crypto::Error),
7}
8
9#[cfg(feature = "defmt")]
10impl defmt::Format for VerificationError {
11    fn format(&self, fmt: defmt::Formatter) {
12        match self {
13            VerificationError::Flash(_) => defmt::write!(fmt, "VerificationError::Flash(_)"),
14            VerificationError::Signature(_) => defmt::write!(fmt, "VerificationError::Signature(_)"),
15        }
16    }
17}
18
19mod sealed {
20    pub trait Sealed {}
21}
22
23/// Wrapper trait for emassy-crypto hashers
24pub trait Digest: sealed::Sealed {
25    /// The output size of the hasher (in bytes)
26    const OUTPUT_SIZE: usize;
27    /// The output type of the hasher
28    type Output: AsRef<[u8]>;
29
30    /// Create a new hasher instance
31    fn new() -> Self;
32    /// Process data, updating the internal state
33    fn update(&mut self, data: &[u8]);
34    /// Retrieve result and consume hasher instance
35    fn finalize(self) -> Self::Output;
36}
37
38macro_rules! impl_digest {
39    ($($t:ident),*) => {$(
40        impl sealed::Sealed for hazard3_crypto::$t {}
41        impl Digest for hazard3_crypto::$t {
42            const OUTPUT_SIZE: usize = <hazard3_crypto::$t>::OUTPUT_SIZE;
43            type Output = [u8; Self::OUTPUT_SIZE];
44            fn new() -> Self {
45                hazard3_crypto::$t::new()
46            }
47            fn update(&mut self, d: &[u8]) {
48                hazard3_crypto::$t::update(self, d)
49            }
50            fn finalize(self) -> [u8; Self::OUTPUT_SIZE] {
51                hazard3_crypto::$t::finalize(self)
52            }
53        }
54    )*};
55}
56
57impl_digest!(Sha1, Sha224, Sha256, Sha384, Sha512, Sha512_224, Sha512_256);
58
59/// Wrapper trait for emassy-crypto signatures
60pub trait Signature {
61    /// The size of the signature (in bytes)
62    const SIGNATURE_SIZE: usize;
63    /// Create a new signature instance from a slice of bytes
64    fn from_bytes(bytes: &[u8]) -> Result<Self, hazard3_crypto::Error>
65    where
66        Self: Sized;
67}
68
69/// Wrapper trait for emassy-crypto verifying keys
70pub trait VerifyingKey: sealed::Sealed {
71    /// The size of the key (in bytes)
72    const KEY_SIZE: usize;
73    /// The signature type associated to this verifying key
74    type Signature: Signature;
75
76    /// Create a new verifying key instance from a slice of bytes
77    fn from_bytes(bytes: &[u8]) -> Result<Self, hazard3_crypto::Error>
78    where
79        Self: Sized;
80
81    /// Verify a message using a signature
82    fn verify(&self, message: &[u8], signature: &Self::Signature) -> Result<(), hazard3_crypto::Error>;
83}
84
85macro_rules! impl_signature_p {
86    ($($t:ident),*) => {$(
87        impl Signature for hazard3_crypto::$t::Signature {
88            const SIGNATURE_SIZE: usize = hazard3_crypto::$t::Signature::SIGNATURE_SIZE;
89            fn from_bytes(b: &[u8]) -> Result<hazard3_crypto::$t::Signature, hazard3_crypto::Error>  {
90                hazard3_crypto::$t::Signature::from_bytes(b.try_into().map_err(|_| hazard3_crypto::Error::InvalidSignature)?)
91            }
92        }
93        impl sealed::Sealed for hazard3_crypto::$t::VerifyingKey {}
94        impl VerifyingKey for hazard3_crypto::$t::VerifyingKey {
95            const KEY_SIZE: usize = hazard3_crypto::$t::SEC1_SIZE;
96            type Signature = hazard3_crypto::$t::Signature;
97            fn from_bytes(b: &[u8]) -> Result<hazard3_crypto::$t::VerifyingKey, hazard3_crypto::Error> {
98                hazard3_crypto::$t::VerifyingKey::from_sec1(b.try_into().map_err(|_| hazard3_crypto::Error::InvalidKey)?)
99            }
100            fn verify(&self, msg: &[u8], signature: &Self::Signature) -> Result<(), hazard3_crypto::Error> {
101                hazard3_crypto::$t::VerifyingKey::verify_prehash(self, msg.try_into().map_err(|_| hazard3_crypto::Error::InvalidInput)?, signature)
102            }
103        }
104    )*};
105}
106
107impl_signature_p!(p256, p384);
108
109impl sealed::Sealed for hazard3_crypto::ed25519::Signature {}
110impl Signature for hazard3_crypto::ed25519::Signature {
111    const SIGNATURE_SIZE: usize = hazard3_crypto::ed25519::Signature::SIGNATURE_SIZE;
112    fn from_bytes(b: &[u8]) -> Result<hazard3_crypto::ed25519::Signature, hazard3_crypto::Error> {
113        Ok(hazard3_crypto::ed25519::Signature::from_bytes(
114            b.try_into().map_err(|_| hazard3_crypto::Error::InvalidSignature)?,
115        ))
116    }
117}
118
119impl sealed::Sealed for hazard3_crypto::ed25519::VerifyingKey {}
120impl VerifyingKey for hazard3_crypto::ed25519::VerifyingKey {
121    const KEY_SIZE: usize = hazard3_crypto::ed25519::VerifyingKey::KEY_SIZE;
122    type Signature = hazard3_crypto::ed25519::Signature;
123    fn from_bytes(b: &[u8]) -> Result<hazard3_crypto::ed25519::VerifyingKey, hazard3_crypto::Error> {
124        Ok(hazard3_crypto::ed25519::VerifyingKey::from_bytes(
125            b.try_into().map_err(|_| hazard3_crypto::Error::InvalidKey)?,
126        ))
127    }
128    fn verify(&self, msg: &[u8], signature: &Self::Signature) -> Result<(), hazard3_crypto::Error> {
129        hazard3_crypto::ed25519::VerifyingKey::verify(self, msg, signature)
130    }
131}
132
133macro_rules! verification_funcs {
134    ($flash: path $(, $async: tt, $await: tt)?) => {
135        pub(crate) $( $async )? fn verify<DFU: $flash, D: Digest, V: VerifyingKey>(
136            dfu: &mut DFU,
137            public_key: &[u8],
138            signature: &[u8],
139            update_len: u32,
140            chunk_buf: &mut [u8],
141        ) -> Result<(), VerificationError> {
142            let public_key = V::from_bytes(public_key)
143                .map_err(|error| VerificationError::Signature(error))?;
144            let signature = V::Signature::from_bytes(signature)
145                .map_err(|error| VerificationError::Signature(error))?;
146
147            let message = hash::<_, D>(dfu, update_len, chunk_buf) $(.$await)?
148                .map_err(|error| VerificationError::Flash(error.kind()))?;
149
150            public_key.verify(message.as_ref(), &signature)
151                .map_err(|error| VerificationError::Signature(error))
152        }
153
154        pub(crate) $( $async )? fn hash<DFU: $flash, D: super::Digest>(
155            dfu: &mut DFU,
156            update_len: u32,
157            chunk_buf: &mut [u8],
158        ) -> Result<D::Output, DFU::Error> {
159            let mut digest = D::new();
160            for offset in (0..update_len).step_by(chunk_buf.len()) {
161                dfu.read(offset, chunk_buf) $(.$await)? ?;
162                let len = chunk_buf.len().min((update_len - offset) as _);
163                digest.update(&chunk_buf[..len]);
164            }
165            Ok(digest.finalize())
166        }
167    };
168}
169
170pub mod blocking {
171    use super::*;
172    verification_funcs!(embedded_storage::nor_flash::ReadNorFlash);
173}
174pub mod asynch {
175    use super::*;
176    verification_funcs!(embedded_storage_async::nor_flash::ReadNorFlash, async, await);
177}
178
179#[cfg(test)]
180mod tests {
181    use hazard3_crypto::{ed25519, p256, p384};
182
183    use super::{Signature, VerifyingKey};
184
185    #[test]
186    fn key_sizes() {
187        // Uncompressed SEC1 points: 0x04 || x || y.
188        assert_eq!(<p256::VerifyingKey as VerifyingKey>::KEY_SIZE, 65);
189        assert_eq!(<p384::VerifyingKey as VerifyingKey>::KEY_SIZE, 97);
190        assert_eq!(<ed25519::VerifyingKey as VerifyingKey>::KEY_SIZE, 32);
191    }
192
193    #[test]
194    fn signature_sizes() {
195        // r || s
196        assert_eq!(<p256::Signature as Signature>::SIGNATURE_SIZE, 64);
197        assert_eq!(<p384::Signature as Signature>::SIGNATURE_SIZE, 96);
198        assert_eq!(<ed25519::Signature as Signature>::SIGNATURE_SIZE, 64);
199    }
200
201    #[test]
202    fn key_size_is_what_from_bytes_takes() {
203        // The P-256 generator point, uncompressed.
204        let generator = [
205            0x04, 0x6B, 0x17, 0xD1, 0xF2, 0xE1, 0x2C, 0x42, 0x47, 0xF8, 0xBC, 0xE6, 0xE5, 0x63, 0xA4, 0x40, 0xF2, 0x77,
206            0x03, 0x7D, 0x81, 0x2D, 0xEB, 0x33, 0xA0, 0xF4, 0xA1, 0x39, 0x45, 0xD8, 0x98, 0xC2, 0x96, 0x4F, 0xE3, 0x42,
207            0xE2, 0xFE, 0x1A, 0x7F, 0x9B, 0x8E, 0xE7, 0xEB, 0x4A, 0x7C, 0x0F, 0x9E, 0x16, 0x2B, 0xCE, 0x33, 0x57, 0x6B,
208            0x31, 0x5E, 0xCE, 0xCB, 0xB6, 0x40, 0x68, 0x37, 0xBF, 0x51, 0xF5,
209        ];
210        assert_eq!(generator.len(), <p256::VerifyingKey as VerifyingKey>::KEY_SIZE);
211        assert!(<p256::VerifyingKey as VerifyingKey>::from_bytes(&generator).is_ok());
212        assert!(<p256::VerifyingKey as VerifyingKey>::from_bytes(&generator[1..]).is_err());
213    }
214}