blob: 1af53ad0c5d21b0a69ed72451c970fd4e4f0cc0e [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 Wang7b2ab942023-09-12 13:04:42 +000018use super::ec_key::EcKey;
Alice Wangff5592d2023-09-13 15:27:39 +000019use super::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 Wangf7c0f942023-09-14 09:33:04 +000023use ciborium::{cbor, value::Value};
Alice Wangd80e99e2023-09-15 13:26:01 +000024use core::result;
Alice Wangf7c0f942023-09-14 09:33:04 +000025use coset::{iana, AsCborValue, CoseSign1, CoseSign1Builder, HeaderBuilder};
Alice Wang4ca86b62023-09-22 11:49:43 +000026use diced_open_dice::{kdf, keypair_from_seed, sign, DiceArtifacts, PrivateKey};
Alice Wang6bc2a702023-09-22 12:42:13 +000027use log::error;
Alice Wangd80e99e2023-09-15 13:26:01 +000028use service_vm_comm::{EcdsaP256KeyPair, GenerateCertificateRequestParams, RequestProcessingError};
Alice Wang4ca86b62023-09-22 11:49:43 +000029use zeroize::Zeroizing;
Alice Wangd80e99e2023-09-15 13:26:01 +000030
31type Result<T> = result::Result<T, RequestProcessingError>;
Alice Wang33f4cae2023-09-05 09:27:39 +000032
Alice Wang4ca86b62023-09-22 11:49:43 +000033/// The salt is generated randomly with:
34/// hexdump -vn32 -e'16/1 "0x%02X, " 1 "\n"' /dev/urandom
35const HMAC_KEY_SALT: [u8; 32] = [
36 0x82, 0x80, 0xFA, 0xD3, 0xA8, 0x0A, 0x9A, 0x4B, 0xF7, 0xA5, 0x7D, 0x7B, 0xE9, 0xC3, 0xAB, 0x13,
37 0x89, 0xDC, 0x7B, 0x46, 0xEE, 0x71, 0x22, 0xB4, 0x5F, 0x4C, 0x3F, 0xE2, 0x40, 0x04, 0x3B, 0x6C,
38];
39const HMAC_KEY_INFO: &[u8] = b"rialto hmac key";
40const HMAC_KEY_LENGTH: usize = 32;
41
Alice Wang77639bf2023-09-21 06:57:12 +000042pub(super) fn generate_ecdsa_p256_key_pair(
Alice Wang4ca86b62023-09-22 11:49:43 +000043 dice_artifacts: &dyn DiceArtifacts,
Alice Wang77639bf2023-09-21 06:57:12 +000044) -> Result<EcdsaP256KeyPair> {
Alice Wang4ca86b62023-09-22 11:49:43 +000045 let hmac_key = derive_hmac_key(dice_artifacts)?;
Alice Wang7b2ab942023-09-12 13:04:42 +000046 let ec_key = EcKey::new_p256()?;
Alice Wang4ca86b62023-09-22 11:49:43 +000047 let maced_public_key = build_maced_public_key(ec_key.cose_public_key()?, hmac_key.as_ref())?;
Alice Wang7b2ab942023-09-12 13:04:42 +000048
49 // TODO(b/279425980): Encrypt the private key in a key blob.
50 // Remove the printing of the private key.
51 log::debug!("Private key: {:?}", ec_key.private_key()?.as_slice());
52
Alice Wanga78d3f02023-09-13 12:39:16 +000053 let key_pair = EcdsaP256KeyPair { maced_public_key, key_blob: Vec::new() };
Alice Wang33f4cae2023-09-05 09:27:39 +000054 Ok(key_pair)
55}
Alice Wang464e4732023-09-06 12:25:22 +000056
Alice Wangf7c0f942023-09-14 09:33:04 +000057const CSR_PAYLOAD_SCHEMA_V3: u8 = 3;
58const AUTH_REQ_SCHEMA_V1: u8 = 1;
59// TODO(b/300624493): Add a new certificate type for AVF CSR.
60const CERTIFICATE_TYPE: &str = "keymint";
61
62/// Builds the CSR described in:
63///
64/// hardware/interfaces/security/rkp/aidl/android/hardware/security/keymint/
65/// generateCertificateRequestV2.cddl
Alice Wang464e4732023-09-06 12:25:22 +000066pub(super) fn generate_certificate_request(
Alice Wangff5592d2023-09-13 15:27:39 +000067 params: GenerateCertificateRequestParams,
Alice Wang6bc2a702023-09-22 12:42:13 +000068 dice_artifacts: &dyn DiceArtifacts,
Alice Wang464e4732023-09-06 12:25:22 +000069) -> Result<Vec<u8>> {
Alice Wang4ca86b62023-09-22 11:49:43 +000070 let hmac_key = derive_hmac_key(dice_artifacts)?;
Alice Wangf7c0f942023-09-14 09:33:04 +000071 let mut public_keys: Vec<Value> = Vec::new();
Alice Wangff5592d2023-09-13 15:27:39 +000072 for key_to_sign in params.keys_to_sign {
Alice Wang4ca86b62023-09-22 11:49:43 +000073 let public_key = validate_public_key(&key_to_sign, hmac_key.as_ref())?;
Alice Wangf7c0f942023-09-14 09:33:04 +000074 public_keys.push(public_key.to_cbor_value()?);
Alice Wangff5592d2023-09-13 15:27:39 +000075 }
Alice Wangf7c0f942023-09-14 09:33:04 +000076 // Builds `CsrPayload`.
77 let csr_payload = cbor!([
78 Value::Integer(CSR_PAYLOAD_SCHEMA_V3.into()),
79 Value::Text(String::from(CERTIFICATE_TYPE)),
80 // TODO(b/299256925): Add device info in CBOR format here.
81 Value::Array(public_keys),
82 ])?;
83 let csr_payload = cbor_to_vec(&csr_payload)?;
84
85 // Builds `SignedData`.
86 let signed_data_payload =
87 cbor!([Value::Bytes(params.challenge.to_vec()), Value::Bytes(csr_payload)])?;
Alice Wang6bc2a702023-09-22 12:42:13 +000088 let signed_data = build_signed_data(&signed_data_payload, dice_artifacts)?.to_cbor_value()?;
Alice Wangf7c0f942023-09-14 09:33:04 +000089
90 // Builds `AuthenticatedRequest<CsrPayload>`.
Alice Wanga2738b72023-09-22 15:31:28 +000091 // Currently `UdsCerts` is left empty because it is only needed for Samsung devices.
92 // Check http://b/301574013#comment3 for more information.
Alice Wangf7c0f942023-09-14 09:33:04 +000093 let uds_certs = Value::Map(Vec::new());
Alice Wanga2738b72023-09-22 15:31:28 +000094 let dice_cert_chain = dice_artifacts
95 .bcc()
96 .map(read_to_value)
97 .ok_or(RequestProcessingError::MissingDiceChain)??;
Alice Wangf7c0f942023-09-14 09:33:04 +000098 let auth_req = cbor!([
99 Value::Integer(AUTH_REQ_SCHEMA_V1.into()),
100 uds_certs,
101 dice_cert_chain,
102 signed_data,
103 ])?;
104 cbor_to_vec(&auth_req)
105}
106
Alice Wang4ca86b62023-09-22 11:49:43 +0000107fn derive_hmac_key(dice_artifacts: &dyn DiceArtifacts) -> Result<Zeroizing<[u8; HMAC_KEY_LENGTH]>> {
108 let mut key = Zeroizing::new([0u8; HMAC_KEY_LENGTH]);
109 kdf(dice_artifacts.cdi_seal(), &HMAC_KEY_SALT, HMAC_KEY_INFO, key.as_mut()).map_err(|e| {
110 error!("Failed to compute the HMAC key: {e}");
111 RequestProcessingError::InternalError
112 })?;
113 Ok(key)
114}
115
Alice Wangf7c0f942023-09-14 09:33:04 +0000116/// Builds the `SignedData` for the given payload.
Alice Wang6bc2a702023-09-22 12:42:13 +0000117fn build_signed_data(payload: &Value, dice_artifacts: &dyn DiceArtifacts) -> Result<CoseSign1> {
118 let cdi_leaf_priv = derive_cdi_leaf_priv(dice_artifacts).map_err(|e| {
119 error!("Failed to derive the CDI_Leaf_Priv: {e}");
120 RequestProcessingError::InternalError
121 })?;
122 let signing_algorithm = iana::Algorithm::EdDSA;
Alice Wangf7c0f942023-09-14 09:33:04 +0000123 let protected = HeaderBuilder::new().algorithm(signing_algorithm).build();
124 let signed_data = CoseSign1Builder::new()
125 .protected(protected)
126 .payload(cbor_to_vec(payload)?)
Alice Wang6bc2a702023-09-22 12:42:13 +0000127 .try_create_signature(&[], |message| sign_message(message, &cdi_leaf_priv))?
Alice Wangf7c0f942023-09-14 09:33:04 +0000128 .build();
129 Ok(signed_data)
130}
131
Alice Wang6bc2a702023-09-22 12:42:13 +0000132fn derive_cdi_leaf_priv(dice_artifacts: &dyn DiceArtifacts) -> diced_open_dice::Result<PrivateKey> {
133 let (_, private_key) = keypair_from_seed(dice_artifacts.cdi_attest())?;
134 Ok(private_key)
135}
136
137fn sign_message(message: &[u8], private_key: &PrivateKey) -> Result<Vec<u8>> {
138 Ok(sign(message, private_key.as_array())
139 .map_err(|e| {
140 error!("Failed to sign the CSR: {e}");
141 RequestProcessingError::InternalError
142 })?
143 .to_vec())
Alice Wang464e4732023-09-06 12:25:22 +0000144}
Alice Wangf7c0f942023-09-14 09:33:04 +0000145
146fn cbor_to_vec(v: &Value) -> Result<Vec<u8>> {
147 let mut data = Vec::new();
148 ciborium::into_writer(v, &mut data).map_err(coset::CoseError::from)?;
149 Ok(data)
150}
Alice Wanga2738b72023-09-22 15:31:28 +0000151
152/// Read a CBOR `Value` from a byte slice, failing if any extra data remains
153/// after the `Value` has been read.
154fn read_to_value(mut data: &[u8]) -> Result<Value> {
155 let value = ciborium::from_reader(&mut data).map_err(|e| {
156 error!("Failed to deserialize the data into CBOR value: {e}");
157 RequestProcessingError::CborValueError
158 })?;
159 if data.is_empty() {
160 Ok(value)
161 } else {
162 error!("CBOR input has extra data.");
163 Err(RequestProcessingError::CborValueError)
164 }
165}