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 //! This module contains functions related to the attestation of the
16 //! service VM via the RKP (Remote Key Provisioning) server.
17 
18 use crate::keyblob::EncryptedKeyBlob;
19 use crate::pub_key::{build_maced_public_key, validate_public_key};
20 use alloc::string::String;
21 use alloc::vec;
22 use alloc::vec::Vec;
23 use bssl_avf::EcKey;
24 use ciborium::{
25     cbor,
26     value::{CanonicalValue, Value},
27 };
28 use core::result;
29 use coset::{AsCborValue, CoseSign1, CoseSign1Builder, HeaderBuilder};
30 use diced_open_dice::{
31     derive_cdi_leaf_priv, kdf, sign, DiceArtifacts, PrivateKey, VM_KEY_ALGORITHM,
32 };
33 use log::{debug, error};
34 use service_vm_comm::{EcdsaP256KeyPair, GenerateCertificateRequestParams, RequestProcessingError};
35 use zeroize::Zeroizing;
36 
37 type Result<T> = result::Result<T, RequestProcessingError>;
38 
39 /// The salt is generated randomly with:
40 /// hexdump -vn32 -e'16/1 "0x%02X, " 1 "\n"' /dev/urandom
41 const HMAC_KEY_SALT: [u8; 32] = [
42     0x82, 0x80, 0xFA, 0xD3, 0xA8, 0x0A, 0x9A, 0x4B, 0xF7, 0xA5, 0x7D, 0x7B, 0xE9, 0xC3, 0xAB, 0x13,
43     0x89, 0xDC, 0x7B, 0x46, 0xEE, 0x71, 0x22, 0xB4, 0x5F, 0x4C, 0x3F, 0xE2, 0x40, 0x04, 0x3B, 0x6C,
44 ];
45 const HMAC_KEY_INFO: &[u8] = b"rialto hmac wkey";
46 const HMAC_KEY_LENGTH: usize = 32;
47 
generate_ecdsa_p256_key_pair( dice_artifacts: &dyn DiceArtifacts, ) -> Result<EcdsaP256KeyPair>48 pub(super) fn generate_ecdsa_p256_key_pair(
49     dice_artifacts: &dyn DiceArtifacts,
50 ) -> Result<EcdsaP256KeyPair> {
51     let hmac_key = derive_hmac_key(dice_artifacts)?;
52     let mut ec_key = EcKey::new_p256()?;
53     ec_key.generate_key()?;
54 
55     let maced_public_key = build_maced_public_key(ec_key.cose_public_key()?, hmac_key.as_ref())?;
56     let key_blob =
57         EncryptedKeyBlob::new(ec_key.ec_private_key()?.as_slice(), dice_artifacts.cdi_seal())?;
58 
59     let key_pair =
60         EcdsaP256KeyPair { maced_public_key, key_blob: cbor_util::serialize(&key_blob)? };
61     Ok(key_pair)
62 }
63 
64 const CSR_PAYLOAD_SCHEMA_V3: u8 = 3;
65 const AUTH_REQ_SCHEMA_V1: u8 = 1;
66 const CERTIFICATE_TYPE: &str = "rkp-vm";
67 
68 /// Builds the CSR described in:
69 ///
70 /// hardware/interfaces/security/rkp/aidl/android/hardware/security/keymint/
71 /// generateCertificateRequestV2.cddl
generate_certificate_request( params: GenerateCertificateRequestParams, dice_artifacts: &dyn DiceArtifacts, ) -> Result<Vec<u8>>72 pub(super) fn generate_certificate_request(
73     params: GenerateCertificateRequestParams,
74     dice_artifacts: &dyn DiceArtifacts,
75 ) -> Result<Vec<u8>> {
76     let hmac_key = derive_hmac_key(dice_artifacts)?;
77     let mut public_keys: Vec<Value> = Vec::new();
78     for key_to_sign in params.keys_to_sign {
79         let public_key = validate_public_key(&key_to_sign, hmac_key.as_ref())?;
80         public_keys.push(public_key.to_cbor_value()?);
81     }
82     debug!("Successfully validated all '{}' public keys.", public_keys.len());
83 
84     // Builds `CsrPayload`.
85     let csr_payload = cbor!([
86         Value::Integer(CSR_PAYLOAD_SCHEMA_V3.into()),
87         Value::Text(String::from(CERTIFICATE_TYPE)),
88         device_info(),
89         Value::Array(public_keys),
90     ])?;
91     let csr_payload = cbor_util::serialize(&csr_payload)?;
92 
93     // Builds `SignedData`.
94     let signed_data_payload =
95         cbor!([Value::Bytes(params.challenge.to_vec()), Value::Bytes(csr_payload)])?;
96     let signed_data = build_signed_data(&signed_data_payload, dice_artifacts)?.to_cbor_value()?;
97     debug!("Successfully signed the CSR payload.");
98 
99     // Builds `AuthenticatedRequest<CsrPayload>`.
100     // Currently `UdsCerts` is left empty because it is only needed for Samsung devices.
101     // Check http://b/301574013#comment3 for more information.
102     let uds_certs = Value::Map(Vec::new());
103     let dice_cert_chain = dice_artifacts.bcc().ok_or(RequestProcessingError::MissingDiceChain)?;
104     let dice_cert_chain: Value = cbor_util::deserialize(dice_cert_chain)?;
105     let auth_req = cbor!([
106         Value::Integer(AUTH_REQ_SCHEMA_V1.into()),
107         uds_certs,
108         dice_cert_chain,
109         signed_data,
110     ])?;
111     debug!("Successfully built the CBOR authenticated request.");
112     Ok(cbor_util::serialize(&auth_req)?)
113 }
114 
115 /// Generates the device info required by the RKP server as a temporary placeholder.
116 /// More details in b/301592917.
117 ///
118 /// The keys of the map should be in the length-first core deterministic encoding order
119 /// as per RFC8949.
device_info() -> CanonicalValue120 fn device_info() -> CanonicalValue {
121     cbor!({
122         "brand" => "aosp-avf",
123         "fused" => 1,
124         "model" => "avf",
125         "device" => "avf",
126         "product" => "avf",
127         "vb_state" => "avf",
128         "manufacturer" => "aosp-avf",
129         "vbmeta_digest" => Value::Bytes(vec![1u8; 1]),
130         "security_level" => "avf",
131         "boot_patch_level" => 20240202,
132         "bootloader_state" => "avf",
133         "system_patch_level" => 202402,
134         "vendor_patch_level" => 20240202,
135     })
136     .unwrap()
137     .into()
138 }
139 
derive_hmac_key(dice_artifacts: &dyn DiceArtifacts) -> Result<Zeroizing<[u8; HMAC_KEY_LENGTH]>>140 fn derive_hmac_key(dice_artifacts: &dyn DiceArtifacts) -> Result<Zeroizing<[u8; HMAC_KEY_LENGTH]>> {
141     let mut key = Zeroizing::new([0u8; HMAC_KEY_LENGTH]);
142     kdf(dice_artifacts.cdi_seal(), &HMAC_KEY_SALT, HMAC_KEY_INFO, key.as_mut()).map_err(|e| {
143         error!("Failed to compute the HMAC key: {e}");
144         RequestProcessingError::InternalError
145     })?;
146     Ok(key)
147 }
148 
149 /// Builds the `SignedData` for the given payload.
build_signed_data(payload: &Value, dice_artifacts: &dyn DiceArtifacts) -> Result<CoseSign1>150 fn build_signed_data(payload: &Value, dice_artifacts: &dyn DiceArtifacts) -> Result<CoseSign1> {
151     let cdi_leaf_priv = derive_cdi_leaf_priv(dice_artifacts).map_err(|e| {
152         error!("Failed to derive the CDI_Leaf_Priv: {e}");
153         RequestProcessingError::InternalError
154     })?;
155     let protected = HeaderBuilder::new().algorithm(VM_KEY_ALGORITHM.into()).build();
156     let signed_data = CoseSign1Builder::new()
157         .protected(protected)
158         .payload(cbor_util::serialize(payload)?)
159         .try_create_signature(&[], |message| sign_message(message, &cdi_leaf_priv))?
160         .build();
161     Ok(signed_data)
162 }
163 
sign_message(message: &[u8], private_key: &PrivateKey) -> Result<Vec<u8>>164 fn sign_message(message: &[u8], private_key: &PrivateKey) -> Result<Vec<u8>> {
165     Ok(sign(message, private_key.as_array())
166         .map_err(|e| {
167             error!("Failed to sign the CSR: {e}");
168             RequestProcessingError::InternalError
169         })?
170         .to_vec())
171 }
172 
173 #[cfg(test)]
174 mod tests {
175     use super::*;
176 
177     /// The keys of device info map should be in the length-first core deterministic encoding
178     /// order as per RFC8949.
179     /// The CBOR ordering rules are:
180     /// 1. If two keys have different lengths, the shorter one sorts earlier;
181     /// 2. If two keys have the same length, the one with the lower value in (bytewise) lexical
182     ///    order sorts earlier.
183     #[test]
device_info_is_in_length_first_deterministic_order()184     fn device_info_is_in_length_first_deterministic_order() {
185         let device_info = cbor!(device_info()).unwrap();
186         let device_info_map = device_info.as_map().unwrap();
187         let device_info_keys: Vec<&str> =
188             device_info_map.iter().map(|k| k.0.as_text().unwrap()).collect();
189         let mut sorted_keys = device_info_keys.clone();
190         sorted_keys.sort_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)));
191         assert_eq!(device_info_keys, sorted_keys);
192     }
193 }
194