summaryrefslogtreecommitdiffstats
path: root/crates/common/certificate/src/lib.rs
blob: 0c81a73d800918d58dd5fdc3c00519c3294ecc76 (plain)
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
use device_id::DeviceIdError;
use rcgen::Certificate;
use rcgen::CertificateParams;
use rcgen::RcgenError;
use sha1::{Digest, Sha1};
use std::path::Path;
use time::{Duration, OffsetDateTime};
use zeroize::Zeroizing;

pub mod device_id;
pub struct PemCertificate {
    pem: x509_parser::pem::Pem,
}

impl PemCertificate {
    pub fn from_pem_file(path: impl AsRef<Path>) -> Result<PemCertificate, CertificateError> {
        let file = std::fs::File::open(path)?;
        let (pem, _) = x509_parser::pem::Pem::read(std::io::BufReader::new(file))?;
        Ok(PemCertificate { pem })
    }

    pub fn from_pem_string(content: &str) -> Result<PemCertificate, CertificateError> {
        let file = std::io::Cursor::new(content.as_bytes());
        let (pem, _) = x509_parser::pem::Pem::read(std::io::BufReader::new(file))?;
        Ok(PemCertificate { pem })
    }

    pub fn subject(&self) -> Result<String, CertificateError> {
        let x509 = PemCertificate::extract_certificate(&self.pem)?;
        Ok(x509.tbs_certificate.subject.to_string())
    }

    pub fn subject_common_name(&self) -> Result<String, CertificateError> {
        let x509 = PemCertificate::extract_certificate(&self.pem)?;
        let subject = x509.tbs_certificate.subject;
        let cn = subject.iter_common_name().next().map(|cn| cn.as_str());

        match cn {
            None => Ok(String::from("")),
            Some(Ok(name)) => Ok(name.to_owned()),
            Some(Err(err)) => Err(PemCertificate::wrap_x509_error(err)),
        }
    }

    pub fn issuer(&self) -> Result<String, CertificateError> {
        let x509 = PemCertificate::extract_certificate(&self.pem)?;
        Ok(x509.tbs_certificate.issuer.to_string())
    }

    pub fn not_before(&self) -> Result<String, CertificateError> {
        let x509 = PemCertificate::extract_certificate(&self.pem)?;
        x509.tbs_certificate
            .validity
            .not_before
            .to_rfc2822()
            .map_err(CertificateError::X509Error)
    }

    pub fn not_after(&self) -> Result<String, CertificateError> {
        let x509 = PemCertificate::extract_certificate(&self.pem)?;
        x509.tbs_certificate
            .validity
            .not_after
            .to_rfc2822()
            .map_err(CertificateError::X509Error)
    }

    pub fn thumbprint(&self) -> Result<String, CertificateError> {
        let bytes = Sha1::digest(&self.pem.contents).as_slice().to_vec();
        let strs: Vec<String> = bytes.iter().map(|b| format!("{:02X}", b)).collect();
        Ok(strs.concat())
    }

    fn extract_certificate(
        pem: &x509_parser::pem::Pem,
    ) -> Result<x509_parser::certificate::X509Certificate, CertificateError> {
        let x509 = pem.parse_x509().map_err(|err| {
            // The x509 error is wrapped into a `nom::Err`
            // and cannot be extracted without pattern matching on that type
            // So one simply extract the error as a string,
            // to avoid a dependency on the `nom` crate.
            let x509_error_string = format!("{}", err);
            CertificateError::X509Error(x509_error_string)
        })?;
        Ok(x509)
    }

    fn wrap_x509_error(err: x509_parser::error::X509Error) -> CertificateError {
        let x509_error_string = format!("{}", err);
        CertificateError::X509Error(x509_error_string)
    }
}

pub struct KeyCertPair {
    certificate: Zeroizing<rcgen::Certificate>,
}

impl KeyCertPair {
    pub fn new_selfsigned_certificate(
        config: &NewCertificateConfig,
        id: &str,
    ) -> Result<KeyCertPair, CertificateError> {
        let today = OffsetDateTime::now_utc();
        let not_before = today - Duration::days(1); // Ensure the certificate is valid today
        KeyCertPair::new_selfsigned_certificate_at(config, id, not_before)
    }

    pub fn new_selfsigned_certificate_at(
        config: &NewCertificateConfig,
        id: &str,
        not_before: OffsetDateTime,
    ) -> Result<KeyCertPair, CertificateError> {
        let () = KeyCertPair::check_identifier(id, config.max_cn_size)?;
        let mut distinguished_name = rcgen::DistinguishedName::new();
        distinguished_name.push(rcgen::DnType::CommonName, id);
        distinguished_name.push(rcgen::DnType::OrganizationName, &config.organization_name);
        distinguished_name.push(
            rcgen::DnType::OrganizationalUnitName,
            &config.organizational_unit_name,
        );

        let not_after = not_before + Duration::days(config.validity_period_days.into());

        let mut params = CertificateParams::default();
        params.distinguished_name = distinguished_name;
        params.not_before = not_before;
        params.not_after = not_after;
        params.alg = &rcgen::PKCS_ECDSA_P256_SHA256; // ECDSA signing using the P-256 curves and SHA-256 hashing as per RFC 5758
        params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); // IsCa::SelfSignedOnly is rejected by C8Y

        Ok(KeyCertPair {
            certificate: Zeroizing::new(Certificate::from_params(params)?),
        })
    }

    pub fn certificate_pem_string(&self) -> Result<String, CertificateError> {
        Ok(self.certificate.serialize_pem()?)
    }

    pub fn private_key_pem_string(&self) -> Result<Zeroizing<String>, CertificateError> {
        Ok(Zeroizing::new(self.certificate.serialize_private_key_pem()))
    }

    fn check_identifier(id: &str, max_cn_size: usize) -> Result<(), CertificateError> {
        Ok(device_id::is_valid_device_id(id, max_cn_size)?)
    }
}

#[derive(thiserror::Error, Debug)]
pub enum CertificateError {
    #[error(transparent)]
    IoError(#[from] std::io::Error),

    #[error("Cryptography related error")]
    CryptographyError(#[from] RcgenError),

    #[error("PEM file format error")]
    PemError(#[from] x509_parser::error::PEMError),

    #[error("X509 file format error: {0}")]
    X509Error(String), // One cannot use x509_parser::error::X509Error unless one use `nom`.

    #[error("DeviceID Error")]
    InvalidDeviceID(#[from] DeviceIdError),
}

pub struct NewCertificateConfig {
    pub max_cn_size: usize,
    pub validity_period_days: u32,
    pub organization_name: String,
    pub organizational_unit_name: String,
}

impl Default for NewCertificateConfig {
    fn default() -> Self {
        NewCertificateConfig {
            max_cn_size: 64,
            validity_period_days: 365,
            organization_name: "Thin Edge".into(),
            organizational_unit_name: "Test Device".into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use time::macros::datetime;

    use super::*;

    fn pem_of_keypair(keypair: &KeyCertPair) -> PemCertificate {
        let pem_string = keypair
            .certificate_pem_string()
            .expect("Fail to read the certificate PEM");
        PemCertificate::from_pem_string(&pem_string).expect("Fail to decode the certificate PEM")
    }

    #[test]
    fn self_signed_cert_subject_is_the_device() {
        // Create a certificate with a given subject
        let config = NewCertificateConfig {