blob: 8189fe0da120a6490ada892c0f5e3d4c5ffc3cdb [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};
Alan Stokes9ca14ca2021-10-20 14:25:57 +010024use binder_common::lazy_service::LazyServiceGuard;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010025use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService;
26use compos_aidl_interface::binder::{ParcelFileDescriptor, Strong};
Alan Stokesd21764c2021-10-25 15:33:40 +010027use compos_common::compos_client::{VmInstance, VmParameters};
Alan Stokes6b2d0a82021-09-29 11:30:39 +010028use compos_common::{
29 COMPOS_DATA_ROOT, INSTANCE_IMAGE_FILE, PRIVATE_KEY_BLOB_FILE, PUBLIC_KEY_FILE,
30};
31use log::{info, warn};
Victor Hsieh18775b12021-10-12 17:42:48 -070032use std::env;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010033use std::fs;
34use std::path::{Path, PathBuf};
35
36pub struct CompOsInstance {
Alan Stokes9ca14ca2021-10-20 14:25:57 +010037 service: Strong<dyn ICompOsService>,
Alan Stokes6b2d0a82021-09-29 11:30:39 +010038 #[allow(dead_code)] // Keeps VirtualizationService & the VM alive
39 vm_instance: VmInstance,
Alan Stokes9ca14ca2021-10-20 14:25:57 +010040 #[allow(dead_code)] // Keeps composd process alive
41 lazy_service_guard: LazyServiceGuard,
Alan Stokes6b2d0a82021-09-29 11:30:39 +010042}
43
44impl CompOsInstance {
45 pub fn get_service(&self) -> Strong<dyn ICompOsService> {
46 self.service.clone()
47 }
48}
49
50pub struct InstanceStarter {
51 instance_name: String,
52 instance_root: PathBuf,
53 instance_image: PathBuf,
54 key_blob: PathBuf,
55 public_key: PathBuf,
Alan Stokesd21764c2021-10-25 15:33:40 +010056 vm_parameters: VmParameters,
Alan Stokes6b2d0a82021-09-29 11:30:39 +010057}
58
59impl InstanceStarter {
Alan Stokesd21764c2021-10-25 15:33:40 +010060 pub fn new(instance_name: &str, vm_parameters: VmParameters) -> Self {
Alan Stokes6b2d0a82021-09-29 11:30:39 +010061 let instance_root = Path::new(COMPOS_DATA_ROOT).join(instance_name);
62 let instant_root_path = instance_root.as_path();
63 let instance_image = instant_root_path.join(INSTANCE_IMAGE_FILE);
64 let key_blob = instant_root_path.join(PRIVATE_KEY_BLOB_FILE);
65 let public_key = instant_root_path.join(PUBLIC_KEY_FILE);
66 Self {
67 instance_name: instance_name.to_owned(),
68 instance_root,
69 instance_image,
70 key_blob,
71 public_key,
Alan Stokesd21764c2021-10-25 15:33:40 +010072 vm_parameters,
Alan Stokes6b2d0a82021-09-29 11:30:39 +010073 }
74 }
75
76 pub fn create_or_start_instance(
77 &self,
Alan Stokesd21764c2021-10-25 15:33:40 +010078 virtualization_service: &dyn IVirtualizationService,
Alan Stokes6b2d0a82021-09-29 11:30:39 +010079 ) -> Result<CompOsInstance> {
Alan Stokesd21764c2021-10-25 15:33:40 +010080 let compos_instance = self.start_existing_instance(virtualization_service);
Alan Stokes6b2d0a82021-09-29 11:30:39 +010081 match compos_instance {
82 Ok(_) => return compos_instance,
Alan Stokes14f07392021-09-27 14:03:31 +010083 Err(e) => warn!("Failed to start: {}", e),
Alan Stokes6b2d0a82021-09-29 11:30:39 +010084 }
85
Alan Stokesd21764c2021-10-25 15:33:40 +010086 self.start_new_instance(virtualization_service)
Alan Stokes6b2d0a82021-09-29 11:30:39 +010087 }
88
Alan Stokesd21764c2021-10-25 15:33:40 +010089 fn start_existing_instance(
90 &self,
91 virtualization_service: &dyn IVirtualizationService,
92 ) -> Result<CompOsInstance> {
Alan Stokes6b2d0a82021-09-29 11:30:39 +010093 // No point even trying if the files we need aren't there.
94 self.check_files_exist()?;
95
Alan Stokes14f07392021-09-27 14:03:31 +010096 info!("Starting {} CompOs instance", self.instance_name);
97
Alan Stokes6b2d0a82021-09-29 11:30:39 +010098 let key_blob = fs::read(&self.key_blob).context("Reading private key blob")?;
99 let public_key = fs::read(&self.public_key).context("Reading public key")?;
100
Alan Stokesd21764c2021-10-25 15:33:40 +0100101 let compos_instance = self.start_vm(virtualization_service)?;
Alan Stokes16e027f2021-10-04 17:57:31 +0100102 let service = &compos_instance.service;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100103
104 if !service.verifySigningKey(&key_blob, &public_key).context("Verifying key pair")? {
105 bail!("Key pair invalid");
106 }
107
108 // If we get this far then the instance image is valid in the current context (e.g. the
109 // current set of APEXes) and the key blob can be successfully decrypted by the VM. So the
110 // files have not been tampered with and we're good to go.
111
Victor Hsieh18775b12021-10-12 17:42:48 -0700112 Self::initialize_service(service, &key_blob)?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100113
Alan Stokes16e027f2021-10-04 17:57:31 +0100114 Ok(compos_instance)
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100115 }
116
117 fn start_new_instance(
118 &self,
119 virtualization_service: &dyn IVirtualizationService,
120 ) -> Result<CompOsInstance> {
121 info!("Creating {} CompOs instance", self.instance_name);
122
123 // Ignore failure here - the directory may already exist.
124 let _ = fs::create_dir(&self.instance_root);
125
126 self.create_instance_image(virtualization_service)?;
127
Alan Stokesd21764c2021-10-25 15:33:40 +0100128 let compos_instance = self.start_vm(virtualization_service)?;
Alan Stokes16e027f2021-10-04 17:57:31 +0100129 let service = &compos_instance.service;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100130
131 let key_data = service.generateSigningKey().context("Generating signing key")?;
132 fs::write(&self.key_blob, &key_data.keyBlob).context("Writing key blob")?;
Alan Stokes14f07392021-09-27 14:03:31 +0100133
134 let key_result = composd_native::extract_rsa_public_key(&key_data.certificate);
135 let rsa_public_key = key_result.key;
136 if rsa_public_key.is_empty() {
137 bail!("Failed to extract public key from certificate: {}", key_result.error);
138 }
139 fs::write(&self.public_key, &rsa_public_key).context("Writing public key")?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100140
Victor Hsieh18775b12021-10-12 17:42:48 -0700141 // Unlike when starting an existing instance, we don't need to verify the key, since we
142 // just generated it and have it in memory.
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100143
Victor Hsieh18775b12021-10-12 17:42:48 -0700144 Self::initialize_service(service, &key_data.keyBlob)?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100145
Alan Stokes16e027f2021-10-04 17:57:31 +0100146 Ok(compos_instance)
147 }
148
Victor Hsieh18775b12021-10-12 17:42:48 -0700149 fn initialize_service(service: &Strong<dyn ICompOsService>, key_blob: &[u8]) -> Result<()> {
150 // Key blob is assumed to be verified/trusted.
151 service.initializeSigningKey(key_blob).context("Loading signing key")?;
152
153 // TODO(198211396): Implement correctly.
154 service
Victor Hsieh64290a52021-11-17 13:34:46 -0800155 .initializeClasspaths(
156 &env::var("BOOTCLASSPATH")?,
157 &env::var("DEX2OATBOOTCLASSPATH")?,
158 &env::var("SYSTEMSERVERCLASSPATH")?,
159 )
Victor Hsieh18775b12021-10-12 17:42:48 -0700160 .context("Initializing *CLASSPATH")?;
161 Ok(())
162 }
163
Alan Stokesd21764c2021-10-25 15:33:40 +0100164 fn start_vm(
165 &self,
166 virtualization_service: &dyn IVirtualizationService,
167 ) -> Result<CompOsInstance> {
Alan Stokes16e027f2021-10-04 17:57:31 +0100168 let instance_image = fs::OpenOptions::new()
169 .read(true)
170 .write(true)
171 .open(&self.instance_image)
172 .context("Failed to open instance image")?;
Alan Stokesd21764c2021-10-25 15:33:40 +0100173 let vm_instance =
174 VmInstance::start(virtualization_service, instance_image, &self.vm_parameters)
175 .context("Starting VM")?;
Alan Stokes16e027f2021-10-04 17:57:31 +0100176 let service = vm_instance.get_service().context("Connecting to CompOS")?;
Alan Stokes9ca14ca2021-10-20 14:25:57 +0100177 Ok(CompOsInstance { vm_instance, service, lazy_service_guard: Default::default() })
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100178 }
179
180 fn create_instance_image(
181 &self,
182 virtualization_service: &dyn IVirtualizationService,
183 ) -> Result<()> {
184 let instance_image = fs::OpenOptions::new()
185 .create(true)
Alan Stokes23b90ee2021-10-28 11:36:14 +0100186 .truncate(true)
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100187 .read(true)
188 .write(true)
189 .open(&self.instance_image)
190 .context("Creating instance image file")?;
191 let instance_image = ParcelFileDescriptor::new(instance_image);
192 // TODO: Where does this number come from?
193 let size = 10 * 1024 * 1024;
194 virtualization_service
195 .initializeWritablePartition(&instance_image, size, PartitionType::ANDROID_VM_INSTANCE)
196 .context("Writing instance image file")?;
197 Ok(())
198 }
199
200 fn check_files_exist(&self) -> Result<()> {
201 if !self.instance_root.is_dir() {
Alan Stokes6fc18372021-11-25 17:50:27 +0000202 bail!("Directory {:?} not found", self.instance_root)
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100203 };
204 Self::check_file_exists(&self.instance_image)?;
205 Self::check_file_exists(&self.key_blob)?;
206 Self::check_file_exists(&self.public_key)?;
207 Ok(())
208 }
209
210 fn check_file_exists(file: &Path) -> Result<()> {
211 if !file.is_file() {
Alan Stokes6fc18372021-11-25 17:50:27 +0000212 bail!("File {:?} not found", file)
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100213 };
214 Ok(())
215 }
216}