blob: 63aefb888ef33b57aee8cf6e4c1375194bd6d797 [file] [log] [blame]
Alan Stokes6b2d0a82021-09-29 11:30:39 +01001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! Responsible for validating and starting an existing instance of the CompOS VM, or creating and
18//! starting a new instance if necessary.
19
20use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
21 IVirtualizationService::IVirtualizationService, PartitionType::PartitionType,
22};
23use anyhow::{bail, Context, Result};
24use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService;
25use compos_aidl_interface::binder::{ParcelFileDescriptor, Strong};
26use compos_common::compos_client::VmInstance;
27use compos_common::{
28 COMPOS_DATA_ROOT, INSTANCE_IMAGE_FILE, PRIVATE_KEY_BLOB_FILE, PUBLIC_KEY_FILE,
29};
30use log::{info, warn};
Victor Hsieh18775b12021-10-12 17:42:48 -070031use std::env;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010032use std::fs;
33use std::path::{Path, PathBuf};
34
35pub struct CompOsInstance {
36 #[allow(dead_code)] // Keeps VirtualizationService & the VM alive
37 vm_instance: VmInstance,
38 service: Strong<dyn ICompOsService>,
39}
40
41impl CompOsInstance {
42 pub fn get_service(&self) -> Strong<dyn ICompOsService> {
43 self.service.clone()
44 }
45}
46
47pub struct InstanceStarter {
48 instance_name: String,
49 instance_root: PathBuf,
50 instance_image: PathBuf,
51 key_blob: PathBuf,
52 public_key: PathBuf,
53}
54
55impl InstanceStarter {
56 pub fn new(instance_name: &str) -> Self {
57 let instance_root = Path::new(COMPOS_DATA_ROOT).join(instance_name);
58 let instant_root_path = instance_root.as_path();
59 let instance_image = instant_root_path.join(INSTANCE_IMAGE_FILE);
60 let key_blob = instant_root_path.join(PRIVATE_KEY_BLOB_FILE);
61 let public_key = instant_root_path.join(PUBLIC_KEY_FILE);
62 Self {
63 instance_name: instance_name.to_owned(),
64 instance_root,
65 instance_image,
66 key_blob,
67 public_key,
68 }
69 }
70
71 pub fn create_or_start_instance(
72 &self,
73 service: &dyn IVirtualizationService,
74 ) -> Result<CompOsInstance> {
75 let compos_instance = self.start_existing_instance();
76 match compos_instance {
77 Ok(_) => return compos_instance,
Alan Stokes14f07392021-09-27 14:03:31 +010078 Err(e) => warn!("Failed to start: {}", e),
Alan Stokes6b2d0a82021-09-29 11:30:39 +010079 }
80
81 self.start_new_instance(service)
82 }
83
84 fn start_existing_instance(&self) -> Result<CompOsInstance> {
85 // No point even trying if the files we need aren't there.
86 self.check_files_exist()?;
87
Alan Stokes14f07392021-09-27 14:03:31 +010088 info!("Starting {} CompOs instance", self.instance_name);
89
Alan Stokes6b2d0a82021-09-29 11:30:39 +010090 let key_blob = fs::read(&self.key_blob).context("Reading private key blob")?;
91 let public_key = fs::read(&self.public_key).context("Reading public key")?;
92
Alan Stokes16e027f2021-10-04 17:57:31 +010093 let compos_instance = self.start_vm()?;
94 let service = &compos_instance.service;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010095
96 if !service.verifySigningKey(&key_blob, &public_key).context("Verifying key pair")? {
97 bail!("Key pair invalid");
98 }
99
100 // If we get this far then the instance image is valid in the current context (e.g. the
101 // current set of APEXes) and the key blob can be successfully decrypted by the VM. So the
102 // files have not been tampered with and we're good to go.
103
Victor Hsieh18775b12021-10-12 17:42:48 -0700104 Self::initialize_service(service, &key_blob)?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100105
Alan Stokes16e027f2021-10-04 17:57:31 +0100106 Ok(compos_instance)
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100107 }
108
109 fn start_new_instance(
110 &self,
111 virtualization_service: &dyn IVirtualizationService,
112 ) -> Result<CompOsInstance> {
113 info!("Creating {} CompOs instance", self.instance_name);
114
115 // Ignore failure here - the directory may already exist.
116 let _ = fs::create_dir(&self.instance_root);
117
118 self.create_instance_image(virtualization_service)?;
119
Alan Stokes16e027f2021-10-04 17:57:31 +0100120 let compos_instance = self.start_vm()?;
121 let service = &compos_instance.service;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100122
123 let key_data = service.generateSigningKey().context("Generating signing key")?;
124 fs::write(&self.key_blob, &key_data.keyBlob).context("Writing key blob")?;
Alan Stokes14f07392021-09-27 14:03:31 +0100125
126 let key_result = composd_native::extract_rsa_public_key(&key_data.certificate);
127 let rsa_public_key = key_result.key;
128 if rsa_public_key.is_empty() {
129 bail!("Failed to extract public key from certificate: {}", key_result.error);
130 }
131 fs::write(&self.public_key, &rsa_public_key).context("Writing public key")?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100132
Victor Hsieh18775b12021-10-12 17:42:48 -0700133 // Unlike when starting an existing instance, we don't need to verify the key, since we
134 // just generated it and have it in memory.
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100135
Victor Hsieh18775b12021-10-12 17:42:48 -0700136 Self::initialize_service(service, &key_data.keyBlob)?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100137
Alan Stokes16e027f2021-10-04 17:57:31 +0100138 Ok(compos_instance)
139 }
140
Victor Hsieh18775b12021-10-12 17:42:48 -0700141 fn initialize_service(service: &Strong<dyn ICompOsService>, key_blob: &[u8]) -> Result<()> {
142 // Key blob is assumed to be verified/trusted.
143 service.initializeSigningKey(key_blob).context("Loading signing key")?;
144
145 // TODO(198211396): Implement correctly.
146 service
147 .initializeClasspaths(&env::var("BOOTCLASSPATH")?, &env::var("DEX2OATBOOTCLASSPATH")?)
148 .context("Initializing *CLASSPATH")?;
149 Ok(())
150 }
151
Alan Stokes16e027f2021-10-04 17:57:31 +0100152 fn start_vm(&self) -> Result<CompOsInstance> {
153 let instance_image = fs::OpenOptions::new()
154 .read(true)
155 .write(true)
156 .open(&self.instance_image)
157 .context("Failed to open instance image")?;
158 let vm_instance = VmInstance::start(instance_image).context("Starting VM")?;
159 let service = vm_instance.get_service().context("Connecting to CompOS")?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100160 Ok(CompOsInstance { vm_instance, service })
161 }
162
163 fn create_instance_image(
164 &self,
165 virtualization_service: &dyn IVirtualizationService,
166 ) -> Result<()> {
167 let instance_image = fs::OpenOptions::new()
168 .create(true)
169 .read(true)
170 .write(true)
171 .open(&self.instance_image)
172 .context("Creating instance image file")?;
173 let instance_image = ParcelFileDescriptor::new(instance_image);
174 // TODO: Where does this number come from?
175 let size = 10 * 1024 * 1024;
176 virtualization_service
177 .initializeWritablePartition(&instance_image, size, PartitionType::ANDROID_VM_INSTANCE)
178 .context("Writing instance image file")?;
179 Ok(())
180 }
181
182 fn check_files_exist(&self) -> Result<()> {
183 if !self.instance_root.is_dir() {
184 bail!("Directory {} not found", self.instance_root.display())
185 };
186 Self::check_file_exists(&self.instance_image)?;
187 Self::check_file_exists(&self.key_blob)?;
188 Self::check_file_exists(&self.public_key)?;
189 Ok(())
190 }
191
192 fn check_file_exists(file: &Path) -> Result<()> {
193 if !file.is_file() {
194 bail!("File {} not found", file.display())
195 };
196 Ok(())
197 }
198}