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, DICE_COSE_KEY_ALG_VALUE,
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 // TODO(b/300624493): Add a new certificate type for AVF CSR.
67 const CERTIFICATE_TYPE: &str = "keymint";
68 
69 /// Builds the CSR described in:
70 ///
71 /// hardware/interfaces/security/rkp/aidl/android/hardware/security/keymint/
72 /// generateCertificateRequestV2.cddl
generate_certificate_request( params: GenerateCertificateRequestParams, dice_artifacts: &dyn DiceArtifacts, ) -> Result<Vec<u8>>73 pub(super) fn generate_certificate_request(
74     params: GenerateCertificateRequestParams,
75     dice_artifacts: &dyn DiceArtifacts,
76 ) -> Result<Vec<u8>> {
77     let hmac_key = derive_hmac_key(dice_artifacts)?;
78     let mut public_keys: Vec<Value> = Vec::new();
79     for key_to_sign in params.keys_to_sign {
80         let public_key = validate_public_key(&key_to_sign, hmac_key.as_ref())?;
81         public_keys.push(public_key.to_cbor_value()?);
82     }
83     debug!("Successfully validated all '{}' public keys.", public_keys.len());
84 
85     // Builds `CsrPayload`.
86     let csr_payload = cbor!([
87         Value::Integer(CSR_PAYLOAD_SCHEMA_V3.into()),
88         Value::Text(String::from(CERTIFICATE_TYPE)),
89         device_info(),
90         Value::Array(public_keys),
91     ])?;
92     let csr_payload = cbor_util::serialize(&csr_payload)?;
93 
94     // Builds `SignedData`.
95     let signed_data_payload =
96         cbor!([Value::Bytes(params.challenge.to_vec()), Value::Bytes(csr_payload)])?;
97     let signed_data = build_signed_data(&signed_data_payload, dice_artifacts)?.to_cbor_value()?;
98     debug!("Successfully signed the CSR payload.");
99 
100     // Builds `AuthenticatedRequest<CsrPayload>`.
101     // Currently `UdsCerts` is left empty because it is only needed for Samsung devices.
102     // Check http://b/301574013#comment3 for more information.
103     let uds_certs = Value::Map(Vec::new());
104     let dice_cert_chain = dice_artifacts.bcc().ok_or(RequestProcessingError::MissingDiceChain)?;
105     let dice_cert_chain: Value = cbor_util::deserialize(dice_cert_chain)?;
106     let auth_req = cbor!([
107         Value::Integer(AUTH_REQ_SCHEMA_V1.into()),
108         uds_certs,
109         dice_cert_chain,
110         signed_data,
111     ])?;
112     debug!("Successfully built the CBOR authenticated request.");
113     Ok(cbor_util::serialize(&auth_req)?)
114 }
115 
116 /// Generates the device info required by the RKP server as a temporary placeholder.
117 /// More details in b/301592917.
118 ///
119 /// The keys of the map should be in the length-first core deterministic encoding order
120 /// as per RFC8949.
device_info() -> CanonicalValue121 fn device_info() -> CanonicalValue {
122     cbor!({
123         "brand" => "aosp-avf",
124         "fused" => 1,
125         "model" => "avf",
126         "device" => "avf",
127         "product" => "avf",
128         "vb_state" => "avf",
129         "manufacturer" => "aosp-avf",
130         "vbmeta_digest" => Value::Bytes(vec![1u8; 1]),
131         "security_level" => "avf",
132         "boot_patch_level" => 20240202,
133         "bootloader_state" => "avf",
134         "system_patch_level" => 202402,
135         "vendor_patch_level" => 20240202,
136     })
137     .unwrap()
138     .into()
139 }
140 
derive_hmac_key(dice_artifacts: &dyn DiceArtifacts) -> Result<Zeroizing<[u8; HMAC_KEY_LENGTH]>>141 fn derive_hmac_key(dice_artifacts: &dyn DiceArtifacts) -> Result<Zeroizing<[u8; HMAC_KEY_LENGTH]>> {
142     let mut key = Zeroizing::new([0u8; HMAC_KEY_LENGTH]);
143     kdf(dice_artifacts.cdi_seal(), &HMAC_KEY_SALT, HMAC_KEY_INFO, key.as_mut()).map_err(|e| {
144         error!("Failed to compute the HMAC key: {e}");
145         RequestProcessingError::InternalError
146     })?;
147     Ok(key)
148 }
149 
150 /// Builds the `SignedData` for the given payload.
build_signed_data(payload: &Value, dice_artifacts: &dyn DiceArtifacts) -> Result<CoseSign1>151 fn build_signed_data(payload: &Value, dice_artifacts: &dyn DiceArtifacts) -> Result<CoseSign1> {
152     let cdi_leaf_priv = derive_cdi_leaf_priv(dice_artifacts).map_err(|e| {
153         error!("Failed to derive the CDI_Leaf_Priv: {e}");
154         RequestProcessingError::InternalError
155     })?;
156     let dice_key_alg = cbor_util::dice_cose_key_alg(DICE_COSE_KEY_ALG_VALUE)?;
157     let protected = HeaderBuilder::new().algorithm(dice_key_alg).build();
158     let signed_data = CoseSign1Builder::new()
159         .protected(protected)
160         .payload(cbor_util::serialize(payload)?)
161         .try_create_signature(&[], |message| sign_message(message, &cdi_leaf_priv))?
162         .build();
163     Ok(signed_data)
164 }
165 
sign_message(message: &[u8], private_key: &PrivateKey) -> Result<Vec<u8>>166 fn sign_message(message: &[u8], private_key: &PrivateKey) -> Result<Vec<u8>> {
167     Ok(sign(message, private_key.as_array())
168         .map_err(|e| {
169             error!("Failed to sign the CSR: {e}");
170             RequestProcessingError::InternalError
171         })?
172         .to_vec())
173 }
174 
175 #[cfg(test)]
176 mod tests {
177     use super::*;
178 
179     /// The keys of device info map should be in the length-first core deterministic encoding
180     /// order as per RFC8949.
181     /// The CBOR ordering rules are:
182     /// 1. If two keys have different lengths, the shorter one sorts earlier;
183     /// 2. If two keys have the same length, the one with the lower value in
184     ///  (bytewise) lexical order sorts earlier.
185     #[test]
device_info_is_in_length_first_deterministic_order()186     fn device_info_is_in_length_first_deterministic_order() {
187         let device_info = cbor!(device_info()).unwrap();
188         let device_info_map = device_info.as_map().unwrap();
189         let device_info_keys: Vec<&str> =
190             device_info_map.iter().map(|k| k.0.as_text().unwrap()).collect();
191         let mut sorted_keys = device_info_keys.clone();
192         sorted_keys.sort_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)));
193         assert_eq!(device_info_keys, sorted_keys);
194     }
195 }
196