1 // Copyright 2023, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! Generate the attestation key and CSR for client VM in the remote
16 //! attestation.
17 
18 use anyhow::{anyhow, Context, Result};
19 use coset::{
20     iana, CborSerializable, CoseKey, CoseKeyBuilder, CoseSign, CoseSignBuilder, CoseSignature,
21     CoseSignatureBuilder, HeaderBuilder,
22 };
23 use diced_open_dice::{derive_cdi_leaf_priv, sign, DiceArtifacts, PrivateKey, VM_KEY_ALGORITHM};
24 use openssl::{
25     bn::{BigNum, BigNumContext},
26     ec::{EcGroup, EcKey, EcKeyRef},
27     ecdsa::EcdsaSig,
28     nid::Nid,
29     pkey::Private,
30     sha::sha256,
31 };
32 use service_vm_comm::{Csr, CsrPayload};
33 use zeroize::Zeroizing;
34 
35 /// Key parameters for the attestation key.
36 ///
37 /// See libs/libservice_vm_comm/client_vm_csr.cddl for more information about the attestation key.
38 const ATTESTATION_KEY_NID: Nid = Nid::X9_62_PRIME256V1; // NIST P-256 curve
39 const ATTESTATION_KEY_ALGO: iana::Algorithm = iana::Algorithm::ES256;
40 const ATTESTATION_KEY_CURVE: iana::EllipticCurve = iana::EllipticCurve::P_256;
41 const ATTESTATION_KEY_AFFINE_COORDINATE_SIZE: i32 = 32;
42 
43 /// Represents the output of generating the attestation key and CSR for the client VM.
44 pub struct ClientVmAttestationData {
45     /// DER-encoded ECPrivateKey to be attested.
46     pub private_key: Zeroizing<Vec<u8>>,
47 
48     /// CSR containing client VM information and the public key corresponding to the
49     /// private key to be attested.
50     pub csr: Csr,
51 }
52 
53 /// Generates the attestation key and CSR including the public key to be attested for the
54 /// client VM in remote attestation.
generate_attestation_key_and_csr( challenge: &[u8], dice_artifacts: &dyn DiceArtifacts, ) -> Result<ClientVmAttestationData>55 pub fn generate_attestation_key_and_csr(
56     challenge: &[u8],
57     dice_artifacts: &dyn DiceArtifacts,
58 ) -> Result<ClientVmAttestationData> {
59     let group = EcGroup::from_curve_name(ATTESTATION_KEY_NID)?;
60     let attestation_key = EcKey::generate(&group)?;
61 
62     let csr = build_csr(challenge, attestation_key.as_ref(), dice_artifacts)?;
63     let private_key = attestation_key.private_key_to_der()?;
64     Ok(ClientVmAttestationData { private_key: Zeroizing::new(private_key), csr })
65 }
66 
build_csr( challenge: &[u8], attestation_key: &EcKeyRef<Private>, dice_artifacts: &dyn DiceArtifacts, ) -> Result<Csr>67 fn build_csr(
68     challenge: &[u8],
69     attestation_key: &EcKeyRef<Private>,
70     dice_artifacts: &dyn DiceArtifacts,
71 ) -> Result<Csr> {
72     // Builds CSR Payload to be signed.
73     let public_key =
74         to_cose_public_key(attestation_key)?.to_vec().context("Failed to serialize public key")?;
75     let csr_payload = CsrPayload { public_key, challenge: challenge.to_vec() };
76     let csr_payload = csr_payload.into_cbor_vec()?;
77 
78     // Builds signed CSR Payload.
79     let cdi_leaf_priv = derive_cdi_leaf_priv(dice_artifacts)?;
80     let signed_csr_payload = build_signed_data(csr_payload, &cdi_leaf_priv, attestation_key)?
81         .to_vec()
82         .context("Failed to serialize signed CSR payload")?;
83 
84     // Builds CSR.
85     let dice_cert_chain = dice_artifacts.bcc().ok_or(anyhow!("bcc is none"))?.to_vec();
86     Ok(Csr { dice_cert_chain, signed_csr_payload })
87 }
88 
build_signed_data( payload: Vec<u8>, cdi_leaf_priv: &PrivateKey, attestation_key: &EcKeyRef<Private>, ) -> Result<CoseSign>89 fn build_signed_data(
90     payload: Vec<u8>,
91     cdi_leaf_priv: &PrivateKey,
92     attestation_key: &EcKeyRef<Private>,
93 ) -> Result<CoseSign> {
94     let cdi_leaf_sig_headers = build_signature_headers(VM_KEY_ALGORITHM.into());
95     let attestation_key_sig_headers = build_signature_headers(ATTESTATION_KEY_ALGO);
96     let aad = &[];
97     let signed_data = CoseSignBuilder::new()
98         .payload(payload)
99         .try_add_created_signature(cdi_leaf_sig_headers, aad, |message| {
100             sign(message, cdi_leaf_priv.as_array()).map(|v| v.to_vec())
101         })?
102         .try_add_created_signature(attestation_key_sig_headers, aad, |message| {
103             ecdsa_sign_cose(message, attestation_key)
104         })?
105         .build();
106     Ok(signed_data)
107 }
108 
109 /// Builds a signature with headers filled with the provided algorithm.
110 /// The signature data will be filled later when building the signed data.
build_signature_headers(alg: iana::Algorithm) -> CoseSignature111 fn build_signature_headers(alg: iana::Algorithm) -> CoseSignature {
112     let protected = HeaderBuilder::new().algorithm(alg).build();
113     CoseSignatureBuilder::new().protected(protected).build()
114 }
115 
ecdsa_sign_cose(message: &[u8], key: &EcKeyRef<Private>) -> Result<Vec<u8>>116 fn ecdsa_sign_cose(message: &[u8], key: &EcKeyRef<Private>) -> Result<Vec<u8>> {
117     let digest = sha256(message);
118     // Passes the digest to `ECDSA_do_sign` as recommended in the spec:
119     // https://commondatastorage.googleapis.com/chromium-boringssl-docs/ecdsa.h.html#ECDSA_do_sign
120     let sig = EcdsaSig::sign::<Private>(&digest, key)?;
121     ecdsa_sig_to_cose(&sig)
122 }
123 
ecdsa_sig_to_cose(signature: &EcdsaSig) -> Result<Vec<u8>>124 fn ecdsa_sig_to_cose(signature: &EcdsaSig) -> Result<Vec<u8>> {
125     let mut result = signature.r().to_vec_padded(ATTESTATION_KEY_AFFINE_COORDINATE_SIZE)?;
126     result.extend_from_slice(&signature.s().to_vec_padded(ATTESTATION_KEY_AFFINE_COORDINATE_SIZE)?);
127     Ok(result)
128 }
129 
get_affine_coordinates(key: &EcKeyRef<Private>) -> Result<(Vec<u8>, Vec<u8>)>130 fn get_affine_coordinates(key: &EcKeyRef<Private>) -> Result<(Vec<u8>, Vec<u8>)> {
131     let mut ctx = BigNumContext::new()?;
132     let mut x = BigNum::new()?;
133     let mut y = BigNum::new()?;
134     key.public_key().affine_coordinates_gfp(key.group(), &mut x, &mut y, &mut ctx)?;
135     let x = x.to_vec_padded(ATTESTATION_KEY_AFFINE_COORDINATE_SIZE)?;
136     let y = y.to_vec_padded(ATTESTATION_KEY_AFFINE_COORDINATE_SIZE)?;
137     Ok((x, y))
138 }
139 
to_cose_public_key(key: &EcKeyRef<Private>) -> Result<CoseKey>140 fn to_cose_public_key(key: &EcKeyRef<Private>) -> Result<CoseKey> {
141     let (x, y) = get_affine_coordinates(key)?;
142     Ok(CoseKeyBuilder::new_ec2_pub_key(ATTESTATION_KEY_CURVE, x, y)
143         .algorithm(ATTESTATION_KEY_ALGO)
144         .build())
145 }
146 
147 #[cfg(test)]
148 mod tests {
149     use super::*;
150     use anyhow::bail;
151     use ciborium::Value;
152     use coset::{iana::EnumI64, Label};
153     use hwtrust::{dice, session::Session};
154     use openssl::pkey::Public;
155 
156     /// The following data was generated randomly with urandom.
157     const CHALLENGE: [u8; 16] = [
158         0xb3, 0x66, 0xfa, 0x72, 0x92, 0x32, 0x2c, 0xd4, 0x99, 0xcb, 0x00, 0x1f, 0x0e, 0xe0, 0xc7,
159         0x41,
160     ];
161 
162     #[test]
csr_and_private_key_have_correct_format() -> Result<()>163     fn csr_and_private_key_have_correct_format() -> Result<()> {
164         let dice_artifacts = diced_sample_inputs::make_sample_bcc_and_cdis()?;
165 
166         let ClientVmAttestationData { private_key, csr } =
167             generate_attestation_key_and_csr(&CHALLENGE, &dice_artifacts)?;
168         let ec_private_key = EcKey::private_key_from_der(&private_key)?;
169         let cose_sign = CoseSign::from_slice(&csr.signed_csr_payload).unwrap();
170         let aad = &[];
171 
172         // Checks CSR payload.
173         let csr_payload =
174             cose_sign.payload.as_ref().and_then(|v| CsrPayload::from_cbor_slice(v).ok()).unwrap();
175         let public_key = to_cose_public_key(&ec_private_key)?.to_vec().unwrap();
176         let expected_csr_payload = CsrPayload { challenge: CHALLENGE.to_vec(), public_key };
177         assert_eq!(expected_csr_payload, csr_payload);
178 
179         // Checks the first signature is signed with CDI_Leaf_Priv.
180         let session = Session::default();
181         let chain = dice::Chain::from_cbor(&session, &csr.dice_cert_chain)?;
182         let public_key = chain.leaf().subject_public_key();
183         cose_sign
184             .verify_signature(0, aad, |signature, message| public_key.verify(signature, message))
185             .context("Verifying CDI_Leaf_Priv signature")?;
186 
187         // Checks the second signature is signed with attestation key.
188         let attestation_public_key = CoseKey::from_slice(&csr_payload.public_key).unwrap();
189         let ec_public_key = to_ec_public_key(&attestation_public_key)?;
190         cose_sign
191             .verify_signature(1, aad, |signature, message| {
192                 ecdsa_verify_cose(signature, message, &ec_public_key)
193             })
194             .context("Verifying attestation key signature")?;
195 
196         // Verifies that private key and the public key form a valid key pair.
197         let message = b"test message";
198         let signature = ecdsa_sign_cose(message, &ec_private_key)?;
199         ecdsa_verify_cose(&signature, message, &ec_public_key)
200             .context("Verifying signature with attested key")?;
201 
202         Ok(())
203     }
204 
ecdsa_verify_cose( signature: &[u8], message: &[u8], ec_public_key: &EcKeyRef<Public>, ) -> Result<()>205     fn ecdsa_verify_cose(
206         signature: &[u8],
207         message: &[u8],
208         ec_public_key: &EcKeyRef<Public>,
209     ) -> Result<()> {
210         let coord_bytes = signature.len() / 2;
211         assert_eq!(signature.len(), coord_bytes * 2);
212 
213         let r = BigNum::from_slice(&signature[..coord_bytes])?;
214         let s = BigNum::from_slice(&signature[coord_bytes..])?;
215         let sig = EcdsaSig::from_private_components(r, s)?;
216         let digest = sha256(message);
217         if sig.verify(&digest, ec_public_key)? {
218             Ok(())
219         } else {
220             bail!("Signature does not match")
221         }
222     }
223 
to_ec_public_key(cose_key: &CoseKey) -> Result<EcKey<Public>>224     fn to_ec_public_key(cose_key: &CoseKey) -> Result<EcKey<Public>> {
225         check_ec_key_params(cose_key)?;
226         let group = EcGroup::from_curve_name(ATTESTATION_KEY_NID)?;
227         let x = get_label_value_as_bignum(cose_key, Label::Int(iana::Ec2KeyParameter::X.to_i64()))?;
228         let y = get_label_value_as_bignum(cose_key, Label::Int(iana::Ec2KeyParameter::Y.to_i64()))?;
229         let key = EcKey::from_public_key_affine_coordinates(&group, &x, &y)?;
230         key.check_key()?;
231         Ok(key)
232     }
233 
check_ec_key_params(cose_key: &CoseKey) -> Result<()>234     fn check_ec_key_params(cose_key: &CoseKey) -> Result<()> {
235         assert_eq!(coset::KeyType::Assigned(iana::KeyType::EC2), cose_key.kty);
236         assert_eq!(Some(coset::Algorithm::Assigned(ATTESTATION_KEY_ALGO)), cose_key.alg);
237         let crv = get_label_value(cose_key, Label::Int(iana::Ec2KeyParameter::Crv.to_i64()))?;
238         assert_eq!(&Value::from(ATTESTATION_KEY_CURVE.to_i64()), crv);
239         Ok(())
240     }
241 
get_label_value_as_bignum(key: &CoseKey, label: Label) -> Result<BigNum>242     fn get_label_value_as_bignum(key: &CoseKey, label: Label) -> Result<BigNum> {
243         get_label_value(key, label)?
244             .as_bytes()
245             .map(|v| BigNum::from_slice(&v[..]).unwrap())
246             .ok_or_else(|| anyhow!("Value not a bstr."))
247     }
248 
get_label_value(key: &CoseKey, label: Label) -> Result<&Value>249     fn get_label_value(key: &CoseKey, label: Label) -> Result<&Value> {
250         Ok(&key
251             .params
252             .iter()
253             .find(|(k, _)| k == &label)
254             .ok_or_else(|| anyhow!("Label {:?} not found", label))?
255             .1)
256     }
257 }
258