blob: 1751d35af8946ee843e1e36d71c161299dbfad2e [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};
31use std::fs;
32use std::path::{Path, PathBuf};
33
34pub struct CompOsInstance {
35 #[allow(dead_code)] // Keeps VirtualizationService & the VM alive
36 vm_instance: VmInstance,
37 service: Strong<dyn ICompOsService>,
38}
39
40impl CompOsInstance {
41 pub fn get_service(&self) -> Strong<dyn ICompOsService> {
42 self.service.clone()
43 }
44}
45
46pub struct InstanceStarter {
47 instance_name: String,
48 instance_root: PathBuf,
49 instance_image: PathBuf,
50 key_blob: PathBuf,
51 public_key: PathBuf,
52}
53
54impl InstanceStarter {
55 pub fn new(instance_name: &str) -> Self {
56 let instance_root = Path::new(COMPOS_DATA_ROOT).join(instance_name);
57 let instant_root_path = instance_root.as_path();
58 let instance_image = instant_root_path.join(INSTANCE_IMAGE_FILE);
59 let key_blob = instant_root_path.join(PRIVATE_KEY_BLOB_FILE);
60 let public_key = instant_root_path.join(PUBLIC_KEY_FILE);
61 Self {
62 instance_name: instance_name.to_owned(),
63 instance_root,
64 instance_image,
65 key_blob,
66 public_key,
67 }
68 }
69
70 pub fn create_or_start_instance(
71 &self,
72 service: &dyn IVirtualizationService,
73 ) -> Result<CompOsInstance> {
74 let compos_instance = self.start_existing_instance();
75 match compos_instance {
76 Ok(_) => return compos_instance,
Alan Stokes14f07392021-09-27 14:03:31 +010077 Err(e) => warn!("Failed to start: {}", e),
Alan Stokes6b2d0a82021-09-29 11:30:39 +010078 }
79
80 self.start_new_instance(service)
81 }
82
83 fn start_existing_instance(&self) -> Result<CompOsInstance> {
84 // No point even trying if the files we need aren't there.
85 self.check_files_exist()?;
86
Alan Stokes14f07392021-09-27 14:03:31 +010087 info!("Starting {} CompOs instance", self.instance_name);
88
Alan Stokes6b2d0a82021-09-29 11:30:39 +010089 let key_blob = fs::read(&self.key_blob).context("Reading private key blob")?;
90 let public_key = fs::read(&self.public_key).context("Reading public key")?;
91
Alan Stokes16e027f2021-10-04 17:57:31 +010092 let compos_instance = self.start_vm()?;
93 let service = &compos_instance.service;
Alan Stokes6b2d0a82021-09-29 11:30:39 +010094
95 if !service.verifySigningKey(&key_blob, &public_key).context("Verifying key pair")? {
96 bail!("Key pair invalid");
97 }
98
99 // If we get this far then the instance image is valid in the current context (e.g. the
100 // current set of APEXes) and the key blob can be successfully decrypted by the VM. So the
101 // files have not been tampered with and we're good to go.
102
103 service.initializeSigningKey(&key_blob).context("Loading signing key")?;
104
Alan Stokes16e027f2021-10-04 17:57:31 +0100105 Ok(compos_instance)
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100106 }
107
108 fn start_new_instance(
109 &self,
110 virtualization_service: &dyn IVirtualizationService,
111 ) -> Result<CompOsInstance> {
112 info!("Creating {} CompOs instance", self.instance_name);
113
114 // Ignore failure here - the directory may already exist.
115 let _ = fs::create_dir(&self.instance_root);
116
117 self.create_instance_image(virtualization_service)?;
118
Alan Stokes16e027f2021-10-04 17:57:31 +0100119 let compos_instance = self.start_vm()?;
120 let service = &compos_instance.service;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100121
122 let key_data = service.generateSigningKey().context("Generating signing key")?;
123 fs::write(&self.key_blob, &key_data.keyBlob).context("Writing key blob")?;
Alan Stokes14f07392021-09-27 14:03:31 +0100124
125 let key_result = composd_native::extract_rsa_public_key(&key_data.certificate);
126 let rsa_public_key = key_result.key;
127 if rsa_public_key.is_empty() {
128 bail!("Failed to extract public key from certificate: {}", key_result.error);
129 }
130 fs::write(&self.public_key, &rsa_public_key).context("Writing public key")?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100131
132 // We don't need to verify the key, since we just generated it and have it in memory.
133
134 service.initializeSigningKey(&key_data.keyBlob).context("Loading signing key")?;
135
Alan Stokes16e027f2021-10-04 17:57:31 +0100136 Ok(compos_instance)
137 }
138
139 fn start_vm(&self) -> Result<CompOsInstance> {
140 let instance_image = fs::OpenOptions::new()
141 .read(true)
142 .write(true)
143 .open(&self.instance_image)
144 .context("Failed to open instance image")?;
145 let vm_instance = VmInstance::start(instance_image).context("Starting VM")?;
146 let service = vm_instance.get_service().context("Connecting to CompOS")?;
Alan Stokes6b2d0a82021-09-29 11:30:39 +0100147 Ok(CompOsInstance { vm_instance, service })
148 }
149
150 fn create_instance_image(
151 &self,
152 virtualization_service: &dyn IVirtualizationService,
153 ) -> Result<()> {
154 let instance_image = fs::OpenOptions::new()
155 .create(true)
156 .read(true)
157 .write(true)
158 .open(&self.instance_image)
159 .context("Creating instance image file")?;
160 let instance_image = ParcelFileDescriptor::new(instance_image);
161 // TODO: Where does this number come from?
162 let size = 10 * 1024 * 1024;
163 virtualization_service
164 .initializeWritablePartition(&instance_image, size, PartitionType::ANDROID_VM_INSTANCE)
165 .context("Writing instance image file")?;
166 Ok(())
167 }
168
169 fn check_files_exist(&self) -> Result<()> {
170 if !self.instance_root.is_dir() {
171 bail!("Directory {} not found", self.instance_root.display())
172 };
173 Self::check_file_exists(&self.instance_image)?;
174 Self::check_file_exists(&self.key_blob)?;
175 Self::check_file_exists(&self.public_key)?;
176 Ok(())
177 }
178
179 fn check_file_exists(file: &Path) -> Result<()> {
180 if !file.is_file() {
181 bail!("File {} not found", file.display())
182 };
183 Ok(())
184 }
185}