blob: c918db51d7e28073b2a692bd5039879e4aaa72dc [file] [log] [blame]
David Brazdil66fc1202022-07-04 21:48:45 +01001// Copyright 2022, 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//! Integration test for Rialto.
16
17use android_system_virtualizationservice::{
18 aidl::android::system::virtualizationservice::{
Alice Wanga6357692023-09-07 14:59:37 +000019 VirtualMachineConfig::VirtualMachineConfig,
David Brazdil66fc1202022-07-04 21:48:45 +010020 VirtualMachineRawConfig::VirtualMachineRawConfig,
21 },
22 binder::{ParcelFileDescriptor, ProcessState},
23};
Alice Wang9646fb32023-09-08 10:01:31 +000024use anyhow::{bail, Context, Result};
Alice Wangeb77f7d2023-12-01 09:13:58 +000025use bssl_avf::{sha256, EcKey, PKey};
Alice Wangf7c0f942023-09-14 09:33:04 +000026use ciborium::value::Value;
Alice Wangde6bee52023-11-10 09:58:40 +000027use client_vm_csr::generate_attestation_key_and_csr;
Alice Wang20b8ebc2023-11-17 09:54:47 +000028use coset::{CborSerializable, CoseMac0, CoseSign};
David Brazdil66fc1202022-07-04 21:48:45 +010029use log::info;
Alice Wang9646fb32023-09-08 10:01:31 +000030use service_vm_comm::{
Alice Wang20b8ebc2023-11-17 09:54:47 +000031 ClientVmAttestationParams, Csr, CsrPayload, EcdsaP256KeyPair, GenerateCertificateRequestParams,
Alice Wangd3a96402023-11-24 15:37:39 +000032 Request, RequestProcessingError, Response, VmType,
Alice Wang9646fb32023-09-08 10:01:31 +000033};
Alice Wang1cc13502023-12-05 11:05:34 +000034use service_vm_fake_chain::client_vm::{
35 fake_client_vm_dice_artifacts, fake_sub_components, SubComponent,
36};
Alice Wang17dc76e2023-09-06 09:43:52 +000037use service_vm_manager::ServiceVm;
Alice Wang20b8ebc2023-11-17 09:54:47 +000038use std::fs;
David Brazdil66fc1202022-07-04 21:48:45 +010039use std::fs::File;
Alice Wangf7c0f942023-09-14 09:33:04 +000040use std::io;
David Brazdil66fc1202022-07-04 21:48:45 +010041use std::panic;
Alice Wang17dc76e2023-09-06 09:43:52 +000042use std::path::PathBuf;
Alice Wang6a504ef2023-12-21 15:37:55 +000043use std::str::FromStr;
Alice Wang17dc76e2023-09-06 09:43:52 +000044use vmclient::VmInstance;
Alice Wang6a504ef2023-12-21 15:37:55 +000045use x509_cert::{
46 certificate::{Certificate, Version},
47 der::{self, asn1, Decode, Encode},
48 name::Name,
49 spki::{AlgorithmIdentifier, ObjectIdentifier, SubjectPublicKeyInfo},
Alice Wang20b8ebc2023-11-17 09:54:47 +000050};
Alice Wang4e082c32023-07-11 07:41:50 +000051
Alice Wang9a8b39f2023-04-12 15:31:48 +000052const UNSIGNED_RIALTO_PATH: &str = "/data/local/tmp/rialto_test/arm64/rialto_unsigned.bin";
53const INSTANCE_IMG_PATH: &str = "/data/local/tmp/rialto_test/arm64/instance.img";
Alice Wang20b8ebc2023-11-17 09:54:47 +000054const TEST_CERT_CHAIN_PATH: &str = "testdata/rkp_cert_chain.der";
David Brazdil66fc1202022-07-04 21:48:45 +010055
Alice Wang9a8b39f2023-04-12 15:31:48 +000056#[test]
Alice Wange910b902023-09-07 10:35:12 +000057fn process_requests_in_protected_vm() -> Result<()> {
Alice Wang9646fb32023-09-08 10:01:31 +000058 check_processing_requests(VmType::ProtectedVm)
Alice Wang9a8b39f2023-04-12 15:31:48 +000059}
60
Alice Wange910b902023-09-07 10:35:12 +000061#[test]
62fn process_requests_in_non_protected_vm() -> Result<()> {
Alice Wang9646fb32023-09-08 10:01:31 +000063 check_processing_requests(VmType::NonProtectedVm)
64}
65
66fn check_processing_requests(vm_type: VmType) -> Result<()> {
67 let mut vm = start_service_vm(vm_type)?;
Alice Wange910b902023-09-07 10:35:12 +000068
69 check_processing_reverse_request(&mut vm)?;
Alice Wang74eb78b2023-11-09 16:13:10 +000070 let key_pair = check_processing_generating_key_pair_request(&mut vm)?;
71 check_processing_generating_certificate_request(&mut vm, &key_pair.maced_public_key)?;
Alice Wangd3a96402023-11-24 15:37:39 +000072 check_attestation_request(&mut vm, &key_pair, vm_type)?;
Alice Wange910b902023-09-07 10:35:12 +000073 Ok(())
74}
75
76fn check_processing_reverse_request(vm: &mut ServiceVm) -> Result<()> {
Alice Wang0486e252023-10-06 14:30:49 +000077 let message = "abc".repeat(500);
Alice Wange910b902023-09-07 10:35:12 +000078 let request = Request::Reverse(message.as_bytes().to_vec());
79
Alice Wangfbdc85b2023-09-07 12:56:46 +000080 let response = vm.process_request(request)?;
81 info!("Received response: {response:?}.");
Alice Wange910b902023-09-07 10:35:12 +000082
83 let expected_response: Vec<u8> = message.as_bytes().iter().rev().cloned().collect();
84 assert_eq!(Response::Reverse(expected_response), response);
85 Ok(())
86}
87
Alice Wang74eb78b2023-11-09 16:13:10 +000088fn check_processing_generating_key_pair_request(vm: &mut ServiceVm) -> Result<EcdsaP256KeyPair> {
Alice Wang9646fb32023-09-08 10:01:31 +000089 let request = Request::GenerateEcdsaP256KeyPair;
90
91 let response = vm.process_request(request)?;
92 info!("Received response: {response:?}.");
93
94 match response {
Alice Wang74eb78b2023-11-09 16:13:10 +000095 Response::GenerateEcdsaP256KeyPair(key_pair) => {
96 assert_array_has_nonzero(&key_pair.maced_public_key);
97 assert_array_has_nonzero(&key_pair.key_blob);
98 Ok(key_pair)
Alice Wanga78d3f02023-09-13 12:39:16 +000099 }
Alice Wangff5592d2023-09-13 15:27:39 +0000100 _ => bail!("Incorrect response type: {response:?}"),
Alice Wang9646fb32023-09-08 10:01:31 +0000101 }
102}
103
Alice Wanga78d3f02023-09-13 12:39:16 +0000104fn assert_array_has_nonzero(v: &[u8]) {
105 assert!(v.iter().any(|&x| x != 0))
106}
107
Alice Wangff5592d2023-09-13 15:27:39 +0000108fn check_processing_generating_certificate_request(
109 vm: &mut ServiceVm,
Alice Wang74eb78b2023-11-09 16:13:10 +0000110 maced_public_key: &[u8],
Alice Wangff5592d2023-09-13 15:27:39 +0000111) -> Result<()> {
112 let params = GenerateCertificateRequestParams {
Alice Wang74eb78b2023-11-09 16:13:10 +0000113 keys_to_sign: vec![maced_public_key.to_vec()],
Alice Wangff5592d2023-09-13 15:27:39 +0000114 challenge: vec![],
115 };
Alice Wang9646fb32023-09-08 10:01:31 +0000116 let request = Request::GenerateCertificateRequest(params);
117
118 let response = vm.process_request(request)?;
119 info!("Received response: {response:?}.");
120
121 match response {
Alice Wangf7c0f942023-09-14 09:33:04 +0000122 Response::GenerateCertificateRequest(csr) => check_csr(csr),
Alice Wangff5592d2023-09-13 15:27:39 +0000123 _ => bail!("Incorrect response type: {response:?}"),
Alice Wang9646fb32023-09-08 10:01:31 +0000124 }
125}
126
Alice Wang20b8ebc2023-11-17 09:54:47 +0000127fn check_attestation_request(
128 vm: &mut ServiceVm,
129 remotely_provisioned_key_pair: &EcdsaP256KeyPair,
Alice Wangd3a96402023-11-24 15:37:39 +0000130 vm_type: VmType,
Alice Wang20b8ebc2023-11-17 09:54:47 +0000131) -> Result<()> {
Alice Wangde6bee52023-11-10 09:58:40 +0000132 /// The following data was generated randomly with urandom.
133 const CHALLENGE: [u8; 16] = [
134 0x7d, 0x86, 0x58, 0x79, 0x3a, 0x09, 0xdf, 0x1c, 0xa5, 0x80, 0x80, 0x15, 0x2b, 0x13, 0x17,
135 0x5c,
136 ];
Alice Wang4ac9c8b2023-12-05 16:23:14 +0000137 let dice_artifacts = fake_client_vm_dice_artifacts()?;
Alice Wangde6bee52023-11-10 09:58:40 +0000138 let attestation_data = generate_attestation_key_and_csr(&CHALLENGE, &dice_artifacts)?;
Alice Wang20b8ebc2023-11-17 09:54:47 +0000139 let cert_chain = fs::read(TEST_CERT_CHAIN_PATH)?;
Alice Wang6a504ef2023-12-21 15:37:55 +0000140 // The certificate chain contains several certificates, but we only need the first one.
141 // Parsing the data with trailing data always fails with a `TrailingData` error.
142 let cert_len: usize = match Certificate::from_der(&cert_chain).unwrap_err().kind() {
143 der::ErrorKind::TrailingData { decoded, .. } => decoded.try_into().unwrap(),
144 e => bail!("Unexpected error: {e}"),
145 };
Alice Wangde6bee52023-11-10 09:58:40 +0000146
Alice Wang20b8ebc2023-11-17 09:54:47 +0000147 // Builds the mock parameters for the client VM attestation.
148 // The `csr` and `remotely_provisioned_key_blob` parameters are extracted from the same
149 // libraries as in production.
150 // The `remotely_provisioned_cert` parameter is an RKP certificate extracted from a test
151 // certificate chain retrieved from RKPD.
Alice Wangde6bee52023-11-10 09:58:40 +0000152 let params = ClientVmAttestationParams {
Alice Wang20b8ebc2023-11-17 09:54:47 +0000153 csr: attestation_data.csr.clone().into_cbor_vec()?,
154 remotely_provisioned_key_blob: remotely_provisioned_key_pair.key_blob.to_vec(),
Alice Wang6a504ef2023-12-21 15:37:55 +0000155 remotely_provisioned_cert: cert_chain[..cert_len].to_vec(),
Alice Wangde6bee52023-11-10 09:58:40 +0000156 };
Alice Wang74eb78b2023-11-09 16:13:10 +0000157 let request = Request::RequestClientVmAttestation(params);
158
159 let response = vm.process_request(request)?;
160 info!("Received response: {response:?}.");
161
162 match response {
Alice Wang20b8ebc2023-11-17 09:54:47 +0000163 Response::RequestClientVmAttestation(certificate) => {
Alice Wangd3a96402023-11-24 15:37:39 +0000164 // The end-to-end test for non-protected VM attestation works because both the service
165 // VM and the client VM use the same fake DICE chain.
166 assert_eq!(vm_type, VmType::NonProtectedVm);
Alice Wang20b8ebc2023-11-17 09:54:47 +0000167 check_certificate_for_client_vm(
168 &certificate,
169 &remotely_provisioned_key_pair.maced_public_key,
170 &attestation_data.csr,
Alice Wang6a504ef2023-12-21 15:37:55 +0000171 &Certificate::from_der(&cert_chain[..cert_len]).unwrap(),
Alice Wang20b8ebc2023-11-17 09:54:47 +0000172 )?;
173 Ok(())
174 }
Alice Wangd3a96402023-11-24 15:37:39 +0000175 Response::Err(RequestProcessingError::InvalidDiceChain) => {
176 // The end-to-end test for protected VM attestation doesn't work because the service VM
177 // compares the fake DICE chain in the CSR with the real DICE chain.
178 // We cannot generate a valid DICE chain with the same payloads up to pvmfw.
179 assert_eq!(vm_type, VmType::ProtectedVm);
180 Ok(())
181 }
Alice Wang74eb78b2023-11-09 16:13:10 +0000182 _ => bail!("Incorrect response type: {response:?}"),
183 }
184}
185
Alice Wang6a504ef2023-12-21 15:37:55 +0000186fn check_vm_components(vm_components: &asn1::SequenceOf<asn1::Any, 4>) -> Result<()> {
Alice Wang1cc13502023-12-05 11:05:34 +0000187 let expected_components = fake_sub_components();
188 assert_eq!(expected_components.len(), vm_components.len());
Alice Wang6a504ef2023-12-21 15:37:55 +0000189 for (i, expected_component) in expected_components.iter().enumerate() {
190 check_vm_component(vm_components.get(i).unwrap(), expected_component)?;
Alice Wang1cc13502023-12-05 11:05:34 +0000191 }
192 Ok(())
193}
194
Alice Wang6a504ef2023-12-21 15:37:55 +0000195fn check_vm_component(vm_component: &asn1::Any, expected_component: &SubComponent) -> Result<()> {
196 let vm_component = vm_component.decode_as::<asn1::SequenceOf<asn1::Any, 4>>().unwrap();
Alice Wang1cc13502023-12-05 11:05:34 +0000197 assert_eq!(4, vm_component.len());
Alice Wang6a504ef2023-12-21 15:37:55 +0000198 let name = vm_component.get(0).unwrap().decode_as::<asn1::Utf8StringRef>().unwrap();
199 assert_eq!(expected_component.name, name.as_ref());
200 let version = vm_component.get(1).unwrap().decode_as::<u64>().unwrap();
201 assert_eq!(expected_component.version, version);
202 let code_hash = vm_component.get(2).unwrap().decode_as::<asn1::OctetString>().unwrap();
203 assert_eq!(expected_component.code_hash, code_hash.as_bytes());
204 let authority_hash = vm_component.get(3).unwrap().decode_as::<asn1::OctetString>().unwrap();
205 assert_eq!(expected_component.authority_hash, authority_hash.as_bytes());
Alice Wang1cc13502023-12-05 11:05:34 +0000206 Ok(())
207}
208
Alice Wang20b8ebc2023-11-17 09:54:47 +0000209fn check_certificate_for_client_vm(
210 certificate: &[u8],
211 maced_public_key: &[u8],
212 csr: &Csr,
Alice Wang6a504ef2023-12-21 15:37:55 +0000213 parent_certificate: &Certificate,
Alice Wang20b8ebc2023-11-17 09:54:47 +0000214) -> Result<()> {
215 let cose_mac = CoseMac0::from_slice(maced_public_key)?;
Alice Wangbe7a4b12023-12-01 11:53:36 +0000216 let authority_public_key =
217 EcKey::from_cose_public_key_slice(&cose_mac.payload.unwrap()).unwrap();
Alice Wang6a504ef2023-12-21 15:37:55 +0000218 let cert = Certificate::from_der(certificate).unwrap();
Alice Wang20b8ebc2023-11-17 09:54:47 +0000219
220 // Checks the certificate signature against the authority public key.
Alice Wang6a504ef2023-12-21 15:37:55 +0000221 const ECDSA_WITH_SHA_256: ObjectIdentifier =
222 ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
223 let expected_algorithm = AlgorithmIdentifier { oid: ECDSA_WITH_SHA_256, parameters: None };
Alice Wang20b8ebc2023-11-17 09:54:47 +0000224 assert_eq!(expected_algorithm, cert.signature_algorithm);
Alice Wang6a504ef2023-12-21 15:37:55 +0000225 let tbs_cert = cert.tbs_certificate;
226 let digest = sha256(&tbs_cert.to_der().unwrap()).unwrap();
Alice Wang20b8ebc2023-11-17 09:54:47 +0000227 authority_public_key
Alice Wang6a504ef2023-12-21 15:37:55 +0000228 .ecdsa_verify(cert.signature.raw_bytes(), &digest)
Alice Wang20b8ebc2023-11-17 09:54:47 +0000229 .expect("Failed to verify the certificate signature with the authority public key");
230
231 // Checks that the certificate's subject public key is equal to the key in the CSR.
232 let cose_sign = CoseSign::from_slice(&csr.signed_csr_payload)?;
233 let csr_payload =
234 cose_sign.payload.as_ref().and_then(|v| CsrPayload::from_cbor_slice(v).ok()).unwrap();
Alice Wangbe7a4b12023-12-01 11:53:36 +0000235 let subject_public_key = EcKey::from_cose_public_key_slice(&csr_payload.public_key).unwrap();
Alice Wang20b8ebc2023-11-17 09:54:47 +0000236 let expected_spki_data =
Alice Wangeb77f7d2023-12-01 09:13:58 +0000237 PKey::try_from(subject_public_key).unwrap().subject_public_key_info().unwrap();
Alice Wang6a504ef2023-12-21 15:37:55 +0000238 let expected_spki = SubjectPublicKeyInfo::from_der(&expected_spki_data).unwrap();
239 assert_eq!(expected_spki, tbs_cert.subject_public_key_info);
Alice Wang20b8ebc2023-11-17 09:54:47 +0000240
241 // Checks the certificate extension.
Alice Wang6a504ef2023-12-21 15:37:55 +0000242 const ATTESTATION_EXTENSION_OID: ObjectIdentifier =
243 ObjectIdentifier::new_unwrap("1.3.6.1.4.1.11129.2.1.29.1");
244 let extensions = tbs_cert.extensions.unwrap();
Alice Wang20b8ebc2023-11-17 09:54:47 +0000245 assert_eq!(1, extensions.len());
246 let extension = &extensions[0];
Alice Wang6a504ef2023-12-21 15:37:55 +0000247 assert_eq!(ATTESTATION_EXTENSION_OID, extension.extn_id);
Alice Wang20b8ebc2023-11-17 09:54:47 +0000248 assert!(!extension.critical);
Alice Wang6a504ef2023-12-21 15:37:55 +0000249 let attestation_ext =
250 asn1::SequenceOf::<asn1::Any, 3>::from_der(extension.extn_value.as_bytes()).unwrap();
Alice Wang1cc13502023-12-05 11:05:34 +0000251 assert_eq!(3, attestation_ext.len());
Alice Wang6a504ef2023-12-21 15:37:55 +0000252 let challenge = attestation_ext.get(0).unwrap().decode_as::<asn1::OctetString>().unwrap();
253 assert_eq!(csr_payload.challenge, challenge.as_bytes());
254 let is_vm_secure = attestation_ext.get(1).unwrap().decode_as::<bool>().unwrap();
Alice Wangd3a96402023-11-24 15:37:39 +0000255 assert!(
256 !is_vm_secure,
257 "The VM shouldn't be secure as the last payload added in the test is in Debug mode"
258 );
Alice Wang6a504ef2023-12-21 15:37:55 +0000259 let vm_components =
260 attestation_ext.get(2).unwrap().decode_as::<asn1::SequenceOf<asn1::Any, 4>>().unwrap();
261 check_vm_components(&vm_components)?;
Alice Wang20b8ebc2023-11-17 09:54:47 +0000262
263 // Checks other fields on the certificate
Alice Wang6a504ef2023-12-21 15:37:55 +0000264 assert_eq!(Version::V3, tbs_cert.version);
265 assert_eq!(parent_certificate.tbs_certificate.validity, tbs_cert.validity);
Alice Wang20b8ebc2023-11-17 09:54:47 +0000266 assert_eq!(
Alice Wang6a504ef2023-12-21 15:37:55 +0000267 Name::from_str("CN=Android Protected Virtual Machine Key").unwrap(),
268 tbs_cert.subject
Alice Wang20b8ebc2023-11-17 09:54:47 +0000269 );
Alice Wang6a504ef2023-12-21 15:37:55 +0000270 assert_eq!(parent_certificate.tbs_certificate.subject, tbs_cert.issuer);
Alice Wang20b8ebc2023-11-17 09:54:47 +0000271
272 Ok(())
273}
274
Alice Wangf7c0f942023-09-14 09:33:04 +0000275/// TODO(b/300625792): Check the CSR with libhwtrust once the CSR is complete.
276fn check_csr(csr: Vec<u8>) -> Result<()> {
277 let mut reader = io::Cursor::new(csr);
278 let csr: Value = ciborium::from_reader(&mut reader)?;
279 match csr {
280 Value::Array(arr) => {
281 assert_eq!(4, arr.len());
282 }
283 _ => bail!("Incorrect CSR format: {csr:?}"),
284 }
285 Ok(())
286}
287
Alice Wange910b902023-09-07 10:35:12 +0000288fn start_service_vm(vm_type: VmType) -> Result<ServiceVm> {
David Brazdil66fc1202022-07-04 21:48:45 +0100289 android_logger::init_once(
290 android_logger::Config::default().with_tag("rialto").with_min_level(log::Level::Debug),
291 );
David Brazdil66fc1202022-07-04 21:48:45 +0100292 // Redirect panic messages to logcat.
293 panic::set_hook(Box::new(|panic_info| {
294 log::error!("{}", panic_info);
295 }));
David Brazdil66fc1202022-07-04 21:48:45 +0100296 // We need to start the thread pool for Binder to work properly, especially link_to_death.
297 ProcessState::start_thread_pool();
Alice Wange910b902023-09-07 10:35:12 +0000298 ServiceVm::start_vm(vm_instance(vm_type)?, vm_type)
Alice Wang17dc76e2023-09-06 09:43:52 +0000299}
300
Alice Wange910b902023-09-07 10:35:12 +0000301fn vm_instance(vm_type: VmType) -> Result<VmInstance> {
Alice Wanga6357692023-09-07 14:59:37 +0000302 match vm_type {
Alice Wang1d9a5872023-09-06 14:32:36 +0000303 VmType::ProtectedVm => {
Alice Wanga6357692023-09-07 14:59:37 +0000304 service_vm_manager::protected_vm_instance(PathBuf::from(INSTANCE_IMG_PATH))
Alice Wang1d9a5872023-09-06 14:32:36 +0000305 }
Alice Wanga6357692023-09-07 14:59:37 +0000306 VmType::NonProtectedVm => nonprotected_vm_instance(),
307 }
308}
309
310fn nonprotected_vm_instance() -> Result<VmInstance> {
311 let rialto = File::open(UNSIGNED_RIALTO_PATH).context("Failed to open Rialto kernel binary")?;
David Brazdil66fc1202022-07-04 21:48:45 +0100312 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Alice Wanga6357692023-09-07 14:59:37 +0000313 name: String::from("Non protected rialto"),
David Brazdil66fc1202022-07-04 21:48:45 +0100314 bootloader: Some(ParcelFileDescriptor::new(rialto)),
Alice Wanga6357692023-09-07 14:59:37 +0000315 protectedVm: false,
David Brazdil66fc1202022-07-04 21:48:45 +0100316 memoryMib: 300,
David Brazdil66fc1202022-07-04 21:48:45 +0100317 platformVersion: "~1.0".to_string(),
Inseob Kim6ef80972023-07-20 17:23:36 +0900318 ..Default::default()
David Brazdil66fc1202022-07-04 21:48:45 +0100319 });
Alice Wanga6357692023-09-07 14:59:37 +0000320 let console = Some(service_vm_manager::android_log_fd()?);
321 let log = Some(service_vm_manager::android_log_fd()?);
322 let virtmgr = vmclient::VirtualizationService::new().context("Failed to spawn VirtMgr")?;
323 let service = virtmgr.connect().context("Failed to connect to VirtMgr")?;
324 info!("Connected to VirtMgr for service VM");
325 VmInstance::create(service.as_ref(), &config, console, /* consoleIn */ None, log, None)
326 .context("Failed to create VM")
David Brazdil66fc1202022-07-04 21:48:45 +0100327}