blob: ac62e58e277daeaa0610edc21171c59f13cabdca [file] [log] [blame]
Jooyung Han347d9f22021-05-28 00:05:14 +09001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Microdroid Manager
16
Jiyong Park21ce2c52021-08-28 02:32:17 +090017mod instance;
Jooyung Hanf48ceb42021-06-01 18:00:04 +090018mod ioutil;
Jooyung Han7a343f92021-09-08 22:53:11 +090019mod payload;
Jooyung Han347d9f22021-05-28 00:05:14 +090020
Jiyong Parkf7dea252021-09-08 01:42:54 +090021use crate::instance::{ApkData, InstanceDisk, MicrodroidData, RootHash};
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090022use anyhow::{anyhow, bail, ensure, Context, Result};
Jiyong Parka41535b2021-09-10 19:31:48 +090023use apkverify::{get_public_key_der, verify};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090024use binder::unstable_api::{new_spibinder, AIBinder};
25use binder::{FromIBinder, Strong};
Jiyong Park21ce2c52021-08-28 02:32:17 +090026use idsig::V4Signature;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090027use log::{error, info, warn};
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090028use microdroid_metadata::{write_metadata, Metadata};
Jooyung Han634e2d72021-06-10 16:27:38 +090029use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090030use payload::{get_apex_data_from_payload, load_metadata, to_metadata};
Jiyong Parkbb4a9872021-09-06 15:59:21 +090031use rustutils::system_properties;
Joel Galenson482704c2021-07-29 15:53:53 -070032use rustutils::system_properties::PropertyWatcher;
Inseob Kim7f61fe72021-08-20 20:50:47 +090033use std::fs::{self, File, OpenOptions};
Inseob Kimc7d28c72021-10-25 14:28:10 +000034use std::os::unix::io::{FromRawFd, IntoRawFd};
Jooyung Hanf48ceb42021-06-01 18:00:04 +090035use std::path::Path;
Jiyong Park8611a6c2021-07-09 18:17:44 +090036use std::process::{Command, Stdio};
37use std::str;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090038use std::time::{Duration, SystemTime};
Jiyong Park8611a6c2021-07-09 18:17:44 +090039use vsock::VsockStream;
Jooyung Han634e2d72021-06-10 16:27:38 +090040
Inseob Kimd0587562021-09-01 21:27:32 +090041use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
42 VM_BINDER_SERVICE_PORT, VM_STREAM_SERVICE_PORT, IVirtualMachineService,
43};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090044
Jooyung Han634e2d72021-06-10 16:27:38 +090045const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jooyung Han19c1d6c2021-08-06 14:08:16 +090046const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
Jooyung Han347d9f22021-05-28 00:05:14 +090047
Inseob Kim1b95f2e2021-08-19 13:17:40 +090048/// The CID representing the host VM
49const VMADDR_CID_HOST: u32 = 2;
50
Jiyong Parkbb4a9872021-09-06 15:59:21 +090051const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
52
Inseob Kim1b95f2e2021-08-19 13:17:40 +090053fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
54 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
55 // safely taken by new_spibinder.
56 let ibinder = unsafe {
57 new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
58 VMADDR_CID_HOST,
Inseob Kimd0587562021-09-01 21:27:32 +090059 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090060 ) as *mut AIBinder)
61 };
62 if let Some(ibinder) = ibinder {
63 <dyn IVirtualMachineService>::try_from(ibinder).context("Cannot connect to RPC service")
64 } else {
65 bail!("Invalid raw AIBinder")
66 }
67}
68
Jooyung Han311b1202021-09-14 22:00:16 +090069fn main() {
70 if let Err(e) = try_main() {
Alan Stokes6018a8c2021-10-01 10:54:38 +010071 error!("failed with {:?}", e);
Jooyung Han311b1202021-09-14 22:00:16 +090072 std::process::exit(1);
73 }
74}
75
76fn try_main() -> Result<()> {
Jiyong Park79b88012021-06-25 13:06:25 +090077 kernlog::init()?;
Jooyung Han347d9f22021-05-28 00:05:14 +090078 info!("started.");
79
Jooyung Han311b1202021-09-14 22:00:16 +090080 let metadata = load_metadata().context("Failed to load payload metadata")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +090081
Jooyung Han311b1202021-09-14 22:00:16 +090082 let mut instance = InstanceDisk::new().context("Failed to load instance.img")?;
Jooyung Han7a343f92021-09-08 22:53:11 +090083 let saved_data = instance.read_microdroid_data().context("Failed to read identity data")?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090084
85 // Verify the payload before using it.
Jooyung Han7a343f92021-09-08 22:53:11 +090086 let verified_data =
87 verify_payload(&metadata, saved_data.as_ref()).context("Payload verification failed")?;
88 if let Some(saved_data) = saved_data {
89 if saved_data == verified_data {
90 info!("Saved data is verified.");
Jiyong Parkbb4a9872021-09-06 15:59:21 +090091 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +090092 bail!("Detected an update of the payload which isn't supported yet.");
Jiyong Parkbb4a9872021-09-06 15:59:21 +090093 }
94 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +090095 info!("Saving verified data.");
96 instance.write_microdroid_data(&verified_data).context("Failed to write identity data")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +090097 }
98
Jooyung Hana6d11eb2021-09-10 11:48:05 +090099 // Before reading a file from the APK, start zipfuse
100 system_properties::write("ctl.start", "zipfuse")?;
Jiyong Park21ce2c52021-08-28 02:32:17 +0900101
Inseob Kim7f61fe72021-08-20 20:50:47 +0900102 let service = get_vms_rpc_binder().expect("cannot connect to VirtualMachineService");
Jooyung Han74573482021-06-08 17:10:21 +0900103 if !metadata.payload_config_path.is_empty() {
Jooyung Han634e2d72021-06-10 16:27:38 +0900104 let config = load_config(Path::new(&metadata.payload_config_path))?;
105
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000106 let fake_secret = "This is a placeholder for a value that is derived from the images that are loaded in the VM.";
Joel Galenson482704c2021-07-29 15:53:53 -0700107 if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000108 warn!("failed to set ro.vmsecret.keymint: {}", err);
109 }
110
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900111 // Wait until apex config is done. (e.g. linker configuration for apexes)
Jooyung Han634e2d72021-06-10 16:27:38 +0900112 // TODO(jooyung): wait until sys.boot_completed?
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900113 wait_for_apex_config_done()?;
114
Jooyung Han347d9f22021-05-28 00:05:14 +0900115 if let Some(main_task) = &config.task {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900116 exec_task(main_task, &service).map_err(|e| {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900117 error!("failed to execute task: {}", e);
118 e
119 })?;
Jooyung Han347d9f22021-05-28 00:05:14 +0900120 }
121 }
122
123 Ok(())
124}
125
Jooyung Han7a343f92021-09-08 22:53:11 +0900126// Verify payload before executing it. For APK payload, Full verification (which is slow) is done
127// when the root_hash values from the idsig file and the instance disk are different. This function
128// returns the verified root hash (for APK payload) and pubkeys (for APEX payloads) that can be
129// saved to the instance disk.
130fn verify_payload(
131 metadata: &Metadata,
132 saved_data: Option<&MicrodroidData>,
133) -> Result<MicrodroidData> {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900134 let start_time = SystemTime::now();
135
Jooyung Han7a343f92021-09-08 22:53:11 +0900136 let root_hash = saved_data.map(|d| &d.apk_data.root_hash);
Jiyong Parkf7dea252021-09-08 01:42:54 +0900137 let root_hash_from_idsig = get_apk_root_hash_from_idsig()?;
138 let root_hash_trustful = root_hash == Some(&root_hash_from_idsig);
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900139
Jiyong Parkf7dea252021-09-08 01:42:54 +0900140 // If root_hash can be trusted, pass it to apkdmverity so that it uses the passed root_hash
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900141 // instead of the value read from the idsig file.
Jiyong Parkf7dea252021-09-08 01:42:54 +0900142 if root_hash_trustful {
143 let root_hash = to_hex_string(root_hash.unwrap());
144 system_properties::write("microdroid_manager.apk_root_hash", &root_hash)?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900145 }
146
147 // Start apkdmverity and wait for the dm-verify block
148 system_properties::write("ctl.start", "apkdmverity")?;
Jooyung Han7a343f92021-09-08 22:53:11 +0900149
Jooyung Hanc8deb472021-09-13 13:48:25 +0900150 // While waiting for apkdmverity to mount APK, gathers public keys and root digests from
151 // APEX payload.
Jooyung Han7a343f92021-09-08 22:53:11 +0900152 let apex_data_from_payload = get_apex_data_from_payload(metadata)?;
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900153 if let Some(saved_data) = saved_data.map(|d| &d.apex_data) {
Jooyung Hanc8deb472021-09-13 13:48:25 +0900154 // We don't support APEX updates. (assuming that update will change root digest)
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900155 ensure!(saved_data == &apex_data_from_payload, "APEX payloads has changed.");
156 let apex_metadata = to_metadata(&apex_data_from_payload);
Jooyung Hanc8deb472021-09-13 13:48:25 +0900157 // Pass metadata(with public keys and root digests) to apexd so that it uses the passed
158 // metadata instead of the default one (/dev/block/by-name/payload-metadata)
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900159 OpenOptions::new()
160 .create_new(true)
161 .write(true)
162 .open("/apex/vm-payload-metadata")
163 .context("Failed to open /apex/vm-payload-metadata")
164 .and_then(|f| write_metadata(&apex_metadata, f))?;
165 }
166 // Start apexd to activate APEXes
167 system_properties::write("ctl.start", "apexd-vm")?;
Jooyung Han7a343f92021-09-08 22:53:11 +0900168
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900169 ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900170
Jiyong Parkf7dea252021-09-08 01:42:54 +0900171 // Do the full verification if the root_hash is un-trustful. This requires the full scanning of
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900172 // the APK file and therefore can be very slow if the APK is large. Note that this step is
Jiyong Parkf7dea252021-09-08 01:42:54 +0900173 // taken only when the root_hash is un-trustful which can be either when this is the first boot
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900174 // of the VM or APK was updated in the host.
175 // TODO(jooyung): consider multithreading to make this faster
Jiyong Parka41535b2021-09-10 19:31:48 +0900176 let apk_pubkey = if !root_hash_trustful {
177 verify(DM_MOUNTED_APK_PATH).context(format!("failed to verify {}", DM_MOUNTED_APK_PATH))?
178 } else {
179 get_public_key_der(DM_MOUNTED_APK_PATH)?
180 };
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900181
182 info!("payload verification successful. took {:#?}", start_time.elapsed().unwrap());
183
Jiyong Parkf7dea252021-09-08 01:42:54 +0900184 // At this point, we can ensure that the root_hash from the idsig file is trusted, either by
185 // fully verifying the APK or by comparing it with the saved root_hash.
Jooyung Han7a343f92021-09-08 22:53:11 +0900186 Ok(MicrodroidData {
Jiyong Parka41535b2021-09-10 19:31:48 +0900187 apk_data: ApkData { root_hash: root_hash_from_idsig, pubkey: apk_pubkey },
Jooyung Han7a343f92021-09-08 22:53:11 +0900188 apex_data: apex_data_from_payload,
189 })
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900190}
191
192// Waits until linker config is generated
193fn wait_for_apex_config_done() -> Result<()> {
194 let mut prop = PropertyWatcher::new(APEX_CONFIG_DONE_PROP)?;
195 loop {
196 prop.wait()?;
197 let val = system_properties::read(APEX_CONFIG_DONE_PROP)?;
198 if val == "true" {
199 break;
200 }
201 }
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900202 Ok(())
203}
204
Jiyong Parkf7dea252021-09-08 01:42:54 +0900205fn get_apk_root_hash_from_idsig() -> Result<Box<RootHash>> {
Jiyong Park21ce2c52021-08-28 02:32:17 +0900206 let mut idsig = File::open("/dev/block/by-name/microdroid-apk-idsig")?;
207 let idsig = V4Signature::from(&mut idsig)?;
208 Ok(idsig.hashing_info.raw_root_hash)
209}
210
Jooyung Han634e2d72021-06-10 16:27:38 +0900211fn load_config(path: &Path) -> Result<VmPayloadConfig> {
212 info!("loading config from {:?}...", path);
213 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
214 Ok(serde_json::from_reader(file)?)
215}
216
Jiyong Park8611a6c2021-07-09 18:17:44 +0900217/// Executes the given task. Stdout of the task is piped into the vsock stream to the
218/// virtualizationservice in the host side.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900219fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900220 info!("executing main task {:?}...", task);
Inseob Kim86ca0162021-10-20 02:21:02 +0000221 let mut command = build_command(task)?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900222
223 info!("notifying payload started");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000224 service.notifyPayloadStarted()?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900225
Inseob Kim86ca0162021-10-20 02:21:02 +0000226 let exit_status = command.spawn()?.wait()?;
Alan Stokes4eea5c72021-09-20 17:40:28 +0100227 if let Some(code) = exit_status.code() {
Inseob Kim2444af92021-08-31 01:22:50 +0900228 info!("notifying payload finished");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000229 service.notifyPayloadFinished(code)?;
Inseob Kim2444af92021-08-31 01:22:50 +0900230
231 if code == 0 {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900232 info!("task successfully finished");
Inseob Kim2444af92021-08-31 01:22:50 +0900233 } else {
234 error!("task exited with exit code: {}", code);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900235 }
Inseob Kim2444af92021-08-31 01:22:50 +0900236 } else {
Alan Stokes4eea5c72021-09-20 17:40:28 +0100237 error!("task terminated: {}", exit_status);
Jiyong Park038b73e2021-06-16 01:57:02 +0900238 }
Inseob Kim2444af92021-08-31 01:22:50 +0900239 Ok(())
Jooyung Han347d9f22021-05-28 00:05:14 +0900240}
Jooyung Han634e2d72021-06-10 16:27:38 +0900241
242fn build_command(task: &Task) -> Result<Command> {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900243 const VMADDR_CID_HOST: u32 = 2;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900244
245 let mut command = match task.type_ {
Jooyung Han634e2d72021-06-10 16:27:38 +0900246 TaskType::Executable => {
247 let mut command = Command::new(&task.command);
248 command.args(&task.args);
249 command
250 }
251 TaskType::MicrodroidLauncher => {
252 let mut command = Command::new("/system/bin/microdroid_launcher");
253 command.arg(find_library_path(&task.command)?).args(&task.args);
254 command
255 }
Inseob Kim7f61fe72021-08-20 20:50:47 +0900256 };
257
Inseob Kimd0587562021-09-01 21:27:32 +0900258 match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32) {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900259 Ok(stream) => {
260 // SAFETY: the ownership of the underlying file descriptor is transferred from stream
261 // to the file object, and then into the Command object. When the command is finished,
262 // the file descriptor is closed.
263 let file = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
264 command
265 .stdin(Stdio::from(file.try_clone()?))
266 .stdout(Stdio::from(file.try_clone()?))
267 .stderr(Stdio::from(file));
268 }
269 Err(e) => {
270 error!("failed to connect to virtualization service: {}", e);
271 // Don't fail hard here. Even if we failed to connect to the virtualizationservice,
272 // we keep executing the task. This can happen if the owner of the VM doesn't register
273 // callback to accept the stream. Use /dev/null as the stream so that the task can
274 // make progress without waiting for someone to consume the output.
275 command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
276 }
277 }
278
279 Ok(command)
Jooyung Han634e2d72021-06-10 16:27:38 +0900280}
281
282fn find_library_path(name: &str) -> Result<String> {
283 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
284 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
285 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
286 let path = format!("/mnt/apk/lib/{}/{}", abi, name);
287
288 let metadata = fs::metadata(&path)?;
289 if !metadata.is_file() {
290 bail!("{} is not a file", &path);
291 }
292
293 Ok(path)
294}
Jiyong Park21ce2c52021-08-28 02:32:17 +0900295
296fn to_hex_string(buf: &[u8]) -> String {
297 buf.iter().map(|b| format!("{:02X}", b)).collect()
298}