blob: c62a36b38173f4c692ef67c5ccb579f839a00ea6 [file] [log] [blame]
Alice Wang33f4cae2023-09-05 09:27:39 +00001// 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
Alice Wang7b2ab942023-09-12 13:04:42 +000016//! service VM via the RKP (Remote Key Provisioning) server.
Alice Wang33f4cae2023-09-05 09:27:39 +000017
Alice Wang8b8e6e62023-10-02 09:10:13 +000018use crate::keyblob::EncryptedKeyBlob;
Alice Wangfacc2b82023-10-05 14:05:47 +000019use crate::pub_key::{build_maced_public_key, validate_public_key};
Alice Wangf7c0f942023-09-14 09:33:04 +000020use alloc::string::String;
21use alloc::vec;
Alice Wang33f4cae2023-09-05 09:27:39 +000022use alloc::vec::Vec;
Alice Wangb3fcf632023-09-26 08:32:55 +000023use bssl_avf::EcKey;
Alice Wang0a76da32024-03-05 13:41:27 +000024use ciborium::{
25 cbor,
26 value::{CanonicalValue, Value},
27};
Alice Wangd80e99e2023-09-15 13:26:01 +000028use core::result;
Alice Wangff381112024-05-22 12:14:39 +000029use coset::{AsCborValue, CoseSign1, CoseSign1Builder, HeaderBuilder};
30use diced_open_dice::{
31 derive_cdi_leaf_priv, kdf, sign, DiceArtifacts, PrivateKey, DICE_COSE_KEY_ALG_VALUE,
32};
Alice Wange39c9072024-04-30 10:02:58 +000033use log::{debug, error};
Alice Wangd80e99e2023-09-15 13:26:01 +000034use service_vm_comm::{EcdsaP256KeyPair, GenerateCertificateRequestParams, RequestProcessingError};
Alice Wang4ca86b62023-09-22 11:49:43 +000035use zeroize::Zeroizing;
Alice Wangd80e99e2023-09-15 13:26:01 +000036
37type Result<T> = result::Result<T, RequestProcessingError>;
Alice Wang33f4cae2023-09-05 09:27:39 +000038
Alice Wang4ca86b62023-09-22 11:49:43 +000039/// The salt is generated randomly with:
40/// hexdump -vn32 -e'16/1 "0x%02X, " 1 "\n"' /dev/urandom
41const 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];
Alice Wang8b8e6e62023-10-02 09:10:13 +000045const HMAC_KEY_INFO: &[u8] = b"rialto hmac wkey";
Alice Wang4ca86b62023-09-22 11:49:43 +000046const HMAC_KEY_LENGTH: usize = 32;
47
Alice Wang77639bf2023-09-21 06:57:12 +000048pub(super) fn generate_ecdsa_p256_key_pair(
Alice Wang4ca86b62023-09-22 11:49:43 +000049 dice_artifacts: &dyn DiceArtifacts,
Alice Wang77639bf2023-09-21 06:57:12 +000050) -> Result<EcdsaP256KeyPair> {
Alice Wang4ca86b62023-09-22 11:49:43 +000051 let hmac_key = derive_hmac_key(dice_artifacts)?;
Alice Wang9bd98092023-11-10 14:08:12 +000052 let mut ec_key = EcKey::new_p256()?;
53 ec_key.generate_key()?;
Alice Wang8b8e6e62023-10-02 09:10:13 +000054
Alice Wang4ca86b62023-09-22 11:49:43 +000055 let maced_public_key = build_maced_public_key(ec_key.cose_public_key()?, hmac_key.as_ref())?;
Alice Wang8b8e6e62023-10-02 09:10:13 +000056 let key_blob =
Alice Wang000595b2023-10-02 13:46:45 +000057 EncryptedKeyBlob::new(ec_key.ec_private_key()?.as_slice(), dice_artifacts.cdi_seal())?;
Alice Wang7b2ab942023-09-12 13:04:42 +000058
Alice Wang5dddeea2023-10-13 12:56:22 +000059 let key_pair =
60 EcdsaP256KeyPair { maced_public_key, key_blob: cbor_util::serialize(&key_blob)? };
Alice Wang33f4cae2023-09-05 09:27:39 +000061 Ok(key_pair)
62}
Alice Wang464e4732023-09-06 12:25:22 +000063
Alice Wangf7c0f942023-09-14 09:33:04 +000064const CSR_PAYLOAD_SCHEMA_V3: u8 = 3;
65const AUTH_REQ_SCHEMA_V1: u8 = 1;
66// TODO(b/300624493): Add a new certificate type for AVF CSR.
67const 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
Alice Wang464e4732023-09-06 12:25:22 +000073pub(super) fn generate_certificate_request(
Alice Wangff5592d2023-09-13 15:27:39 +000074 params: GenerateCertificateRequestParams,
Alice Wang6bc2a702023-09-22 12:42:13 +000075 dice_artifacts: &dyn DiceArtifacts,
Alice Wang464e4732023-09-06 12:25:22 +000076) -> Result<Vec<u8>> {
Alice Wang4ca86b62023-09-22 11:49:43 +000077 let hmac_key = derive_hmac_key(dice_artifacts)?;
Alice Wangf7c0f942023-09-14 09:33:04 +000078 let mut public_keys: Vec<Value> = Vec::new();
Alice Wangff5592d2023-09-13 15:27:39 +000079 for key_to_sign in params.keys_to_sign {
Alice Wang4ca86b62023-09-22 11:49:43 +000080 let public_key = validate_public_key(&key_to_sign, hmac_key.as_ref())?;
Alice Wangf7c0f942023-09-14 09:33:04 +000081 public_keys.push(public_key.to_cbor_value()?);
Alice Wangff5592d2023-09-13 15:27:39 +000082 }
Alice Wange39c9072024-04-30 10:02:58 +000083 debug!("Successfully validated all '{}' public keys.", public_keys.len());
84
Alice Wangf7c0f942023-09-14 09:33:04 +000085 // Builds `CsrPayload`.
86 let csr_payload = cbor!([
87 Value::Integer(CSR_PAYLOAD_SCHEMA_V3.into()),
88 Value::Text(String::from(CERTIFICATE_TYPE)),
Alice Wang68d11402024-01-02 13:59:44 +000089 device_info(),
Alice Wangf7c0f942023-09-14 09:33:04 +000090 Value::Array(public_keys),
91 ])?;
Alice Wang5dddeea2023-10-13 12:56:22 +000092 let csr_payload = cbor_util::serialize(&csr_payload)?;
Alice Wangf7c0f942023-09-14 09:33:04 +000093
94 // Builds `SignedData`.
95 let signed_data_payload =
96 cbor!([Value::Bytes(params.challenge.to_vec()), Value::Bytes(csr_payload)])?;
Alice Wang6bc2a702023-09-22 12:42:13 +000097 let signed_data = build_signed_data(&signed_data_payload, dice_artifacts)?.to_cbor_value()?;
Alice Wange39c9072024-04-30 10:02:58 +000098 debug!("Successfully signed the CSR payload.");
Alice Wangf7c0f942023-09-14 09:33:04 +000099
100 // Builds `AuthenticatedRequest<CsrPayload>`.
Alice Wanga2738b72023-09-22 15:31:28 +0000101 // Currently `UdsCerts` is left empty because it is only needed for Samsung devices.
102 // Check http://b/301574013#comment3 for more information.
Alice Wangf7c0f942023-09-14 09:33:04 +0000103 let uds_certs = Value::Map(Vec::new());
Alice Wangfacc2b82023-10-05 14:05:47 +0000104 let dice_cert_chain = dice_artifacts.bcc().ok_or(RequestProcessingError::MissingDiceChain)?;
Alice Wang5dddeea2023-10-13 12:56:22 +0000105 let dice_cert_chain: Value = cbor_util::deserialize(dice_cert_chain)?;
Alice Wangf7c0f942023-09-14 09:33:04 +0000106 let auth_req = cbor!([
107 Value::Integer(AUTH_REQ_SCHEMA_V1.into()),
108 uds_certs,
109 dice_cert_chain,
110 signed_data,
111 ])?;
Alice Wange39c9072024-04-30 10:02:58 +0000112 debug!("Successfully built the CBOR authenticated request.");
Alice Wang5dddeea2023-10-13 12:56:22 +0000113 Ok(cbor_util::serialize(&auth_req)?)
Alice Wangf7c0f942023-09-14 09:33:04 +0000114}
115
Alice Wang68d11402024-01-02 13:59:44 +0000116/// Generates the device info required by the RKP server as a temporary placeholder.
117/// More details in b/301592917.
Alice Wang0a76da32024-03-05 13:41:27 +0000118///
119/// The keys of the map should be in the length-first core deterministic encoding order
120/// as per RFC8949.
121fn device_info() -> CanonicalValue {
122 cbor!({
123 "brand" => "aosp-avf",
124 "fused" => 1,
125 "model" => "avf",
126 "device" => "avf",
127 "product" => "avf",
Alice Wang48eb6032024-05-13 08:08:03 +0000128 "vb_state" => "avf",
Alice Wang0a76da32024-03-05 13:41:27 +0000129 "manufacturer" => "aosp-avf",
Seth Moore0877f262024-05-28 19:17:19 +0000130 "vbmeta_digest" => Value::Bytes(vec![1u8; 1]),
Alice Wang48eb6032024-05-13 08:08:03 +0000131 "security_level" => "avf",
Alice Wang0a76da32024-03-05 13:41:27 +0000132 "boot_patch_level" => 20240202,
Alice Wang48eb6032024-05-13 08:08:03 +0000133 "bootloader_state" => "avf",
Alice Wang0a76da32024-03-05 13:41:27 +0000134 "system_patch_level" => 202402,
135 "vendor_patch_level" => 20240202,
136 })
Alice Wang68d11402024-01-02 13:59:44 +0000137 .unwrap()
Alice Wang0a76da32024-03-05 13:41:27 +0000138 .into()
Alice Wang68d11402024-01-02 13:59:44 +0000139}
140
Alice Wang4ca86b62023-09-22 11:49:43 +0000141fn 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
Alice Wangf7c0f942023-09-14 09:33:04 +0000150/// Builds the `SignedData` for the given payload.
Alice Wang6bc2a702023-09-22 12:42:13 +0000151fn 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 })?;
Alice Wangff381112024-05-22 12:14:39 +0000156 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();
Alice Wangf7c0f942023-09-14 09:33:04 +0000158 let signed_data = CoseSign1Builder::new()
159 .protected(protected)
Alice Wang5dddeea2023-10-13 12:56:22 +0000160 .payload(cbor_util::serialize(payload)?)
Alice Wang6bc2a702023-09-22 12:42:13 +0000161 .try_create_signature(&[], |message| sign_message(message, &cdi_leaf_priv))?
Alice Wangf7c0f942023-09-14 09:33:04 +0000162 .build();
163 Ok(signed_data)
164}
165
Alice Wang6bc2a702023-09-22 12:42:13 +0000166fn 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())
Alice Wang464e4732023-09-06 12:25:22 +0000173}
Alice Wang0a76da32024-03-05 13:41:27 +0000174
175#[cfg(test)]
176mod 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]
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}