blob: f279b930e6804ef970ba52e29d66715c6939f16f [file] [log] [blame]
Alan Stokeseb97d4a2021-08-26 14:24:32 +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//! A tool to verify whether a CompOs instance image and key pair are valid. It starts a CompOs VM
18//! as part of this. The tool is intended to be run by odsign during boot.
19
20use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
21 IVirtualMachine::IVirtualMachine,
22 IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback},
23 IVirtualizationService::IVirtualizationService,
24 VirtualMachineAppConfig::VirtualMachineAppConfig,
25 VirtualMachineConfig::VirtualMachineConfig,
26};
27use android_system_virtualizationservice::binder::{
28 wait_for_interface, BinderFeatures, DeathRecipient, IBinder, Interface, ParcelFileDescriptor,
29 ProcessState, Result as BinderResult, Strong,
30};
31use anyhow::{anyhow, bail, Context, Result};
32use binder::{
33 unstable_api::{new_spibinder, AIBinder},
34 FromIBinder,
35};
36use compos_aidl_interface::aidl::com::android::compos::ICompOsService::ICompOsService;
37use std::fs::{self, File};
38use std::io::Read;
39use std::path::{Path, PathBuf};
40use std::sync::{Arc, Condvar, Mutex};
41use std::thread;
42use std::time::Duration;
43
44const COMPOS_APEX_ROOT: &str = "/apex/com.android.compos";
45const COMPOS_DATA_ROOT: &str = "/data/misc/apexdata/com.android.compos";
46const CURRENT_DIR: &str = "current";
47const PENDING_DIR: &str = "pending";
48const PRIVATE_KEY_BLOB_FILE: &str = "key.blob";
49const PUBLIC_KEY_FILE: &str = "key.pubkey";
50const INSTANCE_IMAGE_FILE: &str = "instance.img";
51
52const MAX_FILE_SIZE_BYTES: u64 = 8 * 1024;
53
54const COMPOS_SERVICE_PORT: u32 = 6432;
55
56fn main() -> Result<()> {
57 let matches = clap::App::new("compos_verify_key")
58 .arg(
59 clap::Arg::with_name("instance")
60 .long("instance")
61 .takes_value(true)
62 .required(true)
63 .possible_values(&["pending", "current"]),
64 )
65 .get_matches();
66 let do_pending = matches.value_of("instance").unwrap() == "pending";
67
68 let instance_dir: PathBuf =
69 [COMPOS_DATA_ROOT, if do_pending { PENDING_DIR } else { CURRENT_DIR }].iter().collect();
70
71 if !instance_dir.is_dir() {
72 bail!("{} is not a directory", instance_dir.display());
73 }
74
75 // We need to start the thread pool to be able to receive Binder callbacks
76 ProcessState::start_thread_pool();
77
78 let result = verify(&instance_dir).and_then(|_| {
79 if do_pending {
80 // If the pending instance is ok, then it must actually match the current system state,
81 // so we promote it to current.
82 println!("Promoting pending to current");
83 promote_to_current(&instance_dir)
84 } else {
85 Ok(())
86 }
87 });
88
89 if result.is_err() {
90 // This is best efforts, and we still want to report the original error as our result
91 println!("Removing {}", instance_dir.display());
92 if let Err(e) = fs::remove_dir_all(&instance_dir) {
93 eprintln!("Failed to remove directory: {}", e);
94 }
95 }
96
97 result
98}
99
100fn verify(instance_dir: &Path) -> Result<()> {
101 let blob = instance_dir.join(PRIVATE_KEY_BLOB_FILE);
102 let public_key = instance_dir.join(PUBLIC_KEY_FILE);
103 let instance = instance_dir.join(INSTANCE_IMAGE_FILE);
104
105 let blob = read_small_file(blob).context("Failed to read key blob")?;
106 let public_key = read_small_file(public_key).context("Failed to read public key")?;
107
108 let instance = File::open(instance).context("Failed to open instance image file")?;
109 let vm_instance = VmInstance::start(instance)?;
110 let service = get_service(vm_instance.cid).context("Failed to connect to CompOs service")?;
111
112 let result = service.verifySigningKey(&blob, &public_key).context("Verifying signing key")?;
113
114 if !result {
115 bail!("Key files are not valid");
116 }
117
118 Ok(())
119}
120
121fn read_small_file(file: PathBuf) -> Result<Vec<u8>> {
122 let mut file = File::open(file)?;
123 if file.metadata()?.len() > MAX_FILE_SIZE_BYTES {
124 bail!("File is too big");
125 }
126 let mut data = vec![];
127 file.read_to_end(&mut data)?;
128 Ok(data)
129}
130
131fn get_service(cid: i32) -> Result<Strong<dyn ICompOsService>> {
132 let cid = cid as u32;
133 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
134 // safely taken by new_spibinder.
135 let ibinder = unsafe {
136 new_spibinder(
137 binder_rpc_unstable_bindgen::RpcClient(cid, COMPOS_SERVICE_PORT) as *mut AIBinder
138 )
139 }
140 .ok_or_else(|| anyhow!("Invalid raw AIBinder"))?;
141
142 Ok(FromIBinder::try_from(ibinder)?)
143}
144
145fn promote_to_current(instance_dir: &Path) -> Result<()> {
146 let current_dir: PathBuf = [COMPOS_DATA_ROOT, CURRENT_DIR].iter().collect();
147
148 // This may fail if the directory doesn't exist - which is fine, we only care about the rename
149 // succeeding.
150 let _ = fs::remove_dir_all(&current_dir);
151
152 fs::rename(&instance_dir, &current_dir)
153 .context("Unable to promote pending instance to current")?;
154 Ok(())
155}
156
157#[derive(Debug)]
158struct VmState {
159 has_died: bool,
160 cid: Option<i32>,
161}
162
163impl Default for VmState {
164 fn default() -> Self {
165 Self { has_died: false, cid: None }
166 }
167}
168
169#[derive(Debug)]
170struct VmStateMonitor {
171 mutex: Mutex<VmState>,
172 state_ready: Condvar,
173}
174
175impl Default for VmStateMonitor {
176 fn default() -> Self {
177 Self { mutex: Mutex::new(Default::default()), state_ready: Condvar::new() }
178 }
179}
180
181impl VmStateMonitor {
182 fn set_died(&self) {
183 let mut state = self.mutex.lock().unwrap();
184 state.has_died = true;
185 state.cid = None;
186 drop(state); // Unlock the mutex prior to notifying
187 self.state_ready.notify_all();
188 }
189
190 fn set_started(&self, cid: i32) {
191 let mut state = self.mutex.lock().unwrap();
192 if state.has_died {
193 return;
194 }
195 state.cid = Some(cid);
196 drop(state); // Unlock the mutex prior to notifying
197 self.state_ready.notify_all();
198 }
199
200 fn wait_for_start(&self) -> Result<i32> {
201 let (state, result) = self
202 .state_ready
203 .wait_timeout_while(self.mutex.lock().unwrap(), Duration::from_secs(10), |state| {
204 state.cid.is_none() && !state.has_died
205 })
206 .unwrap();
207 if result.timed_out() {
208 bail!("Timed out waiting for VM")
209 }
210 state.cid.ok_or_else(|| anyhow!("VM died"))
211 }
212}
213
214struct VmInstance {
215 #[allow(dead_code)] // Keeps the vm alive even if we don`t touch it
216 vm: Strong<dyn IVirtualMachine>,
217 cid: i32,
218}
219
220impl VmInstance {
221 fn start(instance_file: File) -> Result<VmInstance> {
222 let instance_fd = ParcelFileDescriptor::new(instance_file);
223
224 let apex_dir = Path::new(COMPOS_APEX_ROOT);
225 let data_dir = Path::new(COMPOS_DATA_ROOT);
226
227 let apk_fd = File::open(apex_dir.join("app/CompOSPayloadApp/CompOSPayloadApp.apk"))
228 .context("Failed to open config APK file")?;
229 let apk_fd = ParcelFileDescriptor::new(apk_fd);
230
231 let idsig_fd = File::open(apex_dir.join("etc/CompOSPayloadApp.apk.idsig"))
232 .context("Failed to open config APK idsig file")?;
233 let idsig_fd = ParcelFileDescriptor::new(idsig_fd);
234
235 // TODO: Send this to stdout instead? Or specify None?
236 let log_fd = File::create(data_dir.join("vm.log")).context("Failed to create log file")?;
237 let log_fd = ParcelFileDescriptor::new(log_fd);
238
239 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
240 apk: Some(apk_fd),
241 idsig: Some(idsig_fd),
242 instanceImage: Some(instance_fd),
243 configPath: "assets/vm_config.json".to_owned(),
244 ..Default::default()
245 });
246
247 let service = wait_for_interface::<dyn IVirtualizationService>(
248 "android.system.virtualizationservice",
249 )
250 .context("Failed to find VirtualizationService")?;
251
252 let vm = service.startVm(&config, Some(&log_fd)).context("Failed to start VM")?;
253 let vm_state = Arc::new(VmStateMonitor::default());
254
255 let vm_state_clone = Arc::clone(&vm_state);
256 vm.as_binder().link_to_death(&mut DeathRecipient::new(move || {
257 vm_state_clone.set_died();
258 eprintln!("VirtualizationService died");
259 }))?;
260
261 let vm_state_clone = Arc::clone(&vm_state);
262 let callback = BnVirtualMachineCallback::new_binder(
263 VmCallback(vm_state_clone),
264 BinderFeatures::default(),
265 );
266 vm.registerCallback(&callback)?;
267
268 let cid = vm_state.wait_for_start()?;
269
270 // TODO: Use onPayloadReady to avoid this
271 thread::sleep(Duration::from_secs(3));
272
273 Ok(VmInstance { vm, cid })
274 }
275}
276
277#[derive(Debug)]
278struct VmCallback(Arc<VmStateMonitor>);
279
280impl Interface for VmCallback {}
281
282impl IVirtualMachineCallback for VmCallback {
283 fn onDied(&self, cid: i32) -> BinderResult<()> {
284 self.0.set_died();
285 println!("VM died, cid = {}", cid);
286 Ok(())
287 }
288
289 fn onPayloadStarted(
290 &self,
291 cid: i32,
292 _stream: Option<&binder::parcel::ParcelFileDescriptor>,
293 ) -> BinderResult<()> {
294 self.0.set_started(cid);
295 // TODO: Use the stream?
296 println!("VM payload started, cid = {}", cid);
297 Ok(())
298 }
299
300 fn onPayloadReady(&self, cid: i32) -> BinderResult<()> {
301 // TODO: Use this to trigger vsock connection
302 println!("VM payload ready, cid = {}", cid);
303 Ok(())
304 }
305
306 fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> {
307 // This should probably never happen in our case, but if it does we means our VM is no
308 // longer running
309 self.0.set_died();
310 println!("VM payload finished, cid = {}, exit code = {}", cid, exit_code);
311 Ok(())
312 }
313}