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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
//! Abstraction allowing use of either PKCS1 PEM file or PKCS11 keys
//! for signing data.

use std::convert::{TryFrom, TryInto};
use std::{fmt, fs};

use anyhow::{Context as _, Result};
use rsa::pkcs1::{DecodeRsaPrivateKey as _, DecodeRsaPublicKey as _};
use serde::{Deserialize, Serialize};
use x509_parser::{certificate::X509Certificate, prelude::FromDer as _};

use crate::util::is_default;

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SigningKeySource {
    Pkcs1PemFile(std::path::PathBuf),
    Pkcs11Uri(std::string::String),
}

pub fn split_once(s: &str, delimiter: char) -> Option<(&str, &str)> {
    let i = s.find(delimiter)?;
    Some((&s[..i], &s[i + 1..]))
}

/// Specification of PKI for secure (signed) boot.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
#[serde(deny_unknown_fields)]
pub struct Pki {
    /// URI specifying the private RSA2K key used for signing firmware.
    ///
    /// Currently, two options are supported
    /// - `file:` path to PKCS #1 encoded PEM file containing private key
    /// - `pkcs11:` PKCS #11 URI (RFC 7512), with the extension that `pin-source` can be `env:PIN`.
    ///
    /// Note that in PKCS #11 URIs, whitespace is stripped, and must be percent-encoded (`%20`) if
    /// it is significant, such as in token or object labels.
    ///
    /// Examples:
    /// - `file:/path/to/ca-0-private-key.pem`
    /// - `pkcs11:token=my-ca;object=signing-key;type=private?module-path=/usr/lib/libsofthsm2.so&pin-source=file:pin.txt`
    #[serde(skip_serializing_if = "is_default")]
    #[serde(default)]
    pub signing_key: String,

    /// Paths to the four root certificates.
    ///
    /// The appropriate certificate to include in signed firmware and containers is selected
    /// using the signing key's public key.
    ///
    /// Encoded as X.509 DER files.
    pub certificates: [CertificateUriChain; 4],
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
#[serde(untagged)]
pub enum CertificateUriChain {
    Root(String),
    Chain {
        root: String,
        #[serde(default)]
        chain: Vec<String>,
    },
}

impl CertificateUriChain {
    pub fn root(&self) -> &str {
        match self {
            Self::Root(r) => r,
            Self::Chain { root, chain: _ } => root,
        }
    }

    pub fn chain(&self) -> &[String] {
        match self {
            Self::Root(_) => &[],
            Self::Chain { root: _, chain } => chain,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
/// Type enabling `lpc55 rotkh` to share config file with the secure/signed
/// firmware generation commands. Serializes `Pki` with a `[pki]` header.
pub struct WrappedPki {
    pub pki: Pki,
}

impl TryFrom<&'_ str> for Pki {
    type Error = anyhow::Error;
    fn try_from(config_filename: &str) -> anyhow::Result<Self> {
        let config = fs::read_to_string(config_filename)
            .with_context(|| format!("Failed to read config from {}", config_filename))?;
        let wrapped_pki: WrappedPki = toml::from_str(&config)?;
        let pki = wrapped_pki.pki;
        trace!("{:#?}", &pki);
        Ok(pki)
    }
}

impl TryFrom<&'_ str> for SigningKeySource {
    type Error = anyhow::Error;
    fn try_from(uri: &str) -> anyhow::Result<Self> {
        let (scheme, content) = split_once(uri, ':').unwrap();
        let key_source = match scheme {
            "file" => SigningKeySource::Pkcs1PemFile(std::path::PathBuf::from(content)),
            "pkcs11" => SigningKeySource::Pkcs11Uri(uri.to_string()),
            _ => {
                return Err(anyhow::anyhow!(
                    "only file and pkcs11 secret key URIs supported"
                ))
            }
        };
        Ok(key_source)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum SigningKey {
    Pkcs1(rsa::RsaPrivateKey),
    Pkcs11Uri(pkcs11_uri::Pkcs11Uri),
}

/// An RSA2k public key
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PublicKey(pub rsa::RsaPublicKey);

impl PublicKey {
    pub fn fingerprint(&self) -> Sha256Hash {
        use rsa::PublicKeyParts as _;
        let n = self.0.n();
        let e = self.0.e();

        use sha2::Digest;
        let mut hasher = sha2::Sha256::new();
        hasher.update(n.to_bytes_be());
        hasher.update(e.to_bytes_be());
        let hash = <[u8; 32]>::try_from(hasher.finalize()).unwrap();
        Sha256Hash(hash)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Signature(pub Vec<u8>);

impl SigningKey {
    pub fn try_from_uri(uri: &str) -> anyhow::Result<Self> {
        let source = SigningKeySource::try_from(uri)?;
        Self::try_load(&source)
    }

    pub fn try_load(source: &SigningKeySource) -> anyhow::Result<SigningKey> {
        use SigningKeySource::*;
        Ok(match source {
            Pkcs1PemFile(path) => {
                let pem = std::fs::read_to_string(path).with_context(|| {
                    format!(
                        "Failed to read private key from PEM file {}",
                        path.display()
                    )
                })?;
                // do this instead:
                // https://docs.rs/rsa/0.3.0/rsa/struct.RsaPrivateKey.html?search=#example
                let der = pem::parse(pem)?.contents;
                let key = rsa::RsaPrivateKey::from_pkcs1_der(&der)?;
                SigningKey::Pkcs1(key)
            }
            Pkcs11Uri(uri) => {
                let uri = pkcs11_uri::Pkcs11Uri::try_from(uri)?;
                SigningKey::Pkcs11Uri(uri)
            }
        })
    }

    pub fn sign(&self, data: &[u8]) -> Signature {
        use SigningKey::*;
        let signature = match self {
            Pkcs1(key) => {
                let padding_scheme =
                    rsa::PaddingScheme::new_pkcs1v15_sign(Some(rsa::Hash::SHA2_256));

                use sha2::Digest;
                let mut hasher = sha2::Sha256::new();
                hasher.update(data);
                let hashed_data = hasher.finalize();
                key.sign(padding_scheme, &hashed_data)
                    .expect("signatures work")
            }
            Pkcs11Uri(uri) => {
                let (context, session, object) = uri.identify_object().unwrap();

                //  CKM_SHA256_RSA_PKCS
                let mechanism = pkcs11::types::CK_MECHANISM {
                    mechanism: pkcs11::types::CKM_SHA256_RSA_PKCS,
                    pParameter: std::ptr::null_mut(),
                    ulParameterLen: 0,
                };

                // now do a signature, assuming this is an RSA key
                context.sign_init(session, &mechanism, object).unwrap();
                context.sign(session, data).unwrap()
            }
        };
        Signature(signature)
    }

    pub fn public_key(&self) -> PublicKey {
        use SigningKey::*;
        PublicKey(match self {
            Pkcs1(key) => key.to_public_key(),
            Pkcs11Uri(uri) => {
                let (context, session, object) = uri.identify_object().unwrap();

                use pkcs11::types::{CKA_MODULUS, CKA_PUBLIC_EXPONENT, CK_ATTRIBUTE};

                let /*mut*/ n_buffer = [0u8; 256]; // rust-pkcs11 API is sloppy about mut here; 256B = 2048b is enough for RSA2k keys
                let /*mut*/ e_buffer = [0u8; 3]; // always 0x10001 = u16::MAX + 2 anyway
                let mut n_attribute = CK_ATTRIBUTE::new(CKA_MODULUS);
                n_attribute.set_biginteger(&n_buffer);
                let mut e_attribute = CK_ATTRIBUTE::new(CKA_PUBLIC_EXPONENT);
                e_attribute.set_biginteger(&e_buffer);
                let mut template = vec![n_attribute, e_attribute];

                let (rv, attributes) = context
                    .get_attribute_value(session, object, &mut template)
                    .unwrap();
                assert_eq!(rv, 0);
                let n = attributes[0].get_biginteger().unwrap();
                let e = attributes[1].get_biginteger().unwrap();
                assert!(n.bits() > 2012 && n.bits() <= 2048);
                // dbg!(n.to_str_radix(10));
                assert_eq!(e.to_str_radix(10), "65537");

                // https://github.com/mheese/rust-pkcs11/issues/44
                let n = rsa::BigUint::from_bytes_be(&n.to_bytes_le());
                let e = rsa::BigUint::from_bytes_be(&e.to_bytes_le());
                rsa::RsaPublicKey::new(n, e).unwrap()
            }
        })
    }

    pub fn fingerprint(&self) -> Sha256Hash {
        self.public_key().fingerprint()
    }
}

impl<'a> core::convert::TryFrom<&'a [u8]> for Signature {
    type Error = signature::Error;

    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
        Ok(Signature(Vec::from(bytes)))
    }
}

impl signature::Signature for Signature {
    fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    fn from_bytes(bytes: &[u8]) -> Result<Self, signature::Error> {
        bytes.try_into()
    }
}

impl AsRef<[u8]> for Signature {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl signature::Signer<Signature> for SigningKey {
    fn try_sign(&self, data: &[u8]) -> Result<Signature, signature::Error> {
        Ok(self.sign(data))
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
pub struct CertificateSlot(usize);

// This should not be necessary; not having it would prevent
// negligence errors like "Default::default.into()".
impl From<usize> for CertificateSlot {
    /// panics if i > 3
    fn from(i: usize) -> Self {
        if i <= 3 {
            Self(i)
        } else {
            panic!("Index {} not one of 0, 1, 2, 3", i);
        }
    }
}

impl From<CertificateSlot> for usize {
    /// panics if i > 3
    fn from(i: CertificateSlot) -> usize {
        i.0
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CertificateSource {
    X509DerFile(std::path::PathBuf),
    Pkcs11Uri(std::string::String),
    // RawDer(Vec<u8>),
}

impl TryFrom<&'_ str> for CertificateSource {
    type Error = anyhow::Error;
    fn try_from(uri: &str) -> anyhow::Result<Self> {
        let (scheme, content) = split_once(uri, ':').unwrap();
        let key_source = match scheme {
            "file" => CertificateSource::X509DerFile(std::path::PathBuf::from(content)),
            "pkcs11" => CertificateSource::Pkcs11Uri(uri.to_string()),
            _ => {
                return Err(anyhow::anyhow!(
                    "only file and pkcs11 certificate URIs supported"
                ))
            }
        };
        Ok(key_source)
    }
}

#[derive(Clone, Debug)]
pub struct Certificate {
    der: Vec<u8>,
}

impl Certificate {
    // todo: consider offering pkcs11-uri here too
    pub fn try_from(source: &CertificateSource) -> Result<Self> {
        use CertificateSource::*;
        let der = match source {
            X509DerFile(filename) => fs::read(filename).with_context(|| {
                format!(
                    "Failed to read certificate from DER file {}",
                    filename.display()
                )
            })?,
            Pkcs11Uri(uri) => {
                use pkcs11::types::{CKA_VALUE, CK_ATTRIBUTE};

                let uri = pkcs11_uri::Pkcs11Uri::try_from(uri)?;
                let (context, session, object) = uri.identify_object()?;

                let buffer = [0u8; 4096];
                let /*mut*/ attribute = CK_ATTRIBUTE::new(CKA_VALUE).with_bytes(&buffer);
                let mut template = vec![attribute];
                let (rv, _attributes) = context
                    .get_attribute_value(session, object, &mut template)
                    .unwrap();
                // compiler hint?
                let attribute = _attributes[0];
                assert_eq!(rv, 0);

                let value = attribute.get_bytes()?;
                trace!("certificate DER:\n{}", hex_str!(&value, 32));
                value
            }
        };
        Certificate::try_from_der(&der)
    }

    /// Checks certificate is valid, and public key is RSA.
    pub fn try_from_der(der: &[u8]) -> Result<Self> {
        // implicitly checks public key is RSA
        let _ = Self::cert_fingerprint(X509Certificate::from_der(der)?.1)?;
        Ok(Self {
            der: Vec::from(der),
        })
    }

    fn cert_fingerprint(certificate: X509Certificate<'_>) -> Result<Sha256Hash> {
        let spki = certificate.tbs_certificate.subject_pki;
        trace!("alg: {:?}", spki.algorithm.algorithm);
        // let OID_RSA_ENCRYPTION = oid!(1.2.840.113549.1.1.1);
        assert_eq!(
            oid_registry::OID_PKCS1_RSAENCRYPTION,
            spki.algorithm.algorithm
        );

        let public_key = PublicKey(rsa::RsaPublicKey::from_pkcs1_der(
            &spki.subject_public_key.data,
        )?);
        Ok(public_key.fingerprint())
    }

    pub fn certificate(&self) -> X509Certificate<'_> {
        // no panic, DER is verified in constructor
        X509Certificate::from_der(&self.der).unwrap().1
    }

    pub fn der(&self) -> &[u8] {
        &self.der
    }

    pub fn public_key(&self) -> PublicKey {
        let spki = self.certificate().tbs_certificate.subject_pki;
        assert_eq!(
            oid_registry::OID_PKCS1_RSAENCRYPTION,
            spki.algorithm.algorithm
        );
        PublicKey(rsa::RsaPublicKey::from_pkcs1_der(&spki.subject_public_key.data).unwrap())
    }

    pub fn fingerprint(&self) -> Sha256Hash {
        // no panic, DER is verified in constructor
        Self::cert_fingerprint(self.certificate()).unwrap()
    }
}

#[derive(Clone, Debug)]
pub struct CertificateChain {
    root: Certificate,
    chain: Vec<Certificate>,
}

impl CertificateChain {
    pub fn from_root(root: Certificate) -> Self {
        Self {
            root,
            chain: vec![],
        }
    }

    pub fn try_from(uris: &CertificateUriChain) -> Result<Self> {
        let root = Certificate::try_from(&uris.root().try_into()?)?;
        let chain: Result<Vec<_>, _> = uris
            .chain()
            .iter()
            .map(|uri| {
                let s: &str = uri;
                Certificate::try_from(&s.try_into()?)
            })
            .collect();
        Ok(CertificateChain {
            root,
            chain: chain?,
        })
    }

    pub fn signer(&self) -> &Certificate {
        self.chain.last().unwrap_or(&self.root)
    }

    pub fn root(&self) -> &Certificate {
        &self.root
    }

    /// Returns an iterator over the chain, starting with the root certificate
    pub fn all(&self) -> impl Iterator<Item = &Certificate> {
        std::iter::once(&self.root).chain(self.chain.iter())
    }

    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        1 + self.chain.len()
    }
}

#[derive(Clone, Debug)]
pub struct Certificates {
    chains: [CertificateChain; 4],
}

impl Certificates {
    pub fn try_from_pki(pki: &Pki) -> Result<Self> {
        let chains = [
            CertificateChain::try_from(&pki.certificates[0])?,
            CertificateChain::try_from(&pki.certificates[1])?,
            CertificateChain::try_from(&pki.certificates[2])?,
            CertificateChain::try_from(&pki.certificates[3])?,
        ];

        Ok(Certificates { chains })
    }

    // todo: consider using pkcs11-uri here too
    pub fn try_from(sources: &[CertificateSource; 4]) -> Result<Self> {
        Ok(Self {
            chains: [
                CertificateChain::from_root(Certificate::try_from(&sources[0])?),
                CertificateChain::from_root(Certificate::try_from(&sources[1])?),
                CertificateChain::from_root(Certificate::try_from(&sources[2])?),
                CertificateChain::from_root(Certificate::try_from(&sources[3])?),
            ],
        })
    }

    /// Checks certificates are valid, and public keys are all RSA.
    pub fn try_from_ders(certificate_ders: [Vec<u8>; 4]) -> Result<Self> {
        Ok(Self {
            chains: [
                CertificateChain::from_root(Certificate::try_from_der(&certificate_ders[0])?),
                CertificateChain::from_root(Certificate::try_from_der(&certificate_ders[1])?),
                CertificateChain::from_root(Certificate::try_from_der(&certificate_ders[2])?),
                CertificateChain::from_root(Certificate::try_from_der(&certificate_ders[3])?),
            ],
        })
    }

    pub fn index_of(&self, public_key: PublicKey) -> Result<CertificateSlot> {
        for i in 0..4 {
            let slot = CertificateSlot(i);
            if public_key == self.certificate(slot).public_key() {
                return Ok(slot);
            }
        }
        Err(anyhow::anyhow!(
            "no matching certificate found for public key!"
        ))
    }

    /// Get the end of chain certificate from the chain
    pub fn certificate(&self, i: CertificateSlot) -> &Certificate {
        self.chains[usize::from(i)].signer()
    }

    /// Get the DER reprensentation for the end of chain certificate from the chain
    pub fn certificate_der(&self, i: CertificateSlot) -> &[u8] {
        self.certificate(i).der()
    }

    /// Returns an iterator of the DER serialization of the certificate chain starting at the root
    pub fn chain_der(&self, i: CertificateSlot) -> impl Iterator<Item = &[u8]> {
        self.chains[usize::from(i)].all().map(|c| c.der())
    }

    pub fn chain(&self, i: CertificateSlot) -> &CertificateChain {
        &self.chains[usize::from(i)]
    }

    /// Get the fingerprint of the 4 root certificates
    pub fn fingerprints(&self) -> [Sha256Hash; 4] {
        // array_map when? :)
        [
            self.chains[0].root().fingerprint(),
            self.chains[1].root().fingerprint(),
            self.chains[2].root().fingerprint(),
            self.chains[3].root().fingerprint(),
        ]
    }

    pub fn fingerprint(&self) -> Sha256Hash {
        use sha2::Digest;
        let mut hash = sha2::Sha256::new();
        for fingerprint in self.fingerprints().iter() {
            hash.update(fingerprint);
        }
        let hash = <[u8; 32]>::try_from(hash.finalize()).unwrap();
        Sha256Hash(hash)
    }

    pub fn fingerprint_from_bytes(fingerprints: &[u8]) -> Sha256Hash {
        use sha2::Digest;
        let mut hash = sha2::Sha256::new();
        hash.update(fingerprints);
        let hash = <[u8; 32]>::try_from(hash.finalize()).unwrap();
        Sha256Hash(hash)
    }
}

#[derive(Clone, Copy, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Sha256Hash(pub [u8; 32]);
impl fmt::Debug for Sha256Hash {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        format_bytes(&self.0, f)
    }
}

impl AsRef<[u8]> for Sha256Hash {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl From<[u8; 32]> for Sha256Hash {
    fn from(array: [u8; 32]) -> Self {
        Sha256Hash(array)
    }
}

pub(crate) fn format_bytes(bytes: &[u8], f: &mut fmt::Formatter<'_>) -> fmt::Result {
    // let l = bytes.len();
    let empty = bytes.iter().all(|&byte| byte == 0);
    if empty {
        // return f.write_fmt(format_args!("<all zero>"));
        return f.write_fmt(format_args!("∅"));
    }

    for byte in bytes.iter() {
        f.write_fmt(format_args!("{:02X} ", byte))?;
    }
    Ok(())
    // let info = if empty { "empty" } else { "non-empty" };

    // f.write_fmt(format_args!(
    //     "'{:02x} {:02x} {:02x} (...) {:02x} {:02x} {:02x} ({})'",
    //     bytes[0], bytes[1], bytes[3],
    //     bytes[l-3], bytes[l-2], bytes[l-1],
    //     info,
    // ))
}