blob: 5ceedea286b692ebfa260d4dca0c0bce30b622bb [file] [log] [blame]
Shikha Panwar95084df2023-07-22 11:47:45 +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//! Class for encapsulating & managing represent VM secrets.
16
Shikha Panwarf18ffc32024-03-04 16:57:02 +000017use anyhow::{anyhow, ensure, Context, Result};
Shikha Panwar5d6a6752023-12-14 22:08:26 +000018use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
19use android_hardware_security_secretkeeper::aidl::android::hardware::security::secretkeeper::ISecretkeeper::ISecretkeeper;
20use secretkeeper_comm::data_types::request::Request;
21use binder::{Strong};
Shikha Panwar14abe442024-02-23 15:04:27 +000022use coset::{CoseKey, CborSerializable, CborOrdering};
Shikha Panwar101ac8f2024-01-19 11:20:18 +000023use dice_policy_builder::{CertIndex, ConstraintSpec, ConstraintType, policy_for_dice_chain, MissingAction, WILDCARD_FULL_ARRAY};
Shikha Panwar95084df2023-07-22 11:47:45 +000024use diced_open_dice::{DiceArtifacts, OwnedDiceArtifacts};
25use keystore2_crypto::ZVec;
26use openssl::hkdf::hkdf;
27use openssl::md::Md;
28use openssl::sha;
Shikha Panwar6b178322023-12-23 00:05:17 +000029use secretkeeper_client::dice::OwnedDiceArtifactsWithExplicitKey;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000030use secretkeeper_client::SkSession;
31use secretkeeper_comm::data_types::{Id, ID_SIZE, Secret, SECRET_SIZE};
32use secretkeeper_comm::data_types::response::Response;
33use secretkeeper_comm::data_types::packet::{ResponsePacket, ResponseType};
34use secretkeeper_comm::data_types::request_response_impl::{
35 StoreSecretRequest, GetSecretResponse, GetSecretRequest};
36use secretkeeper_comm::data_types::error::SecretkeeperError;
Shikha Panwar14abe442024-02-23 15:04:27 +000037use std::fs;
Shikha Panwar5d6a6752023-12-14 22:08:26 +000038use zeroize::Zeroizing;
Shikha Panwar95084df2023-07-22 11:47:45 +000039
Shikha Panwar3d3a70a2023-08-21 20:02:08 +000040const ENCRYPTEDSTORE_KEY_IDENTIFIER: &str = "encryptedstore_key";
Shikha Panwar6b178322023-12-23 00:05:17 +000041const AUTHORITY_HASH: i64 = -4670549;
42const MODE: i64 = -4670551;
43const CONFIG_DESC: i64 = -4670548;
44const SECURITY_VERSION: i64 = -70005;
Shikha Panwar101ac8f2024-01-19 11:20:18 +000045const SUBCOMPONENT_DESCRIPTORS: i64 = -71002;
46const SUBCOMPONENT_SECURITY_VERSION: i64 = 2;
47const SUBCOMPONENT_AUTHORITY_HASH: i64 = 4;
48// Index of DiceChainEntry corresponding to Payload (relative to the end considering DICE Chain
49// as an array)
50const PAYLOAD_INDEX_FROM_END: usize = 0;
Shikha Panwar3d3a70a2023-08-21 20:02:08 +000051
Shikha Panwar3d3a70a2023-08-21 20:02:08 +000052// Generated using hexdump -vn32 -e'14/1 "0x%02X, " 1 "\n"' /dev/urandom
53const SALT_ENCRYPTED_STORE: &[u8] = &[
54 0xFC, 0x1D, 0x35, 0x7B, 0x96, 0xF3, 0xEF, 0x17, 0x78, 0x7D, 0x70, 0xED, 0xEA, 0xFE, 0x1D, 0x6F,
55 0xB3, 0xF9, 0x40, 0xCE, 0xDD, 0x99, 0x40, 0xAA, 0xA7, 0x0E, 0x92, 0x73, 0x90, 0x86, 0x4A, 0x75,
56];
57const SALT_PAYLOAD_SERVICE: &[u8] = &[
58 0x8B, 0x0F, 0xF0, 0xD3, 0xB1, 0x69, 0x2B, 0x95, 0x84, 0x2C, 0x9E, 0x3C, 0x99, 0x56, 0x7A, 0x22,
59 0x55, 0xF8, 0x08, 0x23, 0x81, 0x5F, 0xF5, 0x16, 0x20, 0x3E, 0xBE, 0xBA, 0xB7, 0xA8, 0x43, 0x92,
60];
61
Shikha Panwar95084df2023-07-22 11:47:45 +000062pub enum VmSecret {
63 // V2 secrets are derived from 2 independently secured secrets:
64 // 1. Secretkeeper protected secrets (skp secret).
65 // 2. Dice Sealing CDIs (Similar to V1).
66 //
67 // These are protected against rollback of boot images i.e. VM instance rebooted
68 // with downgraded images will not have access to VM's secret.
69 // V2 secrets require hardware support - Secretkeeper HAL, which (among other things)
70 // is backed by tamper-evident storage, providing rollback protection to these secrets.
Shikha Panwar6b178322023-12-23 00:05:17 +000071 V2 { dice_artifacts: OwnedDiceArtifactsWithExplicitKey, skp_secret: ZVec },
Shikha Panwar95084df2023-07-22 11:47:45 +000072 // V1 secrets are not protected against rollback of boot images.
73 // They are reliable only if rollback of images was prevented by verified boot ie,
74 // each stage (including pvmfw/Microdroid/Microdroid Manager) prevents downgrade of next
75 // stage. These are now legacy secrets & used only when Secretkeeper HAL is not supported
76 // by device.
Shikha Panwar6b178322023-12-23 00:05:17 +000077 V1 { dice_artifacts: OwnedDiceArtifacts },
Shikha Panwar95084df2023-07-22 11:47:45 +000078}
79
Shikha Panwar14abe442024-02-23 15:04:27 +000080// For supporting V2 secrets, guest expects the public key to be present in the Linux device tree.
81fn get_secretkeeper_identity() -> Result<CoseKey> {
82 let key = fs::read(super::SECRETKEEPER_KEY)?;
83 let mut key = CoseKey::from_slice(&key)?;
84 key.canonicalize(CborOrdering::Lexicographic);
85 Ok(key)
86}
87
Shikha Panwar95084df2023-07-22 11:47:45 +000088impl VmSecret {
Shikha Panwar5d6a6752023-12-14 22:08:26 +000089 pub fn new(
90 dice_artifacts: OwnedDiceArtifacts,
91 vm_service: &Strong<dyn IVirtualMachineService>,
Shikha Panwar0503cb02024-01-05 10:11:28 +000092 ) -> Result<Self> {
Shikha Panwar5d6a6752023-12-14 22:08:26 +000093 ensure!(dice_artifacts.bcc().is_some(), "Dice chain missing");
94
Shikha Panwarf18ffc32024-03-04 16:57:02 +000095 let Some(sk_service) =
96 is_sk_supported(vm_service).context("Failed to check if Secretkeeper is supported")?
97 else {
Shikha Panwar0503cb02024-01-05 10:11:28 +000098 // Use V1 secrets if Secretkeeper is not supported.
99 return Ok(Self::V1 { dice_artifacts });
100 };
Shikha Panwar14abe442024-02-23 15:04:27 +0000101
Shikha Panwarf18ffc32024-03-04 16:57:02 +0000102 let explicit_dice = OwnedDiceArtifactsWithExplicitKey::from_owned_artifacts(dice_artifacts)
103 .context("Failed to get Dice artifacts in explicit key format")?;
Shikha Panwar14abe442024-02-23 15:04:27 +0000104 // For pVM, skp_secret are stored in Secretkeeper. For non-protected it is all 0s.
Shikha Panwar0503cb02024-01-05 10:11:28 +0000105 let mut skp_secret = Zeroizing::new([0u8; SECRET_SIZE]);
106 if super::is_strict_boot() {
Shikha Panwarf18ffc32024-03-04 16:57:02 +0000107 let mut session = SkSession::new(
108 sk_service,
109 &explicit_dice,
110 Some(get_secretkeeper_identity().context("Failed to get secretkeeper identity")?),
111 )
112 .context("Failed to setup a Secretkeeper session")?;
113 let id = super::get_instance_id()
114 .context("Failed to get instance-id")?
115 .ok_or(anyhow!("Missing instance-id"))?;
Shikha Panwar14abe442024-02-23 15:04:27 +0000116 let explicit_dice_chain = explicit_dice
117 .explicit_key_dice_chain()
118 .ok_or(anyhow!("Missing explicit dice chain, this is unusual"))?;
Shikha Panwarf18ffc32024-03-04 16:57:02 +0000119 let policy = sealing_policy(explicit_dice_chain)
120 .map_err(|e| anyhow!("Failed to build a sealing_policy: {e}"))?;
Shikha Panwar0503cb02024-01-05 10:11:28 +0000121 if super::is_new_instance() {
Shikha Panwar14abe442024-02-23 15:04:27 +0000122 // New instance -> create a secret & store in Secretkeeper.
Shikha Panwar0503cb02024-01-05 10:11:28 +0000123 *skp_secret = rand::random();
Shikha Panwarf18ffc32024-03-04 16:57:02 +0000124 store_secret(&mut session, id, skp_secret.clone(), policy)
125 .context("Failed to store secret in Secretkeeper")?;
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000126 } else {
Shikha Panwar0503cb02024-01-05 10:11:28 +0000127 // Subsequent run of the pVM -> get the secret stored in Secretkeeper.
Shikha Panwarf18ffc32024-03-04 16:57:02 +0000128 *skp_secret = get_secret(&mut session, id, Some(policy))
129 .context("Failed to get secret from Secretkeeper")?;
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000130 }
Shikha Panwar95084df2023-07-22 11:47:45 +0000131 }
Shikha Panwar0503cb02024-01-05 10:11:28 +0000132 Ok(Self::V2 {
133 dice_artifacts: explicit_dice,
134 skp_secret: ZVec::try_from(skp_secret.to_vec())?,
135 })
Shikha Panwar95084df2023-07-22 11:47:45 +0000136 }
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000137
Shikha Panwar6b178322023-12-23 00:05:17 +0000138 pub fn dice_artifacts(&self) -> &dyn DiceArtifacts {
Shikha Panwar95084df2023-07-22 11:47:45 +0000139 match self {
Shikha Panwar6b178322023-12-23 00:05:17 +0000140 Self::V2 { dice_artifacts, .. } => dice_artifacts,
141 Self::V1 { dice_artifacts } => dice_artifacts,
Shikha Panwar95084df2023-07-22 11:47:45 +0000142 }
143 }
144
145 fn get_vm_secret(&self, salt: &[u8], identifier: &[u8], key: &mut [u8]) -> Result<()> {
146 match self {
Shikha Panwar6b178322023-12-23 00:05:17 +0000147 Self::V2 { dice_artifacts, skp_secret } => {
Shikha Panwar95084df2023-07-22 11:47:45 +0000148 let mut hasher = sha::Sha256::new();
Shikha Panwar6b178322023-12-23 00:05:17 +0000149 hasher.update(dice_artifacts.cdi_seal());
Shikha Panwar95084df2023-07-22 11:47:45 +0000150 hasher.update(skp_secret);
151 hkdf(key, Md::sha256(), &hasher.finish(), salt, identifier)?
152 }
Shikha Panwar6b178322023-12-23 00:05:17 +0000153 Self::V1 { dice_artifacts } => {
154 hkdf(key, Md::sha256(), dice_artifacts.cdi_seal(), salt, identifier)?
155 }
Shikha Panwar95084df2023-07-22 11:47:45 +0000156 }
157 Ok(())
158 }
159
Shikha Panwar3d3a70a2023-08-21 20:02:08 +0000160 /// Derive sealing key for payload with following identifier.
161 pub fn derive_payload_sealing_key(&self, identifier: &[u8], key: &mut [u8]) -> Result<()> {
162 self.get_vm_secret(SALT_PAYLOAD_SERVICE, identifier, key)
163 }
164
165 /// Derive encryptedstore key. This uses hardcoded random salt & fixed identifier.
166 pub fn derive_encryptedstore_key(&self, key: &mut [u8]) -> Result<()> {
167 self.get_vm_secret(SALT_ENCRYPTED_STORE, ENCRYPTEDSTORE_KEY_IDENTIFIER.as_bytes(), key)
Shikha Panwar95084df2023-07-22 11:47:45 +0000168 }
169}
170
Shikha Panwar6b178322023-12-23 00:05:17 +0000171// Construct a sealing policy on the dice chain. VMs uses the following set of constraint for
172// protecting secrets against rollback of boot images.
173// 1. ExactMatch on AUTHORITY_HASH (Required ie, each DiceChainEntry must have it).
174// 2. ExactMatch on MODE (Required) - Secret should be inaccessible if any of the runtime
175// configuration changes. For ex, the secrets stored with a boot stage being in Normal mode
176// should be inaccessible when the same stage is booted in Debug mode.
177// 3. GreaterOrEqual on SECURITY_VERSION (Optional): The secrets will be accessible if version of
178// any image is greater or equal to the set version. This is an optional field, certain
179// components may chose to prevent booting of rollback images for ex, ABL is expected to provide
180// rollback protection of pvmfw. Such components may chose to not put SECURITY_VERSION in the
181// corresponding DiceChainEntry.
Shikha Panwar101ac8f2024-01-19 11:20:18 +0000182// 4. For each Subcomponent on the last DiceChainEntry (which corresponds to VM payload, See
183// microdroid_manager/src/vm_config.cddl):
184// - GreaterOrEqual on SECURITY_VERSION (Required)
185// - ExactMatch on AUTHORITY_HASH (Required).
Shikha Panwar6b178322023-12-23 00:05:17 +0000186fn sealing_policy(dice: &[u8]) -> Result<Vec<u8>, String> {
187 let constraint_spec = [
Shikha Panwar101ac8f2024-01-19 11:20:18 +0000188 ConstraintSpec::new(
189 ConstraintType::ExactMatch,
190 vec![AUTHORITY_HASH],
191 MissingAction::Fail,
192 CertIndex::All,
193 ),
194 ConstraintSpec::new(
195 ConstraintType::ExactMatch,
196 vec![MODE],
197 MissingAction::Fail,
198 CertIndex::All,
199 ),
Shikha Panwar6b178322023-12-23 00:05:17 +0000200 ConstraintSpec::new(
201 ConstraintType::GreaterOrEqual,
202 vec![CONFIG_DESC, SECURITY_VERSION],
Shikha Panwar091bfbe2024-01-15 09:37:06 +0000203 MissingAction::Ignore,
Shikha Panwar101ac8f2024-01-19 11:20:18 +0000204 CertIndex::All,
205 ),
206 ConstraintSpec::new(
207 ConstraintType::GreaterOrEqual,
208 vec![
209 CONFIG_DESC,
210 SUBCOMPONENT_DESCRIPTORS,
211 WILDCARD_FULL_ARRAY,
212 SUBCOMPONENT_SECURITY_VERSION,
213 ],
214 MissingAction::Fail,
215 CertIndex::FromEnd(PAYLOAD_INDEX_FROM_END),
216 ),
217 ConstraintSpec::new(
218 ConstraintType::ExactMatch,
219 vec![
220 CONFIG_DESC,
221 SUBCOMPONENT_DESCRIPTORS,
222 WILDCARD_FULL_ARRAY,
223 SUBCOMPONENT_AUTHORITY_HASH,
224 ],
225 MissingAction::Fail,
226 CertIndex::FromEnd(PAYLOAD_INDEX_FROM_END),
Shikha Panwar6b178322023-12-23 00:05:17 +0000227 ),
228 ];
229
Shikha Panware763ce12024-01-19 11:20:18 +0000230 policy_for_dice_chain(dice, &constraint_spec)?
Shikha Panwar6b178322023-12-23 00:05:17 +0000231 .to_vec()
232 .map_err(|e| format!("DicePolicy construction failed {e:?}"))
233}
234
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000235fn store_secret(
Shikha Panwar6b178322023-12-23 00:05:17 +0000236 session: &mut SkSession,
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000237 id: [u8; ID_SIZE],
238 secret: Zeroizing<[u8; SECRET_SIZE]>,
Shikha Panwar6b178322023-12-23 00:05:17 +0000239 sealing_policy: Vec<u8>,
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000240) -> Result<()> {
Shikha Panwar6b178322023-12-23 00:05:17 +0000241 let store_request = StoreSecretRequest { id: Id(id), secret: Secret(*secret), sealing_policy };
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000242 log::info!("Secretkeeper operation: {:?}", store_request);
243
244 let store_request = store_request.serialize_to_packet().to_vec().map_err(anyhow_err)?;
Shikha Panwar6b178322023-12-23 00:05:17 +0000245 let store_response = session.secret_management_request(&store_request)?;
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000246 let store_response = ResponsePacket::from_slice(&store_response).map_err(anyhow_err)?;
247 let response_type = store_response.response_type().map_err(anyhow_err)?;
248 ensure!(
249 response_type == ResponseType::Success,
250 "Secretkeeper store failed with error: {:?}",
251 *SecretkeeperError::deserialize_from_packet(store_response).map_err(anyhow_err)?
252 );
253 Ok(())
254}
255
256fn get_secret(
Shikha Panwar6b178322023-12-23 00:05:17 +0000257 session: &mut SkSession,
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000258 id: [u8; ID_SIZE],
Shikha Panwar6b178322023-12-23 00:05:17 +0000259 updated_sealing_policy: Option<Vec<u8>>,
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000260) -> Result<[u8; SECRET_SIZE]> {
Shikha Panwar6b178322023-12-23 00:05:17 +0000261 let get_request = GetSecretRequest { id: Id(id), updated_sealing_policy };
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000262 log::info!("Secretkeeper operation: {:?}", get_request);
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000263 let get_request = get_request.serialize_to_packet().to_vec().map_err(anyhow_err)?;
Shikha Panwar6b178322023-12-23 00:05:17 +0000264 let get_response = session.secret_management_request(&get_request)?;
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000265 let get_response = ResponsePacket::from_slice(&get_response).map_err(anyhow_err)?;
266 let response_type = get_response.response_type().map_err(anyhow_err)?;
267 ensure!(
268 response_type == ResponseType::Success,
269 "Secretkeeper get failed with error: {:?}",
270 *SecretkeeperError::deserialize_from_packet(get_response).map_err(anyhow_err)?
271 );
272 let get_response =
273 *GetSecretResponse::deserialize_from_packet(get_response).map_err(anyhow_err)?;
274 Ok(get_response.secret.0)
275}
276
277#[inline]
278fn anyhow_err<E: core::fmt::Debug>(err: E) -> anyhow::Error {
279 anyhow!("{:?}", err)
280}
281
Shikha Panwar5803dc72024-03-06 12:00:50 +0000282// Get the secretkeeper connection if supported. Host can be consulted whether the device supports
283// secretkeeper but that should be used with caution for protected VM.
284fn is_sk_supported(
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000285 host: &Strong<dyn IVirtualMachineService>,
286) -> Result<Option<Strong<dyn ISecretkeeper>>> {
287 let sk = if cfg!(llpvm_changes) {
Shikha Panwar14abe442024-02-23 15:04:27 +0000288 host.getSecretkeeper()
289 // TODO rename this error!
290 .map_err(|e| {
291 super::MicrodroidError::FailedToConnectToVirtualizationService(format!(
292 "Failed to get Secretkeeper: {e:?}"
293 ))
294 })?
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000295 } else {
296 // LLPVM flag is disabled
297 None
298 };
299 Ok(sk)
Shikha Panwar95084df2023-07-22 11:47:45 +0000300}