blob: 2755436b83875664026f71107ff5fd9e6c44050d [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 Wang4ac9c8b2023-12-05 16:23:14 +000034use service_vm_fake_chain::client_vm::fake_client_vm_dice_artifacts;
Alice Wang17dc76e2023-09-06 09:43:52 +000035use service_vm_manager::ServiceVm;
Alice Wang20b8ebc2023-11-17 09:54:47 +000036use std::fs;
David Brazdil66fc1202022-07-04 21:48:45 +010037use std::fs::File;
Alice Wangf7c0f942023-09-14 09:33:04 +000038use std::io;
David Brazdil66fc1202022-07-04 21:48:45 +010039use std::panic;
Alice Wang17dc76e2023-09-06 09:43:52 +000040use std::path::PathBuf;
Alice Wang17dc76e2023-09-06 09:43:52 +000041use vmclient::VmInstance;
Alice Wang20b8ebc2023-11-17 09:54:47 +000042use x509_parser::{
43 certificate::X509Certificate,
44 der_parser::{der::parse_der, oid, oid::Oid},
45 prelude::FromDer,
46 x509::{AlgorithmIdentifier, SubjectPublicKeyInfo, X509Version},
47};
Alice Wang4e082c32023-07-11 07:41:50 +000048
Alice Wang9a8b39f2023-04-12 15:31:48 +000049const UNSIGNED_RIALTO_PATH: &str = "/data/local/tmp/rialto_test/arm64/rialto_unsigned.bin";
50const INSTANCE_IMG_PATH: &str = "/data/local/tmp/rialto_test/arm64/instance.img";
Alice Wang20b8ebc2023-11-17 09:54:47 +000051const TEST_CERT_CHAIN_PATH: &str = "testdata/rkp_cert_chain.der";
David Brazdil66fc1202022-07-04 21:48:45 +010052
Alice Wang9a8b39f2023-04-12 15:31:48 +000053#[test]
Alice Wange910b902023-09-07 10:35:12 +000054fn process_requests_in_protected_vm() -> Result<()> {
Alice Wang9646fb32023-09-08 10:01:31 +000055 check_processing_requests(VmType::ProtectedVm)
Alice Wang9a8b39f2023-04-12 15:31:48 +000056}
57
Alice Wange910b902023-09-07 10:35:12 +000058#[test]
59fn process_requests_in_non_protected_vm() -> Result<()> {
Alice Wang9646fb32023-09-08 10:01:31 +000060 check_processing_requests(VmType::NonProtectedVm)
61}
62
63fn check_processing_requests(vm_type: VmType) -> Result<()> {
64 let mut vm = start_service_vm(vm_type)?;
Alice Wange910b902023-09-07 10:35:12 +000065
66 check_processing_reverse_request(&mut vm)?;
Alice Wang74eb78b2023-11-09 16:13:10 +000067 let key_pair = check_processing_generating_key_pair_request(&mut vm)?;
68 check_processing_generating_certificate_request(&mut vm, &key_pair.maced_public_key)?;
Alice Wangd3a96402023-11-24 15:37:39 +000069 check_attestation_request(&mut vm, &key_pair, vm_type)?;
Alice Wange910b902023-09-07 10:35:12 +000070 Ok(())
71}
72
73fn check_processing_reverse_request(vm: &mut ServiceVm) -> Result<()> {
Alice Wang0486e252023-10-06 14:30:49 +000074 let message = "abc".repeat(500);
Alice Wange910b902023-09-07 10:35:12 +000075 let request = Request::Reverse(message.as_bytes().to_vec());
76
Alice Wangfbdc85b2023-09-07 12:56:46 +000077 let response = vm.process_request(request)?;
78 info!("Received response: {response:?}.");
Alice Wange910b902023-09-07 10:35:12 +000079
80 let expected_response: Vec<u8> = message.as_bytes().iter().rev().cloned().collect();
81 assert_eq!(Response::Reverse(expected_response), response);
82 Ok(())
83}
84
Alice Wang74eb78b2023-11-09 16:13:10 +000085fn check_processing_generating_key_pair_request(vm: &mut ServiceVm) -> Result<EcdsaP256KeyPair> {
Alice Wang9646fb32023-09-08 10:01:31 +000086 let request = Request::GenerateEcdsaP256KeyPair;
87
88 let response = vm.process_request(request)?;
89 info!("Received response: {response:?}.");
90
91 match response {
Alice Wang74eb78b2023-11-09 16:13:10 +000092 Response::GenerateEcdsaP256KeyPair(key_pair) => {
93 assert_array_has_nonzero(&key_pair.maced_public_key);
94 assert_array_has_nonzero(&key_pair.key_blob);
95 Ok(key_pair)
Alice Wanga78d3f02023-09-13 12:39:16 +000096 }
Alice Wangff5592d2023-09-13 15:27:39 +000097 _ => bail!("Incorrect response type: {response:?}"),
Alice Wang9646fb32023-09-08 10:01:31 +000098 }
99}
100
Alice Wanga78d3f02023-09-13 12:39:16 +0000101fn assert_array_has_nonzero(v: &[u8]) {
102 assert!(v.iter().any(|&x| x != 0))
103}
104
Alice Wangff5592d2023-09-13 15:27:39 +0000105fn check_processing_generating_certificate_request(
106 vm: &mut ServiceVm,
Alice Wang74eb78b2023-11-09 16:13:10 +0000107 maced_public_key: &[u8],
Alice Wangff5592d2023-09-13 15:27:39 +0000108) -> Result<()> {
109 let params = GenerateCertificateRequestParams {
Alice Wang74eb78b2023-11-09 16:13:10 +0000110 keys_to_sign: vec![maced_public_key.to_vec()],
Alice Wangff5592d2023-09-13 15:27:39 +0000111 challenge: vec![],
112 };
Alice Wang9646fb32023-09-08 10:01:31 +0000113 let request = Request::GenerateCertificateRequest(params);
114
115 let response = vm.process_request(request)?;
116 info!("Received response: {response:?}.");
117
118 match response {
Alice Wangf7c0f942023-09-14 09:33:04 +0000119 Response::GenerateCertificateRequest(csr) => check_csr(csr),
Alice Wangff5592d2023-09-13 15:27:39 +0000120 _ => bail!("Incorrect response type: {response:?}"),
Alice Wang9646fb32023-09-08 10:01:31 +0000121 }
122}
123
Alice Wang20b8ebc2023-11-17 09:54:47 +0000124fn check_attestation_request(
125 vm: &mut ServiceVm,
126 remotely_provisioned_key_pair: &EcdsaP256KeyPair,
Alice Wangd3a96402023-11-24 15:37:39 +0000127 vm_type: VmType,
Alice Wang20b8ebc2023-11-17 09:54:47 +0000128) -> Result<()> {
Alice Wangde6bee52023-11-10 09:58:40 +0000129 /// The following data was generated randomly with urandom.
130 const CHALLENGE: [u8; 16] = [
131 0x7d, 0x86, 0x58, 0x79, 0x3a, 0x09, 0xdf, 0x1c, 0xa5, 0x80, 0x80, 0x15, 0x2b, 0x13, 0x17,
132 0x5c,
133 ];
Alice Wang4ac9c8b2023-12-05 16:23:14 +0000134 let dice_artifacts = fake_client_vm_dice_artifacts()?;
Alice Wangde6bee52023-11-10 09:58:40 +0000135 let attestation_data = generate_attestation_key_and_csr(&CHALLENGE, &dice_artifacts)?;
Alice Wang20b8ebc2023-11-17 09:54:47 +0000136 let cert_chain = fs::read(TEST_CERT_CHAIN_PATH)?;
137 let (remaining, cert) = X509Certificate::from_der(&cert_chain)?;
Alice Wangde6bee52023-11-10 09:58:40 +0000138
Alice Wang20b8ebc2023-11-17 09:54:47 +0000139 // Builds the mock parameters for the client VM attestation.
140 // The `csr` and `remotely_provisioned_key_blob` parameters are extracted from the same
141 // libraries as in production.
142 // The `remotely_provisioned_cert` parameter is an RKP certificate extracted from a test
143 // certificate chain retrieved from RKPD.
Alice Wangde6bee52023-11-10 09:58:40 +0000144 let params = ClientVmAttestationParams {
Alice Wang20b8ebc2023-11-17 09:54:47 +0000145 csr: attestation_data.csr.clone().into_cbor_vec()?,
146 remotely_provisioned_key_blob: remotely_provisioned_key_pair.key_blob.to_vec(),
147 remotely_provisioned_cert: cert_chain[..(cert_chain.len() - remaining.len())].to_vec(),
Alice Wangde6bee52023-11-10 09:58:40 +0000148 };
Alice Wang74eb78b2023-11-09 16:13:10 +0000149 let request = Request::RequestClientVmAttestation(params);
150
151 let response = vm.process_request(request)?;
152 info!("Received response: {response:?}.");
153
154 match response {
Alice Wang20b8ebc2023-11-17 09:54:47 +0000155 Response::RequestClientVmAttestation(certificate) => {
Alice Wangd3a96402023-11-24 15:37:39 +0000156 // The end-to-end test for non-protected VM attestation works because both the service
157 // VM and the client VM use the same fake DICE chain.
158 assert_eq!(vm_type, VmType::NonProtectedVm);
Alice Wang20b8ebc2023-11-17 09:54:47 +0000159 check_certificate_for_client_vm(
160 &certificate,
161 &remotely_provisioned_key_pair.maced_public_key,
162 &attestation_data.csr,
163 &cert,
164 )?;
165 Ok(())
166 }
Alice Wangd3a96402023-11-24 15:37:39 +0000167 Response::Err(RequestProcessingError::InvalidDiceChain) => {
168 // The end-to-end test for protected VM attestation doesn't work because the service VM
169 // compares the fake DICE chain in the CSR with the real DICE chain.
170 // We cannot generate a valid DICE chain with the same payloads up to pvmfw.
171 assert_eq!(vm_type, VmType::ProtectedVm);
172 Ok(())
173 }
Alice Wang74eb78b2023-11-09 16:13:10 +0000174 _ => bail!("Incorrect response type: {response:?}"),
175 }
176}
177
Alice Wang20b8ebc2023-11-17 09:54:47 +0000178fn check_certificate_for_client_vm(
179 certificate: &[u8],
180 maced_public_key: &[u8],
181 csr: &Csr,
182 parent_certificate: &X509Certificate,
183) -> Result<()> {
184 let cose_mac = CoseMac0::from_slice(maced_public_key)?;
Alice Wangbe7a4b12023-12-01 11:53:36 +0000185 let authority_public_key =
186 EcKey::from_cose_public_key_slice(&cose_mac.payload.unwrap()).unwrap();
Alice Wang20b8ebc2023-11-17 09:54:47 +0000187 let (remaining, cert) = X509Certificate::from_der(certificate)?;
188 assert!(remaining.is_empty());
189
190 // Checks the certificate signature against the authority public key.
191 const ECDSA_WITH_SHA_256: Oid<'static> = oid!(1.2.840 .10045 .4 .3 .2);
192 let expected_algorithm =
193 AlgorithmIdentifier { algorithm: ECDSA_WITH_SHA_256, parameters: None };
194 assert_eq!(expected_algorithm, cert.signature_algorithm);
195 let digest = sha256(cert.tbs_certificate.as_ref()).unwrap();
196 authority_public_key
197 .ecdsa_verify(cert.signature_value.as_ref(), &digest)
198 .expect("Failed to verify the certificate signature with the authority public key");
199
200 // Checks that the certificate's subject public key is equal to the key in the CSR.
201 let cose_sign = CoseSign::from_slice(&csr.signed_csr_payload)?;
202 let csr_payload =
203 cose_sign.payload.as_ref().and_then(|v| CsrPayload::from_cbor_slice(v).ok()).unwrap();
Alice Wangbe7a4b12023-12-01 11:53:36 +0000204 let subject_public_key = EcKey::from_cose_public_key_slice(&csr_payload.public_key).unwrap();
Alice Wang20b8ebc2023-11-17 09:54:47 +0000205 let expected_spki_data =
Alice Wangeb77f7d2023-12-01 09:13:58 +0000206 PKey::try_from(subject_public_key).unwrap().subject_public_key_info().unwrap();
Alice Wang20b8ebc2023-11-17 09:54:47 +0000207 let (remaining, expected_spki) = SubjectPublicKeyInfo::from_der(&expected_spki_data)?;
208 assert!(remaining.is_empty());
209 assert_eq!(&expected_spki, cert.public_key());
210
211 // Checks the certificate extension.
212 const ATTESTATION_EXTENSION_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .11129 .2 .1 .29 .1);
213 let extensions = cert.extensions();
214 assert_eq!(1, extensions.len());
215 let extension = &extensions[0];
216 assert_eq!(ATTESTATION_EXTENSION_OID, extension.oid);
217 assert!(!extension.critical);
218 let (remaining, extension) = parse_der(extension.value)?;
219 assert!(remaining.is_empty());
220 let attestation_ext = extension.as_sequence()?;
Alice Wangd3a96402023-11-24 15:37:39 +0000221 assert_eq!(2, attestation_ext.len());
Alice Wang20b8ebc2023-11-17 09:54:47 +0000222 assert_eq!(csr_payload.challenge, attestation_ext[0].as_slice()?);
Alice Wangd3a96402023-11-24 15:37:39 +0000223 let is_vm_secure = attestation_ext[1].as_bool()?;
224 assert!(
225 !is_vm_secure,
226 "The VM shouldn't be secure as the last payload added in the test is in Debug mode"
227 );
Alice Wang20b8ebc2023-11-17 09:54:47 +0000228
229 // Checks other fields on the certificate
230 assert_eq!(X509Version::V3, cert.version());
231 assert_eq!(parent_certificate.validity(), cert.validity());
232 assert_eq!(
233 String::from("CN=Android Protected Virtual Machine Key"),
234 cert.subject().to_string()
235 );
236 assert_eq!(parent_certificate.subject(), cert.issuer());
237
238 Ok(())
239}
240
Alice Wangf7c0f942023-09-14 09:33:04 +0000241/// TODO(b/300625792): Check the CSR with libhwtrust once the CSR is complete.
242fn check_csr(csr: Vec<u8>) -> Result<()> {
243 let mut reader = io::Cursor::new(csr);
244 let csr: Value = ciborium::from_reader(&mut reader)?;
245 match csr {
246 Value::Array(arr) => {
247 assert_eq!(4, arr.len());
248 }
249 _ => bail!("Incorrect CSR format: {csr:?}"),
250 }
251 Ok(())
252}
253
Alice Wange910b902023-09-07 10:35:12 +0000254fn start_service_vm(vm_type: VmType) -> Result<ServiceVm> {
David Brazdil66fc1202022-07-04 21:48:45 +0100255 android_logger::init_once(
256 android_logger::Config::default().with_tag("rialto").with_min_level(log::Level::Debug),
257 );
David Brazdil66fc1202022-07-04 21:48:45 +0100258 // Redirect panic messages to logcat.
259 panic::set_hook(Box::new(|panic_info| {
260 log::error!("{}", panic_info);
261 }));
David Brazdil66fc1202022-07-04 21:48:45 +0100262 // We need to start the thread pool for Binder to work properly, especially link_to_death.
263 ProcessState::start_thread_pool();
Alice Wange910b902023-09-07 10:35:12 +0000264 ServiceVm::start_vm(vm_instance(vm_type)?, vm_type)
Alice Wang17dc76e2023-09-06 09:43:52 +0000265}
266
Alice Wange910b902023-09-07 10:35:12 +0000267fn vm_instance(vm_type: VmType) -> Result<VmInstance> {
Alice Wanga6357692023-09-07 14:59:37 +0000268 match vm_type {
Alice Wang1d9a5872023-09-06 14:32:36 +0000269 VmType::ProtectedVm => {
Alice Wanga6357692023-09-07 14:59:37 +0000270 service_vm_manager::protected_vm_instance(PathBuf::from(INSTANCE_IMG_PATH))
Alice Wang1d9a5872023-09-06 14:32:36 +0000271 }
Alice Wanga6357692023-09-07 14:59:37 +0000272 VmType::NonProtectedVm => nonprotected_vm_instance(),
273 }
274}
275
276fn nonprotected_vm_instance() -> Result<VmInstance> {
277 let rialto = File::open(UNSIGNED_RIALTO_PATH).context("Failed to open Rialto kernel binary")?;
David Brazdil66fc1202022-07-04 21:48:45 +0100278 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Alice Wanga6357692023-09-07 14:59:37 +0000279 name: String::from("Non protected rialto"),
David Brazdil66fc1202022-07-04 21:48:45 +0100280 bootloader: Some(ParcelFileDescriptor::new(rialto)),
Alice Wanga6357692023-09-07 14:59:37 +0000281 protectedVm: false,
David Brazdil66fc1202022-07-04 21:48:45 +0100282 memoryMib: 300,
David Brazdil66fc1202022-07-04 21:48:45 +0100283 platformVersion: "~1.0".to_string(),
Inseob Kim6ef80972023-07-20 17:23:36 +0900284 ..Default::default()
David Brazdil66fc1202022-07-04 21:48:45 +0100285 });
Alice Wanga6357692023-09-07 14:59:37 +0000286 let console = Some(service_vm_manager::android_log_fd()?);
287 let log = Some(service_vm_manager::android_log_fd()?);
288 let virtmgr = vmclient::VirtualizationService::new().context("Failed to spawn VirtMgr")?;
289 let service = virtmgr.connect().context("Failed to connect to VirtMgr")?;
290 info!("Connected to VirtMgr for service VM");
291 VmInstance::create(service.as_ref(), &config, console, /* consoleIn */ None, log, None)
292 .context("Failed to create VM")
David Brazdil66fc1202022-07-04 21:48:45 +0100293}