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