sshcerts 0.15.1

A library for parsing, verifying, and creating SSH Certificates
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
use crate::{PublicKey, TouchRequirement};

use ring::digest;

use yubikey::certificate::Certificate;
use yubikey::piv::{attest, sign_data as yk_sign_data, AlgorithmId, SlotId};
use yubikey::{MgmAlgorithmId, MgmKey, Serial, YubiKey};
use yubikey::{PinPolicy, TouchPolicy};

use super::{Error, Result};

use x509_cert::{
    der::{oid::ObjectIdentifier, Encode},
    name::Name,
    serial_number::SerialNumber,
    time::Validity,
};

use std::str::FromStr;
use yubikey::certificate::yubikey_signer;

#[derive(Debug)]
/// A struct that allows the generation of CSRs via the rcgen library. This is
/// only used when calling the `generate_csr` function.
pub struct CSRSigner {
    slot: SlotId,
    serial: u32,
    public_key: Vec<u8>,
    algorithm: AlgorithmId,
}

#[derive(Clone, Copy, Debug)]
/// Management key algorithm
pub enum ManagementKeyAlgorithm {
    /// 3DES
    ThreeDes,
    /// AES-128
    Aes128,
    /// AES-192
    Aes192,
    /// AES-256
    Aes256,
}

/// OID for secp256r1 / prime256v1 (NIST P-256)
pub const NISTP256_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
/// OID for secp384r1 (NIST P-384)
pub const SECP384_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");

fn touch_policy_requirement(touch_policy: TouchPolicy) -> TouchRequirement {
    match touch_policy {
        TouchPolicy::Always | TouchPolicy::Cached => TouchRequirement::Required,
        // YubiKey PIV defaults to no touch; Unknown is only for missing metadata.
        TouchPolicy::Never | TouchPolicy::Default => TouchRequirement::NotRequired,
    }
}

impl CSRSigner {
    /// Create a new certificate signer based on a Yubikey serial
    /// and slot
    pub fn new(serial: u32, slot: SlotId) -> Result<Self> {
        let mut yk = super::Yubikey::open(serial)?;
        let cert = yk.configured(&slot).map_err(|e| {
            Error::InternalYubiKeyError(format!(
                "failed to read certificate for CSR generation: {}",
                e
            ))
        })?;
        let pki = cert.subject_pki();
        let oid_alg = pki
            .algorithm
            .parameters_oid()
            .map_err(|_| Error::OIDError)?;

        let (public_key, algorithm) = match oid_alg {
            NISTP256_OID => (
                pki.subject_public_key.raw_bytes().to_vec(),
                AlgorithmId::EccP256,
            ),
            SECP384_OID => (
                pki.subject_public_key.raw_bytes().to_vec(),
                AlgorithmId::EccP384,
            ),
            _ => return Err(Error::UnsupportedAlgorithm),
        };

        Ok(Self {
            slot,
            serial,
            public_key,
            algorithm,
        })
    }
}

impl rcgen::RemoteKeyPair for CSRSigner {
    fn public_key(&self) -> &[u8] {
        &self.public_key
    }

    fn sign(&self, message: &[u8]) -> std::result::Result<Vec<u8>, rcgen::RcgenError> {
        let mut yk = if let Ok(yk) = super::Yubikey::open(self.serial) {
            yk
        } else {
            return Err(rcgen::RcgenError::RemoteKeyError);
        };

        yk.sign_data(message, self.algorithm, &self.slot)
            .map_err(|_| rcgen::RcgenError::RemoteKeyError)
    }

    fn algorithm(&self) -> &'static rcgen::SignatureAlgorithm {
        match self.algorithm {
            AlgorithmId::EccP256 => &rcgen::PKCS_ECDSA_P256_SHA256,
            AlgorithmId::EccP384 => &rcgen::PKCS_ECDSA_P384_SHA384,
            _ => panic!("Unimplemented"),
        }
    }
}

impl FromStr for ManagementKeyAlgorithm {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        match s {
            "3des" => Ok(ManagementKeyAlgorithm::ThreeDes),
            "aes128" => Ok(ManagementKeyAlgorithm::Aes128),
            "aes192" => Ok(ManagementKeyAlgorithm::Aes192),
            "aes256" => Ok(ManagementKeyAlgorithm::Aes256),
            _ => Err(Error::InvalidManagementKeyAlgorithm),
        }
    }
}

impl Into<MgmAlgorithmId> for ManagementKeyAlgorithm {
    fn into(self) -> MgmAlgorithmId {
        match self {
            ManagementKeyAlgorithm::ThreeDes => MgmAlgorithmId::ThreeDes,
            ManagementKeyAlgorithm::Aes128 => MgmAlgorithmId::Aes128,
            ManagementKeyAlgorithm::Aes192 => MgmAlgorithmId::Aes192,
            ManagementKeyAlgorithm::Aes256 => MgmAlgorithmId::Aes256,
        }
    }
}

impl From<MgmAlgorithmId> for ManagementKeyAlgorithm {
    fn from(alg: MgmAlgorithmId) -> Self {
        match alg {
            MgmAlgorithmId::ThreeDes => ManagementKeyAlgorithm::ThreeDes,
            MgmAlgorithmId::Aes128 => ManagementKeyAlgorithm::Aes128,
            MgmAlgorithmId::Aes192 => ManagementKeyAlgorithm::Aes192,
            MgmAlgorithmId::Aes256 => ManagementKeyAlgorithm::Aes256,
        }
    }
}

impl super::Yubikey {
    /// Create a new YubiKey. Assumes there is only one Yubikey connected
    pub fn new() -> Result<Self> {
        Ok(Self {
            yk: YubiKey::open()?,
        })
    }

    /// Open a Yubikey from a serial
    pub fn open(serial: u32) -> Result<Self> {
        match YubiKey::open_by_serial(serial.into()) {
            Ok(yk) => Ok(Self { yk }),
            Err(_) => Err(Error::NoSuchYubikey),
        }
    }

    /// Reconnet to the Yubikey (if possible, if it's disconnected)
    pub fn reconnect(&mut self) -> Result<()> {
        match self.yk.reconnect() {
            Ok(()) => Ok(()),
            Err(_) => match YubiKey::open_by_serial(self.yk.serial()) {
                Ok(yk) => {
                    self.yk = yk;
                    Ok(())
                }
                Err(_) => Err(Error::NoSuchYubikey),
            },
        }
    }

    /// Unlock the yubikey for signing or provisioning operations
    pub fn unlock(&mut self, pin: &[u8], mgm_key: &[u8]) -> Result<()> {
        self.yk.verify_pin(pin)?;

        let mgm = self.management_key_from_bytes(mgm_key)?;
        self.yk.authenticate(&mgm)?;

        Ok(())
    }

    /// Unlock the yubikey with an explicit management key algorithm.
    pub fn unlock_with_management_key_algorithm(
        &mut self,
        pin: &[u8],
        mgm_key: &[u8],
        alg: ManagementKeyAlgorithm,
    ) -> Result<()> {
        self.yk.verify_pin(pin)?;

        let mgm = MgmKey::from_bytes(mgm_key, Some(alg.into()))
            .map_err(|_| Error::InvalidManagementKey)?;
        self.yk.authenticate(&mgm)?;

        Ok(())
    }

    fn management_key_from_bytes(&self, mgm_key: &[u8]) -> Result<MgmKey> {
        let alg = MgmKey::get_default(&self.yk)?.algorithm_id();
        MgmKey::from_bytes(mgm_key, Some(alg)).map_err(|_| Error::InvalidManagementKey)
    }

    /// Fetch the serial number of the Yubikey
    pub fn serial(&mut self) -> Result<Serial> {
        let serial = self.yk.serial();
        Ok(serial)
    }

    /// Check to see that a provided Yubikey and slot is configured for signing
    pub fn configured(&mut self, slot: &SlotId) -> Result<Certificate> {
        let cert = Certificate::read(&mut self.yk, *slot)?;
        Ok(cert)
    }

    /// Check to see that a provided Yubikey and slot is configured for signing
    pub fn fetch_subject(&mut self, slot: &SlotId) -> Result<String> {
        let cert = Certificate::read(&mut self.yk, *slot)?;
        Ok(cert.subject().to_string())
    }

    /// Fetch the certificate from a given Yubikey slot.
    pub fn fetch_certificate(&mut self, slot: &SlotId) -> Result<Vec<u8>> {
        let cert = Certificate::read(&mut self.yk, *slot)?;
        Ok(cert.cert.to_der().map_err(|e| {
            Error::InternalYubiKeyError(format!("Failed to encode certificate: {}", e))
        })?)
    }

    /// Write the certificate from a given Yubikey slot.
    pub fn write_certificate(&mut self, slot: &SlotId, data: &[u8]) -> Result<()> {
        Ok(Certificate::from_bytes(data.to_vec())?.write(
            &mut self.yk,
            *slot,
            yubikey::certificate::CertInfo::Uncompressed,
        )?)
    }

    /// Generate attestation for a slot
    pub fn fetch_attestation(&mut self, slot: &SlotId) -> Result<Vec<u8>> {
        Ok(attest(&mut self.yk, *slot)?.to_vec())
    }

    /// Fetch the touch policy configured for a YubiKey PIV slot.
    pub fn fetch_touch_policy(&mut self, slot: &SlotId) -> Result<Option<TouchPolicy>> {
        let metadata = match yubikey::piv::metadata(&mut self.yk, *slot) {
            Ok(metadata) => metadata,
            Err(yubikey::Error::NotFound) => return Err(Error::Unprovisioned),
            Err(e) => return Err(e.into()),
        };

        Ok(metadata.policy.map(|(_, touch_policy)| touch_policy))
    }

    /// Returns the touch requirement for a YubiKey PIV slot.
    ///
    /// Returns `TouchRequirement::Unknown` only when the device does not expose
    /// policy metadata. A slot's default touch policy is `Never`, so it resolves
    /// to `NotRequired`.
    pub fn touch_requirement(&mut self, slot: &SlotId) -> Result<TouchRequirement> {
        Ok(self
            .fetch_touch_policy(slot)?
            .map(touch_policy_requirement)
            .unwrap_or(TouchRequirement::Unknown))
    }

    /// Generate CSR for slot
    pub fn generate_csr(&mut self, slot: &SlotId, common_name: &str) -> Result<Vec<u8>> {
        let mut params = rcgen::CertificateParams::new(vec![]);
        let cert = self.configured(&slot).map_err(|e| {
            Error::InternalYubiKeyError(format!(
                "failed to read certificate for CSR generation: {}",
                e
            ))
        })?;
        let pki = cert.subject_pki();
        let oid_alg = pki
            .algorithm
            .parameters_oid()
            .map_err(|_| Error::Unsupported)?;

        params.alg = match oid_alg {
            NISTP256_OID => &rcgen::PKCS_ECDSA_P256_SHA256,
            SECP384_OID => &rcgen::PKCS_ECDSA_P384_SHA384,
            _ => return Err(Error::Unsupported),
        };
        params
            .distinguished_name
            .push(rcgen::DnType::CommonName, common_name.to_string());

        let csr_signer = CSRSigner::new(self.yk.serial().into(), *slot)?;
        params.key_pair = Some(
            rcgen::KeyPair::from_remote(Box::new(csr_signer))
                .map_err(|e| Error::InternalYubiKeyError(format!("{}", e)))?,
        );

        let csr = rcgen::Certificate::from_params(params)
            .map_err(|e| Error::InternalYubiKeyError(format!("{}", e)))?;
        let csr = csr
            .serialize_request_der()
            .map_err(|e| Error::InternalYubiKeyError(format!("{}", e)))?;

        Ok(csr)
    }

    /// Provisions the YubiKey with a new certificate generated on the device.
    /// Only keys that are generated this way can use the attestation functionality.
    fn provision<KT: yubikey_signer::KeyType>(
        &mut self,
        slot: &SlotId,
        common_name: &str,
        touch_policy: TouchPolicy,
        pin_policy: PinPolicy,
    ) -> Result<PublicKey> {
        let key_info =
            yubikey::piv::generate(&mut self.yk, *slot, KT::ALGORITHM, pin_policy, touch_policy)?;
        // Generate a self-signed certificate for the new key.
        Certificate::generate_self_signed::<_, KT>(
            &mut self.yk,
            *slot,
            SerialNumber::new(&[0; 20]).unwrap(),
            Validity::from_now(std::time::Duration::new(3600 * 24 * 3650, 0)).unwrap(),
            Name::from_str(&format!("CN={}", common_name)).unwrap(),
            key_info,
            |_builder| Ok(()),
        )?;

        self.ssh_cert_fetch_pubkey(slot)
    }

    /// Provisions the YubiKey with a new certificate generated on the device.
    /// Only keys that are generated this way can use the attestation functionality.
    /// This is a nongeneric version to generate a p384 key
    pub fn provision_p384(
        &mut self,
        slot: &SlotId,
        common_name: &str,
        touch_policy: TouchPolicy,
        pin_policy: PinPolicy,
    ) -> Result<PublicKey> {
        self.provision::<super::keytype::NistP384>(slot, common_name, touch_policy, pin_policy)
    }

    /// Provisions the YubiKey with a new certificate generated on the device.
    /// Only keys that are generated this way can use the attestation functionality.
    /// This is a nongeneric version to generate a p256 key
    pub fn provision_p256(
        &mut self,
        slot: &SlotId,
        common_name: &str,
        touch_policy: TouchPolicy,
        pin_policy: PinPolicy,
    ) -> Result<PublicKey> {
        self.provision::<super::keytype::NistP256>(slot, common_name, touch_policy, pin_policy)
    }

    /// Take data, an algorithm, and a slot and attempt to sign the data field
    ///
    /// If the requested algorithm doesn't match the key in the slot (or the slot
    /// is empty) this will error.
    pub fn sign_data(&mut self, data: &[u8], alg: AlgorithmId, slot: &SlotId) -> Result<Vec<u8>> {
        let cert = self.configured(&slot).map_err(|e| {
            Error::InternalYubiKeyError(format!("failed to read slot for signing: {}", e))
        })?;
        let pki = cert.subject_pki();
        let oid_alg = pki
            .algorithm
            .parameters_oid()
            .map_err(|_| Error::Unprovisioned)?;

        let (slot_alg, hash_alg) = match oid_alg {
            NISTP256_OID => (AlgorithmId::EccP256, &digest::SHA256),
            SECP384_OID => (AlgorithmId::EccP384, &digest::SHA384),
            _ => return Err(Error::Unprovisioned),
        };

        if slot_alg != alg {
            return Err(Error::WrongKeyType);
        }
        let signature = yk_sign_data(
            &mut self.yk,
            digest::digest(hash_alg, data).as_ref(),
            alg,
            *slot,
        )?;
        Ok(signature.to_vec())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn touch_policy_requirement_maps_known_policies() {
        assert_eq!(
            touch_policy_requirement(TouchPolicy::Always),
            TouchRequirement::Required
        );
        assert_eq!(
            touch_policy_requirement(TouchPolicy::Cached),
            TouchRequirement::Required
        );
        assert_eq!(
            touch_policy_requirement(TouchPolicy::Never),
            TouchRequirement::NotRequired
        );
        assert_eq!(
            touch_policy_requirement(TouchPolicy::Default),
            TouchRequirement::NotRequired
        );
    }
}