blob: 85c3efe6336866233258ac7297498ba7243e76fb [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 Wang20b8ebc2023-11-17 09:54:47 +000025use bssl_avf::{sha256, EcKey, EvpPKey};
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,
32 Request, Response, VmType,
Alice Wang9646fb32023-09-08 10:01:31 +000033};
Alice Wang17dc76e2023-09-06 09:43:52 +000034use service_vm_manager::ServiceVm;
Alice Wang20b8ebc2023-11-17 09:54:47 +000035use std::fs;
David Brazdil66fc1202022-07-04 21:48:45 +010036use std::fs::File;
Alice Wangf7c0f942023-09-14 09:33:04 +000037use std::io;
David Brazdil66fc1202022-07-04 21:48:45 +010038use std::panic;
Alice Wang17dc76e2023-09-06 09:43:52 +000039use std::path::PathBuf;
Alice Wang17dc76e2023-09-06 09:43:52 +000040use vmclient::VmInstance;
Alice Wang20b8ebc2023-11-17 09:54:47 +000041use x509_parser::{
42 certificate::X509Certificate,
43 der_parser::{der::parse_der, oid, oid::Oid},
44 prelude::FromDer,
45 x509::{AlgorithmIdentifier, SubjectPublicKeyInfo, X509Version},
46};
Alice Wang4e082c32023-07-11 07:41:50 +000047
Alice Wang9a8b39f2023-04-12 15:31:48 +000048const UNSIGNED_RIALTO_PATH: &str = "/data/local/tmp/rialto_test/arm64/rialto_unsigned.bin";
49const INSTANCE_IMG_PATH: &str = "/data/local/tmp/rialto_test/arm64/instance.img";
Alice Wang20b8ebc2023-11-17 09:54:47 +000050const TEST_CERT_CHAIN_PATH: &str = "testdata/rkp_cert_chain.der";
David Brazdil66fc1202022-07-04 21:48:45 +010051
Alice Wang9a8b39f2023-04-12 15:31:48 +000052#[test]
Alice Wange910b902023-09-07 10:35:12 +000053fn process_requests_in_protected_vm() -> Result<()> {
Alice Wang9646fb32023-09-08 10:01:31 +000054 check_processing_requests(VmType::ProtectedVm)
Alice Wang9a8b39f2023-04-12 15:31:48 +000055}
56
Alice Wange910b902023-09-07 10:35:12 +000057#[test]
58fn process_requests_in_non_protected_vm() -> Result<()> {
Alice Wang9646fb32023-09-08 10:01:31 +000059 check_processing_requests(VmType::NonProtectedVm)
60}
61
62fn check_processing_requests(vm_type: VmType) -> Result<()> {
63 let mut vm = start_service_vm(vm_type)?;
Alice Wange910b902023-09-07 10:35:12 +000064
65 check_processing_reverse_request(&mut vm)?;
Alice Wang74eb78b2023-11-09 16:13:10 +000066 let key_pair = check_processing_generating_key_pair_request(&mut vm)?;
67 check_processing_generating_certificate_request(&mut vm, &key_pair.maced_public_key)?;
Alice Wang20b8ebc2023-11-17 09:54:47 +000068 check_attestation_request(&mut vm, &key_pair)?;
Alice Wange910b902023-09-07 10:35:12 +000069 Ok(())
70}
71
72fn check_processing_reverse_request(vm: &mut ServiceVm) -> Result<()> {
Alice Wang0486e252023-10-06 14:30:49 +000073 let message = "abc".repeat(500);
Alice Wange910b902023-09-07 10:35:12 +000074 let request = Request::Reverse(message.as_bytes().to_vec());
75
Alice Wangfbdc85b2023-09-07 12:56:46 +000076 let response = vm.process_request(request)?;
77 info!("Received response: {response:?}.");
Alice Wange910b902023-09-07 10:35:12 +000078
79 let expected_response: Vec<u8> = message.as_bytes().iter().rev().cloned().collect();
80 assert_eq!(Response::Reverse(expected_response), response);
81 Ok(())
82}
83
Alice Wang74eb78b2023-11-09 16:13:10 +000084fn check_processing_generating_key_pair_request(vm: &mut ServiceVm) -> Result<EcdsaP256KeyPair> {
Alice Wang9646fb32023-09-08 10:01:31 +000085 let request = Request::GenerateEcdsaP256KeyPair;
86
87 let response = vm.process_request(request)?;
88 info!("Received response: {response:?}.");
89
90 match response {
Alice Wang74eb78b2023-11-09 16:13:10 +000091 Response::GenerateEcdsaP256KeyPair(key_pair) => {
92 assert_array_has_nonzero(&key_pair.maced_public_key);
93 assert_array_has_nonzero(&key_pair.key_blob);
94 Ok(key_pair)
Alice Wanga78d3f02023-09-13 12:39:16 +000095 }
Alice Wangff5592d2023-09-13 15:27:39 +000096 _ => bail!("Incorrect response type: {response:?}"),
Alice Wang9646fb32023-09-08 10:01:31 +000097 }
98}
99
Alice Wanga78d3f02023-09-13 12:39:16 +0000100fn assert_array_has_nonzero(v: &[u8]) {
101 assert!(v.iter().any(|&x| x != 0))
102}
103
Alice Wangff5592d2023-09-13 15:27:39 +0000104fn check_processing_generating_certificate_request(
105 vm: &mut ServiceVm,
Alice Wang74eb78b2023-11-09 16:13:10 +0000106 maced_public_key: &[u8],
Alice Wangff5592d2023-09-13 15:27:39 +0000107) -> Result<()> {
108 let params = GenerateCertificateRequestParams {
Alice Wang74eb78b2023-11-09 16:13:10 +0000109 keys_to_sign: vec![maced_public_key.to_vec()],
Alice Wangff5592d2023-09-13 15:27:39 +0000110 challenge: vec![],
111 };
Alice Wang9646fb32023-09-08 10:01:31 +0000112 let request = Request::GenerateCertificateRequest(params);
113
114 let response = vm.process_request(request)?;
115 info!("Received response: {response:?}.");
116
117 match response {
Alice Wangf7c0f942023-09-14 09:33:04 +0000118 Response::GenerateCertificateRequest(csr) => check_csr(csr),
Alice Wangff5592d2023-09-13 15:27:39 +0000119 _ => bail!("Incorrect response type: {response:?}"),
Alice Wang9646fb32023-09-08 10:01:31 +0000120 }
121}
122
Alice Wang20b8ebc2023-11-17 09:54:47 +0000123fn check_attestation_request(
124 vm: &mut ServiceVm,
125 remotely_provisioned_key_pair: &EcdsaP256KeyPair,
126) -> Result<()> {
Alice Wangde6bee52023-11-10 09:58:40 +0000127 /// The following data was generated randomly with urandom.
128 const CHALLENGE: [u8; 16] = [
129 0x7d, 0x86, 0x58, 0x79, 0x3a, 0x09, 0xdf, 0x1c, 0xa5, 0x80, 0x80, 0x15, 0x2b, 0x13, 0x17,
130 0x5c,
131 ];
132 let dice_artifacts = diced_sample_inputs::make_sample_bcc_and_cdis()?;
133 let attestation_data = generate_attestation_key_and_csr(&CHALLENGE, &dice_artifacts)?;
Alice Wang20b8ebc2023-11-17 09:54:47 +0000134 let cert_chain = fs::read(TEST_CERT_CHAIN_PATH)?;
135 let (remaining, cert) = X509Certificate::from_der(&cert_chain)?;
Alice Wangde6bee52023-11-10 09:58:40 +0000136
Alice Wang20b8ebc2023-11-17 09:54:47 +0000137 // Builds the mock parameters for the client VM attestation.
138 // The `csr` and `remotely_provisioned_key_blob` parameters are extracted from the same
139 // libraries as in production.
140 // The `remotely_provisioned_cert` parameter is an RKP certificate extracted from a test
141 // certificate chain retrieved from RKPD.
Alice Wangde6bee52023-11-10 09:58:40 +0000142 let params = ClientVmAttestationParams {
Alice Wang20b8ebc2023-11-17 09:54:47 +0000143 csr: attestation_data.csr.clone().into_cbor_vec()?,
144 remotely_provisioned_key_blob: remotely_provisioned_key_pair.key_blob.to_vec(),
145 remotely_provisioned_cert: cert_chain[..(cert_chain.len() - remaining.len())].to_vec(),
Alice Wangde6bee52023-11-10 09:58:40 +0000146 };
Alice Wang74eb78b2023-11-09 16:13:10 +0000147 let request = Request::RequestClientVmAttestation(params);
148
149 let response = vm.process_request(request)?;
150 info!("Received response: {response:?}.");
151
152 match response {
Alice Wang20b8ebc2023-11-17 09:54:47 +0000153 Response::RequestClientVmAttestation(certificate) => {
154 check_certificate_for_client_vm(
155 &certificate,
156 &remotely_provisioned_key_pair.maced_public_key,
157 &attestation_data.csr,
158 &cert,
159 )?;
160 Ok(())
161 }
Alice Wang74eb78b2023-11-09 16:13:10 +0000162 _ => bail!("Incorrect response type: {response:?}"),
163 }
164}
165
Alice Wang20b8ebc2023-11-17 09:54:47 +0000166fn check_certificate_for_client_vm(
167 certificate: &[u8],
168 maced_public_key: &[u8],
169 csr: &Csr,
170 parent_certificate: &X509Certificate,
171) -> Result<()> {
172 let cose_mac = CoseMac0::from_slice(maced_public_key)?;
173 let authority_public_key = EcKey::from_cose_public_key(&cose_mac.payload.unwrap()).unwrap();
174 let (remaining, cert) = X509Certificate::from_der(certificate)?;
175 assert!(remaining.is_empty());
176
177 // Checks the certificate signature against the authority public key.
178 const ECDSA_WITH_SHA_256: Oid<'static> = oid!(1.2.840 .10045 .4 .3 .2);
179 let expected_algorithm =
180 AlgorithmIdentifier { algorithm: ECDSA_WITH_SHA_256, parameters: None };
181 assert_eq!(expected_algorithm, cert.signature_algorithm);
182 let digest = sha256(cert.tbs_certificate.as_ref()).unwrap();
183 authority_public_key
184 .ecdsa_verify(cert.signature_value.as_ref(), &digest)
185 .expect("Failed to verify the certificate signature with the authority public key");
186
187 // Checks that the certificate's subject public key is equal to the key in the CSR.
188 let cose_sign = CoseSign::from_slice(&csr.signed_csr_payload)?;
189 let csr_payload =
190 cose_sign.payload.as_ref().and_then(|v| CsrPayload::from_cbor_slice(v).ok()).unwrap();
191 let subject_public_key = EcKey::from_cose_public_key(&csr_payload.public_key).unwrap();
192 let expected_spki_data =
193 EvpPKey::try_from(subject_public_key).unwrap().subject_public_key_info().unwrap();
194 let (remaining, expected_spki) = SubjectPublicKeyInfo::from_der(&expected_spki_data)?;
195 assert!(remaining.is_empty());
196 assert_eq!(&expected_spki, cert.public_key());
197
198 // Checks the certificate extension.
199 const ATTESTATION_EXTENSION_OID: Oid<'static> = oid!(1.3.6 .1 .4 .1 .11129 .2 .1 .29 .1);
200 let extensions = cert.extensions();
201 assert_eq!(1, extensions.len());
202 let extension = &extensions[0];
203 assert_eq!(ATTESTATION_EXTENSION_OID, extension.oid);
204 assert!(!extension.critical);
205 let (remaining, extension) = parse_der(extension.value)?;
206 assert!(remaining.is_empty());
207 let attestation_ext = extension.as_sequence()?;
208 assert_eq!(1, attestation_ext.len());
209 assert_eq!(csr_payload.challenge, attestation_ext[0].as_slice()?);
210
211 // Checks other fields on the certificate
212 assert_eq!(X509Version::V3, cert.version());
213 assert_eq!(parent_certificate.validity(), cert.validity());
214 assert_eq!(
215 String::from("CN=Android Protected Virtual Machine Key"),
216 cert.subject().to_string()
217 );
218 assert_eq!(parent_certificate.subject(), cert.issuer());
219
220 Ok(())
221}
222
Alice Wangf7c0f942023-09-14 09:33:04 +0000223/// TODO(b/300625792): Check the CSR with libhwtrust once the CSR is complete.
224fn check_csr(csr: Vec<u8>) -> Result<()> {
225 let mut reader = io::Cursor::new(csr);
226 let csr: Value = ciborium::from_reader(&mut reader)?;
227 match csr {
228 Value::Array(arr) => {
229 assert_eq!(4, arr.len());
230 }
231 _ => bail!("Incorrect CSR format: {csr:?}"),
232 }
233 Ok(())
234}
235
Alice Wange910b902023-09-07 10:35:12 +0000236fn start_service_vm(vm_type: VmType) -> Result<ServiceVm> {
David Brazdil66fc1202022-07-04 21:48:45 +0100237 android_logger::init_once(
238 android_logger::Config::default().with_tag("rialto").with_min_level(log::Level::Debug),
239 );
David Brazdil66fc1202022-07-04 21:48:45 +0100240 // Redirect panic messages to logcat.
241 panic::set_hook(Box::new(|panic_info| {
242 log::error!("{}", panic_info);
243 }));
David Brazdil66fc1202022-07-04 21:48:45 +0100244 // We need to start the thread pool for Binder to work properly, especially link_to_death.
245 ProcessState::start_thread_pool();
Alice Wange910b902023-09-07 10:35:12 +0000246 ServiceVm::start_vm(vm_instance(vm_type)?, vm_type)
Alice Wang17dc76e2023-09-06 09:43:52 +0000247}
248
Alice Wange910b902023-09-07 10:35:12 +0000249fn vm_instance(vm_type: VmType) -> Result<VmInstance> {
Alice Wanga6357692023-09-07 14:59:37 +0000250 match vm_type {
Alice Wang1d9a5872023-09-06 14:32:36 +0000251 VmType::ProtectedVm => {
Alice Wanga6357692023-09-07 14:59:37 +0000252 service_vm_manager::protected_vm_instance(PathBuf::from(INSTANCE_IMG_PATH))
Alice Wang1d9a5872023-09-06 14:32:36 +0000253 }
Alice Wanga6357692023-09-07 14:59:37 +0000254 VmType::NonProtectedVm => nonprotected_vm_instance(),
255 }
256}
257
258fn nonprotected_vm_instance() -> Result<VmInstance> {
259 let rialto = File::open(UNSIGNED_RIALTO_PATH).context("Failed to open Rialto kernel binary")?;
David Brazdil66fc1202022-07-04 21:48:45 +0100260 let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig {
Alice Wanga6357692023-09-07 14:59:37 +0000261 name: String::from("Non protected rialto"),
David Brazdil66fc1202022-07-04 21:48:45 +0100262 bootloader: Some(ParcelFileDescriptor::new(rialto)),
Alice Wanga6357692023-09-07 14:59:37 +0000263 protectedVm: false,
David Brazdil66fc1202022-07-04 21:48:45 +0100264 memoryMib: 300,
David Brazdil66fc1202022-07-04 21:48:45 +0100265 platformVersion: "~1.0".to_string(),
Inseob Kim6ef80972023-07-20 17:23:36 +0900266 ..Default::default()
David Brazdil66fc1202022-07-04 21:48:45 +0100267 });
Alice Wanga6357692023-09-07 14:59:37 +0000268 let console = Some(service_vm_manager::android_log_fd()?);
269 let log = Some(service_vm_manager::android_log_fd()?);
270 let virtmgr = vmclient::VirtualizationService::new().context("Failed to spawn VirtMgr")?;
271 let service = virtmgr.connect().context("Failed to connect to VirtMgr")?;
272 info!("Connected to VirtMgr for service VM");
273 VmInstance::create(service.as_ref(), &config, console, /* consoleIn */ None, log, None)
274 .context("Failed to create VM")
David Brazdil66fc1202022-07-04 21:48:45 +0100275}