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
//! Obtain an X.509 attestation certificate for a key within the `YubiHSM2`
//!
//! <https://developers.yubico.com/YubiHSM2/Commands/Get_Object_Info.html>
//!
use super::{Command, Response};
use {Adapter, CommandType, ObjectId, Session, SessionError};

/// Obtain an X.509 attestation certificate for a key within the YubiHSM2.
/// This can be used to demonstrate that a given key was generated by
/// and stored within a YubiHSM2 in a non-exportable manner.
///
/// The `key_id` is the subject key for which an attestation certificate
/// is created, and the`attestation_key_id` will be used to sign the
/// attestation certificate.
///
/// If no attestation key is given, the device's default attestation key
/// will be used, and can be verified against Yubico's certificate.
pub fn attest_asymmetric<A: Adapter>(
    session: &mut Session<A>,
    key_id: ObjectId,
    attestation_key_id: Option<ObjectId>,
) -> Result<AttestationCertificate, SessionError> {
    session.send_command(AttestAsymmetricCommand {
        key_id,
        attestation_key_id: attestation_key_id.unwrap_or(0),
    })
}

/// Request parameters for `commands::attest_asymmetric`
#[derive(Serialize, Deserialize, Debug)]
pub(crate) struct AttestAsymmetricCommand {
    /// Key that attestation certificate will be generated for
    pub key_id: ObjectId,

    /// Key to use to sign attestation certificate
    pub attestation_key_id: ObjectId,
}

impl Command for AttestAsymmetricCommand {
    type ResponseType = AttestationCertificate;
}

/// DER encoded X.509 attestation certificate
#[derive(Serialize, Deserialize, Debug)]
pub struct AttestationCertificate(pub Vec<u8>);

impl Response for AttestationCertificate {
    const COMMAND_TYPE: CommandType = CommandType::AttestAsymmetric;
}

// TODO: use clippy's scoped lints once they work on stable
#[allow(
    unknown_lints,
    renamed_and_removed_lints,
    len_without_is_empty
)]
impl AttestationCertificate {
    /// Unwrap inner byte vector
    pub fn into_vec(self) -> Vec<u8> {
        self.into()
    }

    /// Get length of the certificate
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Get slice of the inner byte vector
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        self.as_ref()
    }
}

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

impl Into<Vec<u8>> for AttestationCertificate {
    fn into(self) -> Vec<u8> {
        self.0
    }
}