blob: 9a9a1f8718c611e9e21e6fe04dc961fb210bcef0 [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
Andrew Sculld64ae7d2022-10-05 17:41:43 +000017mod dice;
Jiyong Park21ce2c52021-08-28 02:32:17 +090018mod instance;
Jooyung Hanf48ceb42021-06-01 18:00:04 +090019mod ioutil;
Jooyung Han7a343f92021-09-08 22:53:11 +090020mod payload;
Keir Fraser933f0ac2022-10-12 08:23:28 +000021mod swap;
Alan Stokes1125e012023-10-13 12:31:10 +010022mod verify;
Alice Wang59a9e562022-10-04 15:24:10 +000023mod vm_payload_service;
Shikha Panwar95084df2023-07-22 11:47:45 +000024mod vm_secret;
Jooyung Han347d9f22021-05-28 00:05:14 +090025
Alan Stokes2bead0d2022-09-05 16:58:34 +010026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
David Brazdil73988ea2022-11-11 15:10:32 +000027use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Inseob Kim090b70b2022-11-16 20:01:14 +090028use android_system_virtualization_payload::aidl::android::system::virtualization::payload::IVmPayloadService::{
29 VM_APK_CONTENTS_PATH,
30 VM_PAYLOAD_SERVICE_SOCKET_NAME,
Shikha Panwarddc124b2022-11-28 19:17:54 +000031 ENCRYPTEDSTORE_MOUNTPOINT,
Inseob Kim090b70b2022-11-16 20:01:14 +090032};
Alan Stokes1125e012023-10-13 12:31:10 +010033
34use crate::dice::dice_derivation;
Alan Stokes03754962023-11-06 15:36:09 +000035use crate::instance::{InstanceDisk, MicrodroidData};
Alan Stokes1125e012023-10-13 12:31:10 +010036use crate::verify::verify_payload;
37use crate::vm_payload_service::register_vm_payload_service;
Jooyung Handd0a1732021-11-23 15:26:20 +090038use anyhow::{anyhow, bail, ensure, Context, Error, Result};
Alice Wang43c884b2022-10-24 09:42:40 +000039use binder::Strong;
Nikita Ioffee18cc132024-02-28 16:13:36 +000040use dice_driver::DiceDriver;
Alice Wang7e6c9352023-02-15 15:44:13 +000041use keystore2_crypto::ZVec;
Alan Stokes1125e012023-10-13 12:31:10 +010042use libc::VMADDR_CID_HOST;
43use log::{error, info};
Shikha Panwar185ba932024-03-12 22:35:09 +000044use microdroid_metadata::{Metadata, PayloadMetadata};
Alan Stokesfda70842023-12-20 17:50:14 +000045use microdroid_payload_config::{ApkConfig, OsConfig, Task, TaskType, VmPayloadConfig};
Frederick Mayleb5f7b6b2022-11-11 15:24:03 -080046use nix::sys::signal::Signal;
Alan Stokes03754962023-11-06 15:36:09 +000047use payload::load_metadata;
David Brazdila2125dd2022-12-14 16:37:44 +000048use rpcbinder::RpcSession;
Inseob Kim090b70b2022-11-16 20:01:14 +090049use rustutils::sockets::android_get_control_socket;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090050use rustutils::system_properties;
Joel Galenson482704c2021-07-29 15:53:53 -070051use rustutils::system_properties::PropertyWatcher;
Shikha Panwar0503cb02024-01-05 10:11:28 +000052use secretkeeper_comm::data_types::ID_SIZE;
Alan Stokes3ba10fd2022-10-06 15:46:51 +010053use std::borrow::Cow::{Borrowed, Owned};
Inseob Kim7ff121c2022-11-14 18:13:23 +090054use std::env;
Shikha Panwardef7ef92023-01-06 08:35:48 +000055use std::ffi::CString;
Alan Stokes1125e012023-10-13 12:31:10 +010056use std::fs::{self, create_dir, File, OpenOptions};
Jaewan Kim3124ef02023-03-23 19:25:20 +090057use std::io::{Read, Write};
Alan Stokes1125e012023-10-13 12:31:10 +010058use std::os::unix::io::{FromRawFd, OwnedFd};
Nikita Ioffe3452ee22022-12-15 00:31:56 +000059use std::os::unix::process::CommandExt;
Frederick Mayleb5f7b6b2022-11-11 15:24:03 -080060use std::os::unix::process::ExitStatusExt;
Jooyung Hanf48ceb42021-06-01 18:00:04 +090061use std::path::Path;
Inseob Kim217038e2021-11-25 11:15:06 +090062use std::process::{Child, Command, Stdio};
Jiyong Park8611a6c2021-07-09 18:17:44 +090063use std::str;
Alan Stokes1125e012023-10-13 12:31:10 +010064use std::time::Duration;
Shikha Panwar95084df2023-07-22 11:47:45 +000065use vm_secret::VmSecret;
Jooyung Han634e2d72021-06-10 16:27:38 +090066
67const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jaewan Kim1f0135b2024-01-31 14:59:47 +090068const AVF_STRICT_BOOT: &str = "/proc/device-tree/chosen/avf,strict-boot";
69const AVF_NEW_INSTANCE: &str = "/proc/device-tree/chosen/avf,new-instance";
70const AVF_DEBUG_POLICY_RAMDUMP: &str = "/proc/device-tree/avf/guest/common/ramdump";
Inseob Kime379e7d2022-07-22 18:55:18 +090071const DEBUG_MICRODROID_NO_VERIFIED_BOOT: &str =
Jaewan Kim1f0135b2024-01-31 14:59:47 +090072 "/proc/device-tree/virtualization/guest/debug-microdroid,no-verified-boot";
Shikha Panwar14abe442024-02-23 15:04:27 +000073const SECRETKEEPER_KEY: &str = "/proc/device-tree/avf/secretkeeper_public_key";
74const INSTANCE_ID_PATH: &str = "/proc/device-tree/avf/untrusted/instance-id";
Jooyung Han347d9f22021-05-28 00:05:14 +090075
Alan Stokes4fb201c2023-02-08 17:39:05 +000076const ENCRYPTEDSTORE_BIN: &str = "/system/bin/encryptedstore";
77const ZIPFUSE_BIN: &str = "/system/bin/zipfuse";
78
Jiyong Parkbb4a9872021-09-06 15:59:21 +090079const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
Seungjae Yoofa22bb02022-12-08 16:38:42 +090080const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable";
Jiyong Parkbb4a9872021-09-06 15:59:21 +090081
Inseob Kim11f40d02022-06-13 17:16:00 +090082// SYNC WITH virtualizationservice/src/crosvm.rs
83const FAILURE_SERIAL_DEVICE: &str = "/dev/ttyS1";
84
Shikha Panwar566c9672022-11-15 14:39:58 +000085const ENCRYPTEDSTORE_BACKING_DEVICE: &str = "/dev/block/by-name/encryptedstore";
Alice Wang62f7e642023-02-10 09:55:13 +000086const ENCRYPTEDSTORE_KEYSIZE: usize = 32;
Shikha Panwar566c9672022-11-15 14:39:58 +000087
Jooyung Handd0a1732021-11-23 15:26:20 +090088#[derive(thiserror::Error, Debug)]
89enum MicrodroidError {
Inseob Kim11f40d02022-06-13 17:16:00 +090090 #[error("Cannot connect to virtualization service: {0}")]
91 FailedToConnectToVirtualizationService(String),
Jooyung Handd0a1732021-11-23 15:26:20 +090092 #[error("Payload has changed: {0}")]
93 PayloadChanged(String),
94 #[error("Payload verification has failed: {0}")]
95 PayloadVerificationFailed(String),
Jooyung Han5c6d4172021-12-06 14:17:52 +090096 #[error("Payload config is invalid: {0}")]
Alan Stokesbbed8872023-10-19 13:17:12 +010097 PayloadInvalidConfig(String),
Jooyung Handd0a1732021-11-23 15:26:20 +090098}
99
Alan Stokes2bead0d2022-09-05 16:58:34 +0100100fn translate_error(err: &Error) -> (ErrorCode, String) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900101 if let Some(e) = err.downcast_ref::<MicrodroidError>() {
102 match e {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100103 MicrodroidError::PayloadChanged(msg) => (ErrorCode::PAYLOAD_CHANGED, msg.to_string()),
Jooyung Handd0a1732021-11-23 15:26:20 +0900104 MicrodroidError::PayloadVerificationFailed(msg) => {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100105 (ErrorCode::PAYLOAD_VERIFICATION_FAILED, msg.to_string())
Jooyung Handd0a1732021-11-23 15:26:20 +0900106 }
Alan Stokesbbed8872023-10-19 13:17:12 +0100107 MicrodroidError::PayloadInvalidConfig(msg) => {
108 (ErrorCode::PAYLOAD_INVALID_CONFIG, msg.to_string())
Alan Stokes2bead0d2022-09-05 16:58:34 +0100109 }
Inseob Kim11f40d02022-06-13 17:16:00 +0900110 // Connection failure won't be reported to VS; return the default value
111 MicrodroidError::FailedToConnectToVirtualizationService(msg) => {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100112 (ErrorCode::UNKNOWN, msg.to_string())
Inseob Kim11f40d02022-06-13 17:16:00 +0900113 }
Jooyung Handd0a1732021-11-23 15:26:20 +0900114 }
115 } else {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100116 (ErrorCode::UNKNOWN, err.to_string())
Jooyung Handd0a1732021-11-23 15:26:20 +0900117 }
118}
119
Inseob Kim11f40d02022-06-13 17:16:00 +0900120fn write_death_reason_to_serial(err: &Error) -> Result<()> {
121 let death_reason = if let Some(e) = err.downcast_ref::<MicrodroidError>() {
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100122 Borrowed(match e {
Inseob Kim11f40d02022-06-13 17:16:00 +0900123 MicrodroidError::FailedToConnectToVirtualizationService(_) => {
124 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE"
125 }
126 MicrodroidError::PayloadChanged(_) => "MICRODROID_PAYLOAD_HAS_CHANGED",
127 MicrodroidError::PayloadVerificationFailed(_) => {
128 "MICRODROID_PAYLOAD_VERIFICATION_FAILED"
129 }
Alan Stokesbbed8872023-10-19 13:17:12 +0100130 MicrodroidError::PayloadInvalidConfig(_) => "MICRODROID_INVALID_PAYLOAD_CONFIG",
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100131 })
Inseob Kim11f40d02022-06-13 17:16:00 +0900132 } else {
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100133 // Send context information back after a separator, to ease diagnosis.
134 // These errors occur before the payload runs, so this should not leak sensitive
135 // information.
136 Owned(format!("MICRODROID_UNKNOWN_RUNTIME_ERROR|{:?}", err))
Inseob Kim11f40d02022-06-13 17:16:00 +0900137 };
138
Pierre-Clément Tosid225af52023-09-15 15:59:20 +0100139 for chunk in death_reason.as_bytes().chunks(16) {
Inseob Kim11f40d02022-06-13 17:16:00 +0900140 // TODO(b/220071963): Sometimes, sending more than 16 bytes at once makes MM hang.
Pierre-Clément Tosid225af52023-09-15 15:59:20 +0100141 OpenOptions::new().read(false).write(true).open(FAILURE_SERIAL_DEVICE)?.write_all(chunk)?;
Inseob Kim11f40d02022-06-13 17:16:00 +0900142 }
143
144 Ok(())
145}
146
Shikha Panwar14abe442024-02-23 15:04:27 +0000147/// The (host allocated) instance_id can be found at node /avf/untrusted/ in the device tree.
148fn get_instance_id() -> Result<Option<[u8; ID_SIZE]>> {
149 let path = Path::new(INSTANCE_ID_PATH);
150 let instance_id = if path.exists() {
151 Some(
152 fs::read(path)?
153 .try_into()
154 .map_err(|x: Vec<_>| anyhow!("Expected {ID_SIZE} bytes, found {:?}", x.len()))?,
155 )
156 } else {
157 // TODO(b/325094712): x86 support for Device tree in nested guest is limited/broken/
158 // untested. So instance_id will not be present in cuttlefish.
159 None
160 };
161 Ok(instance_id)
162}
163
Inseob Kim437f1052022-06-21 11:30:22 +0900164fn main() -> Result<()> {
Inseob Kim7ff121c2022-11-14 18:13:23 +0900165 // If debuggable, print full backtrace to console log with stdio_to_kmsg
Alan Stokes1125e012023-10-13 12:31:10 +0100166 if is_debuggable()? {
Inseob Kim7ff121c2022-11-14 18:13:23 +0900167 env::set_var("RUST_BACKTRACE", "full");
168 }
169
Inseob Kim437f1052022-06-21 11:30:22 +0900170 scopeguard::defer! {
171 info!("Shutting down...");
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900172 if let Err(e) = system_properties::write("sys.powerctl", "shutdown") {
173 error!("failed to shutdown {:?}", e);
174 }
Jooyung Han311b1202021-09-14 22:00:16 +0900175 }
Inseob Kim437f1052022-06-21 11:30:22 +0900176
177 try_main().map_err(|e| {
178 error!("Failed with {:?}.", e);
179 if let Err(e) = write_death_reason_to_serial(&e) {
180 error!("Failed to write death reason {:?}", e);
181 }
182 e
183 })
Jooyung Han311b1202021-09-14 22:00:16 +0900184}
185
186fn try_main() -> Result<()> {
Jiyong Park2b6346d2023-06-19 13:37:42 +0900187 android_logger::init_once(
188 android_logger::Config::default()
189 .with_tag("microdroid_manager")
Jeff Vander Stoep57da1572024-01-31 10:52:16 +0100190 .with_max_level(log::LevelFilter::Info),
Jiyong Park2b6346d2023-06-19 13:37:42 +0900191 );
Jooyung Han347d9f22021-05-28 00:05:14 +0900192 info!("started.");
193
Alice Wangfd222fd2023-05-25 09:37:38 +0000194 // SAFETY: This is the only place we take the ownership of the fd of the vm payload service.
195 //
Alice Wang2a5306e2023-06-05 09:18:32 +0000196 // To ensure that the CLOEXEC flag is set on the file descriptor as early as possible,
197 // it is necessary to fetch the socket corresponding to vm_payload_service at the
198 // very beginning, as android_get_control_socket() sets the CLOEXEC flag on the file
199 // descriptor.
Alice Wangfd222fd2023-05-25 09:37:38 +0000200 let vm_payload_service_fd = unsafe { prepare_vm_payload_service_socket()? };
Inseob Kim090b70b2022-11-16 20:01:14 +0900201
Jiyong Park202856e2022-08-22 16:04:26 +0900202 load_crashkernel_if_supported().context("Failed to load crashkernel")?;
203
Alice Wangeff58392023-07-04 13:32:09 +0000204 swap::init_swap().context("Failed to initialize swap")?;
Keir Fraser933f0ac2022-10-12 08:23:28 +0000205 info!("swap enabled.");
206
Inseob Kim11f40d02022-06-13 17:16:00 +0900207 let service = get_vms_rpc_binder()
208 .context("cannot connect to VirtualMachineService")
209 .map_err(|e| MicrodroidError::FailedToConnectToVirtualizationService(e.to_string()))?;
Seungjae Yoofd9a0622022-10-14 10:01:29 +0900210
Alice Wangfd222fd2023-05-25 09:37:38 +0000211 match try_run_payload(&service, vm_payload_service_fd) {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900212 Ok(code) => {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900213 if code == 0 {
214 info!("task successfully finished");
215 } else {
216 error!("task exited with exit code: {}", code);
217 }
Shikha Panwardef7ef92023-01-06 08:35:48 +0000218 if let Err(e) = post_payload_work() {
219 error!(
220 "Failed to run post payload work. It is possible that certain tasks
221 like syncing encrypted store might be incomplete. Error: {:?}",
222 e
223 );
224 };
225
226 info!("notifying payload finished");
227 service.notifyPayloadFinished(code)?;
Jooyung Han5c6d4172021-12-06 14:17:52 +0900228 Ok(())
229 }
230 Err(err) => {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900231 let (error_code, message) = translate_error(&err);
232 service.notifyError(error_code, &message)?;
233 Err(err)
234 }
Jooyung Handd0a1732021-11-23 15:26:20 +0900235 }
236}
237
Shikha Panwar185ba932024-03-12 22:35:09 +0000238fn verify_payload_with_instance_img(
239 metadata: &Metadata,
240 dice: &DiceDriver,
241) -> Result<MicrodroidData> {
Jooyung Han311b1202021-09-14 22:00:16 +0900242 let mut instance = InstanceDisk::new().context("Failed to load instance.img")?;
Shikha Panwar185ba932024-03-12 22:35:09 +0000243 let saved_data = instance.read_microdroid_data(dice).context("Failed to read identity data")?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900244
Andrew Scullab72ec52022-03-14 09:10:52 +0000245 if is_strict_boot() {
246 // Provisioning must happen on the first boot and never again.
247 if is_new_instance() {
248 ensure!(
249 saved_data.is_none(),
Alan Stokesbbed8872023-10-19 13:17:12 +0100250 MicrodroidError::PayloadInvalidConfig(
251 "Found instance data on first boot.".to_string()
252 )
Andrew Scullab72ec52022-03-14 09:10:52 +0000253 );
254 } else {
255 ensure!(
256 saved_data.is_some(),
Alan Stokesbbed8872023-10-19 13:17:12 +0100257 MicrodroidError::PayloadInvalidConfig("Instance data not found.".to_string())
Andrew Scullab72ec52022-03-14 09:10:52 +0000258 );
259 };
260 }
261
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900262 // Verify the payload before using it.
Shikha Panwar185ba932024-03-12 22:35:09 +0000263 let extracted_data = verify_payload(metadata, saved_data.as_ref())
Inseob Kim11f40d02022-06-13 17:16:00 +0900264 .context("Payload verification failed")
265 .map_err(|e| MicrodroidError::PayloadVerificationFailed(e.to_string()))?;
Inseob Kime379e7d2022-07-22 18:55:18 +0900266
267 // In case identity is ignored (by debug policy), we should reuse existing payload data, even
268 // when the payload is changed. This is to keep the derived secret same as before.
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000269 let instance_data = if let Some(saved_data) = saved_data {
Inseob Kime379e7d2022-07-22 18:55:18 +0900270 if !is_verified_boot() {
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000271 if saved_data != extracted_data {
Inseob Kime379e7d2022-07-22 18:55:18 +0900272 info!("Detected an update of the payload, but continue (regarding debug policy)")
273 }
274 } else {
275 ensure!(
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000276 saved_data == extracted_data,
Inseob Kime379e7d2022-07-22 18:55:18 +0900277 MicrodroidError::PayloadChanged(String::from(
278 "Detected an update of the payload which isn't supported yet."
279 ))
280 );
281 info!("Saved data is verified.");
282 }
283 saved_data
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900284 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +0900285 info!("Saving verified data.");
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000286 instance
Shikha Panwar185ba932024-03-12 22:35:09 +0000287 .write_microdroid_data(&extracted_data, dice)
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000288 .context("Failed to write identity data")?;
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000289 extracted_data
Inseob Kime379e7d2022-07-22 18:55:18 +0900290 };
Shikha Panwar185ba932024-03-12 22:35:09 +0000291 Ok(instance_data)
292}
293
294fn try_run_payload(
295 service: &Strong<dyn IVirtualMachineService>,
296 vm_payload_service_fd: OwnedFd,
297) -> Result<i32> {
298 let metadata = load_metadata().context("Failed to load payload metadata")?;
299 let dice = DiceDriver::new(Path::new("/dev/open-dice0"), is_strict_boot())
300 .context("Failed to load DICE")?;
301
302 // TODO(b/291306122): Checking with host about Secretkeeper support multiple times introduces
303 // a whole range of security vulnerability since host can give different answers. Guest should
304 // check only once and the same answer should be known to pVM Firmware and Microdroid.
305 let instance_data = if let Some(_sk) = vm_secret::is_sk_supported(service)? {
306 verify_payload(&metadata, None)?
307 } else {
308 verify_payload_with_instance_img(&metadata, &dice)?
309 };
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900310
Alan Stokes1f417c92022-09-29 15:13:28 +0100311 let payload_metadata = metadata.payload.ok_or_else(|| {
Alan Stokesbbed8872023-10-19 13:17:12 +0100312 MicrodroidError::PayloadInvalidConfig("No payload config in metadata".to_string())
Alan Stokes1f417c92022-09-29 15:13:28 +0100313 })?;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100314
Inseob Kimb2519c52022-04-14 02:10:09 +0900315 // To minimize the exposure to untrusted data, derive dice profile as soon as possible.
316 info!("DICE derivation for payload");
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000317 let dice_artifacts = dice_derivation(dice, &instance_data, &payload_metadata)?;
Shikha Panwar5d6a6752023-12-14 22:08:26 +0000318 let vm_secret =
Shikha Panwar14abe442024-02-23 15:04:27 +0000319 VmSecret::new(dice_artifacts, service).context("Failed to create VM secrets")?;
Shikha Panwar566c9672022-11-15 14:39:58 +0000320
Alan Stokes9a7f67e2023-11-07 09:37:40 +0000321 if cfg!(dice_changes) {
322 // Now that the DICE derivation is done, it's ok to allow payload code to run.
323
324 // Start apexd to activate APEXes. This may allow code within them to run.
325 system_properties::write("ctl.start", "apexd-vm")?;
326 }
327
Shikha Panwar566c9672022-11-15 14:39:58 +0000328 // Run encryptedstore binary to prepare the storage
329 let encryptedstore_child = if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() {
330 info!("Preparing encryptedstore ...");
Shikha Panwar95084df2023-07-22 11:47:45 +0000331 Some(prepare_encryptedstore(&vm_secret).context("encryptedstore run")?)
Shikha Panwar566c9672022-11-15 14:39:58 +0000332 } else {
333 None
334 };
Inseob Kimb2519c52022-04-14 02:10:09 +0900335
Alan Stokes960c9032022-12-07 16:53:45 +0000336 let mut zipfuse = Zipfuse::default();
337
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900338 // Before reading a file from the APK, start zipfuse
Alan Stokes960c9032022-12-07 16:53:45 +0000339 zipfuse.mount(
Alan Stokes60f82202022-10-07 16:40:07 +0100340 MountForExec::Allowed,
Inseob Kim217038e2021-11-25 11:15:06 +0900341 "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:system_file:s0",
Alan Stokes1125e012023-10-13 12:31:10 +0100342 Path::new(verify::DM_MOUNTED_APK_PATH),
Alice Wang6bbb6da2022-10-26 12:44:06 +0000343 Path::new(VM_APK_CONTENTS_PATH),
Alan Stokes960c9032022-12-07 16:53:45 +0000344 "microdroid_manager.apk.mounted".to_owned(),
345 )?;
Jiyong Park21ce2c52021-08-28 02:32:17 +0900346
Andrew Scull4d262dc2022-10-21 13:14:33 +0000347 // Restricted APIs are only allowed to be used by platform or test components. Infer this from
348 // the use of a VM config file since those can only be used by platform and test components.
349 let allow_restricted_apis = match payload_metadata {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000350 PayloadMetadata::ConfigPath(_) => true,
351 PayloadMetadata::Config(_) => false,
352 _ => false, // default is false for safety
Andrew Scull4d262dc2022-10-21 13:14:33 +0000353 };
354
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100355 let config = load_config(payload_metadata).context("Failed to load payload metadata")?;
Shikha Panwar6f03c942022-04-13 20:26:50 +0000356
Alan Stokes01b3ef02022-09-22 17:43:24 +0100357 let task = config
358 .task
359 .as_ref()
Alan Stokesbbed8872023-10-19 13:17:12 +0100360 .ok_or_else(|| MicrodroidError::PayloadInvalidConfig("No task in VM config".to_string()))?;
Alan Stokes01b3ef02022-09-22 17:43:24 +0100361
Alice Wang061478b2023-04-11 13:26:17 +0000362 ensure!(
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000363 config.extra_apks.len() == instance_data.extra_apks_data.len(),
Alice Wang061478b2023-04-11 13:26:17 +0000364 "config expects {} extra apks, but found {}",
365 config.extra_apks.len(),
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000366 instance_data.extra_apks_data.len()
Alice Wang061478b2023-04-11 13:26:17 +0000367 );
Alan Stokes960c9032022-12-07 16:53:45 +0000368 mount_extra_apks(&config, &mut zipfuse)?;
Jooyung Han634e2d72021-06-10 16:27:38 +0900369
Alan Stokes26efd192023-11-06 16:30:15 +0000370 register_vm_payload_service(
371 allow_restricted_apis,
372 service.clone(),
373 vm_secret,
374 vm_payload_service_fd,
375 )?;
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000376
Shikha Panwar1a6efcd2023-02-03 19:23:43 +0000377 // Set export_tombstones if enabled
Inseob Kimab1037d2023-02-08 17:03:31 +0900378 if should_export_tombstones(&config) {
Shikha Panwar1a6efcd2023-02-03 19:23:43 +0000379 // This property is read by tombstone_handler.
380 system_properties::write("microdroid_manager.export_tombstones.enabled", "1")
381 .context("set microdroid_manager.export_tombstones.enabled")?;
Inseob Kimcd9c1dd2022-07-13 17:13:45 +0900382 }
383
Alan Stokes26efd192023-11-06 16:30:15 +0000384 // Wait until apex config is done. (e.g. linker configuration for apexes)
385 wait_for_property_true(APEX_CONFIG_DONE_PROP).context("Failed waiting for apex config done")?;
386
387 // Trigger init post-fs-data. This will start authfs if we wask it to.
388 if config.enable_authfs {
389 system_properties::write("microdroid_manager.authfs.enabled", "1")
390 .context("failed to write microdroid_manager.authfs.enabled")?;
391 }
392 system_properties::write("microdroid_manager.config_done", "1")
393 .context("failed to write microdroid_manager.config_done")?;
394
Alan Stokes960c9032022-12-07 16:53:45 +0000395 // Wait until zipfuse has mounted the APKs so we can access the payload
396 zipfuse.wait_until_done()?;
Alan Stokes60f82202022-10-07 16:40:07 +0100397
Shikha Panwarddc124b2022-11-28 19:17:54 +0000398 // Wait for encryptedstore to finish mounting the storage (if enabled) before setting
399 // microdroid_manager.init_done. Reason is init stops uneventd after that.
400 // Encryptedstore, however requires ueventd
Shikha Panwar566c9672022-11-15 14:39:58 +0000401 if let Some(mut child) = encryptedstore_child {
402 let exitcode = child.wait().context("Wait for encryptedstore child")?;
403 ensure!(exitcode.success(), "Unable to prepare encrypted storage. Exitcode={}", exitcode);
404 }
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100405
Alan Stokes26efd192023-11-06 16:30:15 +0000406 // Wait for init to have finished booting.
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000407 wait_for_property_true("dev.bootcomplete").context("failed waiting for dev.bootcomplete")?;
Alan Stokes26efd192023-11-06 16:30:15 +0000408
409 // And then tell it we're done so unnecessary services can be shut down.
Shikha Panwar3f6f6a52022-11-29 17:28:36 +0000410 system_properties::write("microdroid_manager.init_done", "1")
411 .context("set microdroid_manager.init_done")?;
Inseob Kimc16b0cc2023-01-26 14:57:24 +0900412
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000413 info!("boot completed, time to run payload");
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100414 exec_task(task, service).context("Failed to run payload")
Alan Stokes01b3ef02022-09-22 17:43:24 +0100415}
416
Alan Stokes03754962023-11-06 15:36:09 +0000417fn post_payload_work() -> Result<()> {
418 // Sync the encrypted storage filesystem (flushes the filesystem caches).
419 if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() {
420 let mountpoint = CString::new(ENCRYPTEDSTORE_MOUNTPOINT).unwrap();
421
422 // SAFETY: `mountpoint` is a valid C string. `syncfs` and `close` are safe for any parameter
423 // values.
424 let ret = unsafe {
425 let dirfd = libc::open(
426 mountpoint.as_ptr(),
427 libc::O_DIRECTORY | libc::O_RDONLY | libc::O_CLOEXEC,
428 );
429 ensure!(dirfd >= 0, "Unable to open {:?}", mountpoint);
430 let ret = libc::syncfs(dirfd);
431 libc::close(dirfd);
432 ret
433 };
434 if ret != 0 {
435 error!("failed to sync encrypted storage.");
436 return Err(anyhow!(std::io::Error::last_os_error()));
437 }
438 }
439 Ok(())
440}
441
Alan Stokes03754962023-11-06 15:36:09 +0000442fn mount_extra_apks(config: &VmPayloadConfig, zipfuse: &mut Zipfuse) -> Result<()> {
443 // For now, only the number of apks is important, as the mount point and dm-verity name is fixed
444 for i in 0..config.extra_apks.len() {
445 let mount_dir = format!("/mnt/extra-apk/{i}");
446 create_dir(Path::new(&mount_dir)).context("Failed to create mount dir for extra apks")?;
447
448 let mount_for_exec =
449 if cfg!(multi_tenant) { MountForExec::Allowed } else { MountForExec::Disallowed };
450 // These run asynchronously in parallel - we wait later for them to complete.
451 zipfuse.mount(
452 mount_for_exec,
453 "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:extra_apk_file:s0",
454 Path::new(&format!("/dev/block/mapper/extra-apk-{i}")),
455 Path::new(&mount_dir),
456 format!("microdroid_manager.extra_apk.mounted.{i}"),
457 )?;
458 }
459
460 Ok(())
461}
462
463fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
464 // The host is running a VirtualMachineService for this VM on a port equal
465 // to the CID of this VM.
466 let port = vsock::get_local_cid().context("Could not determine local CID")?;
467 RpcSession::new()
468 .setup_vsock_client(VMADDR_CID_HOST, port)
469 .context("Could not connect to IVirtualMachineService")
470}
471
472/// Prepares a socket file descriptor for the vm payload service.
473///
474/// # Safety
475///
476/// The caller must ensure that this function is the only place that claims ownership
477/// of the file descriptor and it is called only once.
478unsafe fn prepare_vm_payload_service_socket() -> Result<OwnedFd> {
479 let raw_fd = android_get_control_socket(VM_PAYLOAD_SERVICE_SOCKET_NAME)?;
480
481 // Creating OwnedFd for stdio FDs is not safe.
482 if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) {
483 bail!("File descriptor {raw_fd} is standard I/O descriptor");
484 }
485 // SAFETY: Initializing OwnedFd for a RawFd created by the init.
486 // We checked that the integer value corresponds to a valid FD and that the caller
487 // ensures that this is the only place to claim its ownership.
488 Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) })
489}
490
491fn is_strict_boot() -> bool {
492 Path::new(AVF_STRICT_BOOT).exists()
493}
494
495fn is_new_instance() -> bool {
496 Path::new(AVF_NEW_INSTANCE).exists()
497}
498
499fn is_verified_boot() -> bool {
500 !Path::new(DEBUG_MICRODROID_NO_VERIFIED_BOOT).exists()
501}
502
503fn is_debuggable() -> Result<bool> {
504 Ok(system_properties::read_bool(DEBUGGABLE_PROP, true)?)
505}
506
507fn should_export_tombstones(config: &VmPayloadConfig) -> bool {
508 match config.export_tombstones {
509 Some(b) => b,
510 None => is_debuggable().unwrap_or(false),
511 }
512}
513
514/// Get debug policy value in bool. It's true iff the value is explicitly set to <1>.
515fn get_debug_policy_bool(path: &'static str) -> Result<Option<bool>> {
516 let mut file = match File::open(path) {
517 Ok(dp) => dp,
518 Err(e) => {
519 info!(
520 "Assumes that debug policy is disabled because failed to read debug policy ({e:?})"
521 );
522 return Ok(Some(false));
523 }
524 };
525 let mut log: [u8; 4] = Default::default();
526 file.read_exact(&mut log).context("Malformed data in {path}")?;
527 // DT spec uses big endian although Android is always little endian.
528 Ok(Some(u32::from_be_bytes(log) == 1))
529}
530
Alan Stokes60f82202022-10-07 16:40:07 +0100531enum MountForExec {
532 Allowed,
533 Disallowed,
534}
535
Alan Stokes960c9032022-12-07 16:53:45 +0000536#[derive(Default)]
537struct Zipfuse {
538 ready_properties: Vec<String>,
539}
540
541impl Zipfuse {
542 fn mount(
543 &mut self,
544 noexec: MountForExec,
545 option: &str,
546 zip_path: &Path,
547 mount_dir: &Path,
548 ready_prop: String,
549 ) -> Result<Child> {
550 let mut cmd = Command::new(ZIPFUSE_BIN);
551 if let MountForExec::Disallowed = noexec {
552 cmd.arg("--noexec");
553 }
Alan Stokes1294f942023-08-21 14:34:12 +0100554 // Let root own the files in APK, so we can access them, but set the group to
555 // allow all payloads to have access too.
556 let (uid, gid) = (microdroid_uids::ROOT_UID, microdroid_uids::MICRODROID_PAYLOAD_GID);
557
Alan Stokes960c9032022-12-07 16:53:45 +0000558 cmd.args(["-p", &ready_prop, "-o", option]);
Alan Stokes1294f942023-08-21 14:34:12 +0100559 cmd.args(["-u", &uid.to_string()]);
560 cmd.args(["-g", &gid.to_string()]);
Alan Stokes960c9032022-12-07 16:53:45 +0000561 cmd.arg(zip_path).arg(mount_dir);
562 self.ready_properties.push(ready_prop);
563 cmd.spawn().with_context(|| format!("Failed to run zipfuse for {mount_dir:?}"))
Andrew Scullcc339a12022-07-04 12:44:19 +0000564 }
Alan Stokes960c9032022-12-07 16:53:45 +0000565
566 fn wait_until_done(self) -> Result<()> {
567 // We check the last-started check first in the hope that by the time it is done
568 // all or most of the others will also be done, minimising the number of times we
569 // block on a property.
570 for property in self.ready_properties.into_iter().rev() {
571 wait_for_property_true(&property)
572 .with_context(|| format!("Failed waiting for {property}"))?;
573 }
574 Ok(())
Alan Stokes60f82202022-10-07 16:40:07 +0100575 }
Inseob Kim217038e2021-11-25 11:15:06 +0900576}
577
Alan Stokes60f82202022-10-07 16:40:07 +0100578fn wait_for_property_true(property_name: &str) -> Result<()> {
579 let mut prop = PropertyWatcher::new(property_name)?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900580 loop {
Andrew Walbrand9c766e2023-05-10 15:15:39 +0000581 prop.wait(None)?;
Alan Stokes60f82202022-10-07 16:40:07 +0100582 if system_properties::read_bool(property_name, false)? {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900583 break;
584 }
585 }
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900586 Ok(())
587}
588
Alan Stokes1f417c92022-09-29 15:13:28 +0100589fn load_config(payload_metadata: PayloadMetadata) -> Result<VmPayloadConfig> {
590 match payload_metadata {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000591 PayloadMetadata::ConfigPath(path) => {
Alan Stokes1f417c92022-09-29 15:13:28 +0100592 let path = Path::new(&path);
593 info!("loading config from {:?}...", path);
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100594 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)
595 .with_context(|| format!("Failed to read {:?}", path))?;
Alan Stokes1f417c92022-09-29 15:13:28 +0100596 Ok(serde_json::from_reader(file)?)
597 }
Ludovic Barman93ee3082023-06-20 12:18:43 +0000598 PayloadMetadata::Config(payload_config) => {
Alan Stokes1f417c92022-09-29 15:13:28 +0100599 let task = Task {
600 type_: TaskType::MicrodroidLauncher,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000601 command: payload_config.payload_binary_name,
Alan Stokes1f417c92022-09-29 15:13:28 +0100602 };
Alan Stokesfda70842023-12-20 17:50:14 +0000603 // We don't care about the paths, only the number of extra APKs really matters.
604 let extra_apks = (0..payload_config.extra_apk_count)
605 .map(|i| ApkConfig { path: format!("extra-apk-{i}") })
606 .collect();
Alan Stokes1f417c92022-09-29 15:13:28 +0100607 Ok(VmPayloadConfig {
608 os: OsConfig { name: "microdroid".to_owned() },
609 task: Some(task),
610 apexes: vec![],
Alan Stokesfda70842023-12-20 17:50:14 +0000611 extra_apks,
Alan Stokes1f417c92022-09-29 15:13:28 +0100612 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900613 export_tombstones: None,
Alan Stokes1f417c92022-09-29 15:13:28 +0100614 enable_authfs: false,
615 })
616 }
Ludovic Barman93ee3082023-06-20 12:18:43 +0000617 _ => bail!("Failed to match config against a config type."),
Alan Stokes1f417c92022-09-29 15:13:28 +0100618 }
Jooyung Han634e2d72021-06-10 16:27:38 +0900619}
620
Jaewan Kim3124ef02023-03-23 19:25:20 +0900621/// Loads the crashkernel into memory using kexec if debuggable or debug policy says so.
622/// The VM should be loaded with `crashkernel=' parameter in the cmdline to allocate memory
623/// for crashkernel.
Jiyong Park202856e2022-08-22 16:04:26 +0900624fn load_crashkernel_if_supported() -> Result<()> {
625 let supported = std::fs::read_to_string("/proc/cmdline")?.contains(" crashkernel=");
626 info!("ramdump supported: {}", supported);
Jaewan Kim3124ef02023-03-23 19:25:20 +0900627
628 if !supported {
629 return Ok(());
630 }
631
Alan Stokes1125e012023-10-13 12:31:10 +0100632 let debuggable = is_debuggable()?;
Jaewan Kim3124ef02023-03-23 19:25:20 +0900633 let ramdump = get_debug_policy_bool(AVF_DEBUG_POLICY_RAMDUMP)?.unwrap_or_default();
634 let requested = debuggable | ramdump;
635
636 if requested {
Jiyong Park202856e2022-08-22 16:04:26 +0900637 let status = Command::new("/system/bin/kexec_load").status()?;
638 if !status.success() {
639 return Err(anyhow!("Failed to load crashkernel: {:?}", status));
640 }
Jaewan Kim3124ef02023-03-23 19:25:20 +0900641 info!("ramdump is loaded: debuggable={debuggable}, ramdump={ramdump}");
Jiyong Park202856e2022-08-22 16:04:26 +0900642 }
643 Ok(())
644}
645
Inseob Kim090b70b2022-11-16 20:01:14 +0900646/// Executes the given task.
Jooyung Han5c6d4172021-12-06 14:17:52 +0900647fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<i32> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900648 info!("executing main task {:?}...", task);
David Brazdil451cc962022-10-14 14:08:12 +0100649 let mut command = match task.type_ {
Alan Stokes1294f942023-08-21 14:34:12 +0100650 TaskType::Executable => {
Alan Stokes679ddf32023-09-01 11:14:48 +0100651 // TODO(b/297501338): Figure out how to handle non-root for system payloads.
Alan Stokes1294f942023-08-21 14:34:12 +0100652 Command::new(&task.command)
653 }
David Brazdil451cc962022-10-14 14:08:12 +0100654 TaskType::MicrodroidLauncher => {
655 let mut command = Command::new("/system/bin/microdroid_launcher");
656 command.arg(find_library_path(&task.command)?);
Alan Stokes1294f942023-08-21 14:34:12 +0100657 command.uid(microdroid_uids::MICRODROID_PAYLOAD_UID);
658 command.gid(microdroid_uids::MICRODROID_PAYLOAD_GID);
David Brazdil451cc962022-10-14 14:08:12 +0100659 command
660 }
661 };
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000662
Andrew Walbranaac68302023-07-21 19:05:34 +0100663 // SAFETY: We are not accessing any resource of the parent process. This means we can't make any
664 // log calls inside the closure.
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000665 unsafe {
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000666 command.pre_exec(|| {
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000667 // It is OK to continue with payload execution even if the calls below fail, since
668 // whether process can use a capability is controlled by the SELinux. Dropping the
669 // capabilities here is just another defense-in-depth layer.
Andrew Walbranaac68302023-07-21 19:05:34 +0100670 let _ = cap::drop_inheritable_caps();
671 let _ = cap::drop_bounding_set();
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000672 Ok(())
673 });
674 }
675
Inseob Kim090b70b2022-11-16 20:01:14 +0900676 command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
Inseob Kim7f61fe72021-08-20 20:50:47 +0900677
678 info!("notifying payload started");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000679 service.notifyPayloadStarted()?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900680
Inseob Kim86ca0162021-10-20 02:21:02 +0000681 let exit_status = command.spawn()?.wait()?;
Frederick Mayleb5f7b6b2022-11-11 15:24:03 -0800682 match exit_status.code() {
683 Some(exit_code) => Ok(exit_code),
684 None => Err(match exit_status.signal() {
685 Some(signal) => anyhow!(
686 "Payload exited due to signal: {} ({})",
687 signal,
688 Signal::try_from(signal).map_or("unknown", |s| s.as_str())
689 ),
690 None => anyhow!("Payload has neither exit code nor signal"),
691 }),
692 }
Jooyung Han347d9f22021-05-28 00:05:14 +0900693}
Jooyung Han634e2d72021-06-10 16:27:38 +0900694
Jooyung Han634e2d72021-06-10 16:27:38 +0900695fn find_library_path(name: &str) -> Result<String> {
696 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
697 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
698 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
Alice Wang6bbb6da2022-10-26 12:44:06 +0000699 let path = format!("{}/lib/{}/{}", VM_APK_CONTENTS_PATH, abi, name);
Jooyung Han634e2d72021-06-10 16:27:38 +0900700
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100701 let metadata = fs::metadata(&path).with_context(|| format!("Unable to access {}", path))?;
Jooyung Han634e2d72021-06-10 16:27:38 +0900702 if !metadata.is_file() {
703 bail!("{} is not a file", &path);
704 }
705
706 Ok(path)
707}
Jiyong Park21ce2c52021-08-28 02:32:17 +0900708
Shikha Panwar95084df2023-07-22 11:47:45 +0000709fn prepare_encryptedstore(vm_secret: &VmSecret) -> Result<Child> {
Alice Wang7e6c9352023-02-15 15:44:13 +0000710 let mut key = ZVec::new(ENCRYPTEDSTORE_KEYSIZE)?;
Shikha Panwar3d3a70a2023-08-21 20:02:08 +0000711 vm_secret.derive_encryptedstore_key(&mut key)?;
Shikha Panwar566c9672022-11-15 14:39:58 +0000712 let mut cmd = Command::new(ENCRYPTEDSTORE_BIN);
713 cmd.arg("--blkdevice")
714 .arg(ENCRYPTEDSTORE_BACKING_DEVICE)
715 .arg("--key")
716 .arg(hex::encode(&*key))
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000717 .args(["--mountpoint", ENCRYPTEDSTORE_MOUNTPOINT])
Shikha Panwar566c9672022-11-15 14:39:58 +0000718 .spawn()
719 .context("encryptedstore failed")
720}