1 /*
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 a CompOS signature. It starts a CompOS VM as part of this to retrieve the
18 //! public key. The tool is intended to be run by odsign during boot.
19
20 use android_logger::LogId;
21 use anyhow::{anyhow, bail, Context, Result};
22 use binder::ProcessState;
23 use clap::{Parser, ValueEnum};
24 use compos_common::compos_client::{ComposClient, VmCpuTopology, VmParameters};
25 use compos_common::odrefresh::{
26 CURRENT_ARTIFACTS_SUBDIR, ODREFRESH_OUTPUT_ROOT_DIR, PENDING_ARTIFACTS_SUBDIR,
27 TEST_ARTIFACTS_SUBDIR,
28 };
29 use compos_common::{
30 COMPOS_DATA_ROOT, CURRENT_INSTANCE_DIR, IDSIG_FILE, IDSIG_MANIFEST_APK_FILE,
31 IDSIG_MANIFEST_EXT_APK_FILE, INSTANCE_ID_FILE, INSTANCE_IMAGE_FILE, TEST_INSTANCE_DIR,
32 };
33 use log::error;
34 use std::fs;
35 use std::fs::File;
36 use std::io::Read;
37 use std::panic;
38 use std::path::Path;
39
40 const MAX_FILE_SIZE_BYTES: u64 = 100 * 1024;
41
42 #[derive(Parser)]
43 struct Args {
44 /// Type of the VM instance
45 #[clap(long, value_enum)]
46 instance: Instance,
47
48 /// Starts the VM in debug mode
49 #[clap(long, action)]
50 debug: bool,
51 }
52
53 #[derive(ValueEnum, Clone)]
54 enum Instance {
55 Current,
56 Pending,
57 Test,
58 }
59
main()60 fn main() {
61 android_logger::init_once(
62 android_logger::Config::default()
63 .with_tag("compos_verify")
64 .with_max_level(log::LevelFilter::Info)
65 .with_log_buffer(LogId::System), // Needed to log successfully early in boot
66 );
67
68 // Redirect panic messages to logcat.
69 panic::set_hook(Box::new(|panic_info| {
70 error!("{}", panic_info);
71 }));
72
73 if let Err(e) = try_main() {
74 error!("{:?}", e);
75 std::process::exit(1)
76 }
77 }
78
try_main() -> Result<()>79 fn try_main() -> Result<()> {
80 let args = Args::parse();
81 let (instance_dir, artifacts_dir) = match args.instance {
82 Instance::Current => (CURRENT_INSTANCE_DIR, CURRENT_ARTIFACTS_SUBDIR),
83 Instance::Pending => (CURRENT_INSTANCE_DIR, PENDING_ARTIFACTS_SUBDIR),
84 Instance::Test => (TEST_INSTANCE_DIR, TEST_ARTIFACTS_SUBDIR),
85 };
86
87 let instance_dir = Path::new(COMPOS_DATA_ROOT).join(instance_dir);
88 let artifacts_dir = Path::new(ODREFRESH_OUTPUT_ROOT_DIR).join(artifacts_dir);
89
90 if !instance_dir.is_dir() {
91 bail!("{:?} is not a directory", instance_dir);
92 }
93
94 let instance_id_file = instance_dir.join(INSTANCE_ID_FILE);
95 let instance_image = instance_dir.join(INSTANCE_IMAGE_FILE);
96 let idsig = instance_dir.join(IDSIG_FILE);
97 let idsig_manifest_apk = instance_dir.join(IDSIG_MANIFEST_APK_FILE);
98 let idsig_manifest_ext_apk = instance_dir.join(IDSIG_MANIFEST_EXT_APK_FILE);
99
100 let instance_id: [u8; 64] = if cfg!(llpvm_changes) {
101 fs::read(instance_id_file)?.try_into().map_err(|_| anyhow!("Failed to get instance_id"))?
102 } else {
103 [0u8; 64]
104 };
105 let instance_image = File::open(instance_image).context("Failed to open instance image")?;
106
107 let info = artifacts_dir.join("compos.info");
108 let signature = artifacts_dir.join("compos.info.signature");
109
110 let info = read_small_file(&info).context("Failed to read compos.info")?;
111 let signature = read_small_file(&signature).context("Failed to read compos.info signature")?;
112
113 // We need to start the thread pool to be able to receive Binder callbacks
114 ProcessState::start_thread_pool();
115
116 let virtmgr = vmclient::VirtualizationService::new()?;
117 let virtualization_service = virtmgr.connect()?;
118 let vm_instance = ComposClient::start(
119 &*virtualization_service,
120 instance_id,
121 instance_image,
122 &idsig,
123 &idsig_manifest_apk,
124 &idsig_manifest_ext_apk,
125 &VmParameters {
126 name: String::from("ComposVerify"),
127 os: String::from("microdroid"),
128 cpu_topology: VmCpuTopology::OneCpu, // This VM runs very little work at boot
129 debug_mode: args.debug,
130 ..Default::default()
131 },
132 )?;
133
134 let service = vm_instance.connect_service()?;
135 let public_key = service.getPublicKey().context("Getting public key");
136
137 vm_instance.shutdown(service);
138
139 if !compos_verify_native::verify(&public_key?, &signature, &info) {
140 bail!("Signature verification failed");
141 }
142
143 Ok(())
144 }
145
read_small_file(file: &Path) -> Result<Vec<u8>>146 fn read_small_file(file: &Path) -> Result<Vec<u8>> {
147 let mut file = File::open(file)?;
148 if file.metadata()?.len() > MAX_FILE_SIZE_BYTES {
149 bail!("File is too big");
150 }
151 let mut data = Vec::new();
152 file.read_to_end(&mut data)?;
153 Ok(data)
154 }
155
156 #[cfg(test)]
157 mod tests {
158 use super::*;
159 use clap::CommandFactory;
160
161 #[test]
verify_args()162 fn verify_args() {
163 // Check that the command parsing has been configured in a valid way.
164 Args::command().debug_assert();
165 }
166 }
167