blob: 1b41e58e0cdc53e48a8091d756eadb607eb8280a [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;
Alan Stokes1125e012023-10-13 12:31:10 +010018mod dice_driver;
Jiyong Park21ce2c52021-08-28 02:32:17 +090019mod instance;
Jooyung Hanf48ceb42021-06-01 18:00:04 +090020mod ioutil;
Jooyung Han7a343f92021-09-08 22:53:11 +090021mod payload;
Keir Fraser933f0ac2022-10-12 08:23:28 +000022mod swap;
Alan Stokes1125e012023-10-13 12:31:10 +010023mod verify;
Alice Wang59a9e562022-10-04 15:24:10 +000024mod vm_payload_service;
Shikha Panwar95084df2023-07-22 11:47:45 +000025mod vm_secret;
Jooyung Han347d9f22021-05-28 00:05:14 +090026
Alan Stokes2bead0d2022-09-05 16:58:34 +010027use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode;
David Brazdil73988ea2022-11-11 15:10:32 +000028use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService;
Inseob Kim090b70b2022-11-16 20:01:14 +090029use android_system_virtualization_payload::aidl::android::system::virtualization::payload::IVmPayloadService::{
30 VM_APK_CONTENTS_PATH,
31 VM_PAYLOAD_SERVICE_SOCKET_NAME,
Shikha Panwarddc124b2022-11-28 19:17:54 +000032 ENCRYPTEDSTORE_MOUNTPOINT,
Inseob Kim090b70b2022-11-16 20:01:14 +090033};
Alan Stokes1125e012023-10-13 12:31:10 +010034
35use crate::dice::dice_derivation;
36use crate::dice_driver::DiceDriver;
Alan Stokes03754962023-11-06 15:36:09 +000037use crate::instance::{InstanceDisk, MicrodroidData};
Alan Stokes1125e012023-10-13 12:31:10 +010038use crate::verify::verify_payload;
39use crate::vm_payload_service::register_vm_payload_service;
Jooyung Handd0a1732021-11-23 15:26:20 +090040use anyhow::{anyhow, bail, ensure, Context, Error, Result};
Alice Wang43c884b2022-10-24 09:42:40 +000041use binder::Strong;
Alice Wang7e6c9352023-02-15 15:44:13 +000042use keystore2_crypto::ZVec;
Alan Stokes1125e012023-10-13 12:31:10 +010043use libc::VMADDR_CID_HOST;
44use log::{error, info};
Alan Stokes03754962023-11-06 15:36:09 +000045use microdroid_metadata::PayloadMetadata;
Seungjae Yoofd9a0622022-10-14 10:01:29 +090046use microdroid_payload_config::{OsConfig, Task, TaskType, VmPayloadConfig};
Frederick Mayleb5f7b6b2022-11-11 15:24:03 -080047use nix::sys::signal::Signal;
Alan Stokes03754962023-11-06 15:36:09 +000048use payload::load_metadata;
David Brazdila2125dd2022-12-14 16:37:44 +000049use rpcbinder::RpcSession;
Inseob Kim090b70b2022-11-16 20:01:14 +090050use rustutils::sockets::android_get_control_socket;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090051use rustutils::system_properties;
Joel Galenson482704c2021-07-29 15:53:53 -070052use rustutils::system_properties::PropertyWatcher;
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);
Andrew Scullab72ec52022-03-14 09:10:52 +000068const AVF_STRICT_BOOT: &str = "/sys/firmware/devicetree/base/chosen/avf,strict-boot";
69const AVF_NEW_INSTANCE: &str = "/sys/firmware/devicetree/base/chosen/avf,new-instance";
Jaewan Kim3124ef02023-03-23 19:25:20 +090070const AVF_DEBUG_POLICY_RAMDUMP: &str = "/sys/firmware/devicetree/base/avf/guest/common/ramdump";
Inseob Kime379e7d2022-07-22 18:55:18 +090071const DEBUG_MICRODROID_NO_VERIFIED_BOOT: &str =
72 "/sys/firmware/devicetree/base/virtualization/guest/debug-microdroid,no-verified-boot";
Jooyung Han347d9f22021-05-28 00:05:14 +090073
Alan Stokes4fb201c2023-02-08 17:39:05 +000074const ENCRYPTEDSTORE_BIN: &str = "/system/bin/encryptedstore";
75const ZIPFUSE_BIN: &str = "/system/bin/zipfuse";
76
Jiyong Parkbb4a9872021-09-06 15:59:21 +090077const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
Seungjae Yoofa22bb02022-12-08 16:38:42 +090078const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable";
Jiyong Parkbb4a9872021-09-06 15:59:21 +090079
Inseob Kim11f40d02022-06-13 17:16:00 +090080// SYNC WITH virtualizationservice/src/crosvm.rs
81const FAILURE_SERIAL_DEVICE: &str = "/dev/ttyS1";
82
Shikha Panwar566c9672022-11-15 14:39:58 +000083const ENCRYPTEDSTORE_BACKING_DEVICE: &str = "/dev/block/by-name/encryptedstore";
Alice Wang62f7e642023-02-10 09:55:13 +000084const ENCRYPTEDSTORE_KEYSIZE: usize = 32;
Shikha Panwar566c9672022-11-15 14:39:58 +000085
Jooyung Handd0a1732021-11-23 15:26:20 +090086#[derive(thiserror::Error, Debug)]
87enum MicrodroidError {
Inseob Kim11f40d02022-06-13 17:16:00 +090088 #[error("Cannot connect to virtualization service: {0}")]
89 FailedToConnectToVirtualizationService(String),
Jooyung Handd0a1732021-11-23 15:26:20 +090090 #[error("Payload has changed: {0}")]
91 PayloadChanged(String),
92 #[error("Payload verification has failed: {0}")]
93 PayloadVerificationFailed(String),
Jooyung Han5c6d4172021-12-06 14:17:52 +090094 #[error("Payload config is invalid: {0}")]
Alan Stokesbbed8872023-10-19 13:17:12 +010095 PayloadInvalidConfig(String),
Jooyung Handd0a1732021-11-23 15:26:20 +090096}
97
Alan Stokes2bead0d2022-09-05 16:58:34 +010098fn translate_error(err: &Error) -> (ErrorCode, String) {
Jooyung Handd0a1732021-11-23 15:26:20 +090099 if let Some(e) = err.downcast_ref::<MicrodroidError>() {
100 match e {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100101 MicrodroidError::PayloadChanged(msg) => (ErrorCode::PAYLOAD_CHANGED, msg.to_string()),
Jooyung Handd0a1732021-11-23 15:26:20 +0900102 MicrodroidError::PayloadVerificationFailed(msg) => {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100103 (ErrorCode::PAYLOAD_VERIFICATION_FAILED, msg.to_string())
Jooyung Handd0a1732021-11-23 15:26:20 +0900104 }
Alan Stokesbbed8872023-10-19 13:17:12 +0100105 MicrodroidError::PayloadInvalidConfig(msg) => {
106 (ErrorCode::PAYLOAD_INVALID_CONFIG, msg.to_string())
Alan Stokes2bead0d2022-09-05 16:58:34 +0100107 }
Inseob Kim11f40d02022-06-13 17:16:00 +0900108
109 // Connection failure won't be reported to VS; return the default value
110 MicrodroidError::FailedToConnectToVirtualizationService(msg) => {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100111 (ErrorCode::UNKNOWN, msg.to_string())
Inseob Kim11f40d02022-06-13 17:16:00 +0900112 }
Jooyung Handd0a1732021-11-23 15:26:20 +0900113 }
114 } else {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100115 (ErrorCode::UNKNOWN, err.to_string())
Jooyung Handd0a1732021-11-23 15:26:20 +0900116 }
117}
118
Inseob Kim11f40d02022-06-13 17:16:00 +0900119fn write_death_reason_to_serial(err: &Error) -> Result<()> {
120 let death_reason = if let Some(e) = err.downcast_ref::<MicrodroidError>() {
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100121 Borrowed(match e {
Inseob Kim11f40d02022-06-13 17:16:00 +0900122 MicrodroidError::FailedToConnectToVirtualizationService(_) => {
123 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE"
124 }
125 MicrodroidError::PayloadChanged(_) => "MICRODROID_PAYLOAD_HAS_CHANGED",
126 MicrodroidError::PayloadVerificationFailed(_) => {
127 "MICRODROID_PAYLOAD_VERIFICATION_FAILED"
128 }
Alan Stokesbbed8872023-10-19 13:17:12 +0100129 MicrodroidError::PayloadInvalidConfig(_) => "MICRODROID_INVALID_PAYLOAD_CONFIG",
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100130 })
Inseob Kim11f40d02022-06-13 17:16:00 +0900131 } else {
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100132 // Send context information back after a separator, to ease diagnosis.
133 // These errors occur before the payload runs, so this should not leak sensitive
134 // information.
135 Owned(format!("MICRODROID_UNKNOWN_RUNTIME_ERROR|{:?}", err))
Inseob Kim11f40d02022-06-13 17:16:00 +0900136 };
137
Pierre-Clément Tosid225af52023-09-15 15:59:20 +0100138 for chunk in death_reason.as_bytes().chunks(16) {
Inseob Kim11f40d02022-06-13 17:16:00 +0900139 // TODO(b/220071963): Sometimes, sending more than 16 bytes at once makes MM hang.
Pierre-Clément Tosid225af52023-09-15 15:59:20 +0100140 OpenOptions::new().read(false).write(true).open(FAILURE_SERIAL_DEVICE)?.write_all(chunk)?;
Inseob Kim11f40d02022-06-13 17:16:00 +0900141 }
142
143 Ok(())
144}
145
Inseob Kim437f1052022-06-21 11:30:22 +0900146fn main() -> Result<()> {
Inseob Kim7ff121c2022-11-14 18:13:23 +0900147 // If debuggable, print full backtrace to console log with stdio_to_kmsg
Alan Stokes1125e012023-10-13 12:31:10 +0100148 if is_debuggable()? {
Inseob Kim7ff121c2022-11-14 18:13:23 +0900149 env::set_var("RUST_BACKTRACE", "full");
150 }
151
Inseob Kim437f1052022-06-21 11:30:22 +0900152 scopeguard::defer! {
153 info!("Shutting down...");
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900154 if let Err(e) = system_properties::write("sys.powerctl", "shutdown") {
155 error!("failed to shutdown {:?}", e);
156 }
Jooyung Han311b1202021-09-14 22:00:16 +0900157 }
Inseob Kim437f1052022-06-21 11:30:22 +0900158
159 try_main().map_err(|e| {
160 error!("Failed with {:?}.", e);
161 if let Err(e) = write_death_reason_to_serial(&e) {
162 error!("Failed to write death reason {:?}", e);
163 }
164 e
165 })
Jooyung Han311b1202021-09-14 22:00:16 +0900166}
167
168fn try_main() -> Result<()> {
Jiyong Park2b6346d2023-06-19 13:37:42 +0900169 android_logger::init_once(
170 android_logger::Config::default()
171 .with_tag("microdroid_manager")
172 .with_min_level(log::Level::Info),
173 );
Jooyung Han347d9f22021-05-28 00:05:14 +0900174 info!("started.");
175
Alice Wangfd222fd2023-05-25 09:37:38 +0000176 // SAFETY: This is the only place we take the ownership of the fd of the vm payload service.
177 //
Alice Wang2a5306e2023-06-05 09:18:32 +0000178 // To ensure that the CLOEXEC flag is set on the file descriptor as early as possible,
179 // it is necessary to fetch the socket corresponding to vm_payload_service at the
180 // very beginning, as android_get_control_socket() sets the CLOEXEC flag on the file
181 // descriptor.
Alice Wangfd222fd2023-05-25 09:37:38 +0000182 let vm_payload_service_fd = unsafe { prepare_vm_payload_service_socket()? };
Inseob Kim090b70b2022-11-16 20:01:14 +0900183
Jiyong Park202856e2022-08-22 16:04:26 +0900184 load_crashkernel_if_supported().context("Failed to load crashkernel")?;
185
Alice Wangeff58392023-07-04 13:32:09 +0000186 swap::init_swap().context("Failed to initialize swap")?;
Keir Fraser933f0ac2022-10-12 08:23:28 +0000187 info!("swap enabled.");
188
Inseob Kim11f40d02022-06-13 17:16:00 +0900189 let service = get_vms_rpc_binder()
190 .context("cannot connect to VirtualMachineService")
191 .map_err(|e| MicrodroidError::FailedToConnectToVirtualizationService(e.to_string()))?;
Seungjae Yoofd9a0622022-10-14 10:01:29 +0900192
Alice Wangfd222fd2023-05-25 09:37:38 +0000193 match try_run_payload(&service, vm_payload_service_fd) {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900194 Ok(code) => {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900195 if code == 0 {
196 info!("task successfully finished");
197 } else {
198 error!("task exited with exit code: {}", code);
199 }
Shikha Panwardef7ef92023-01-06 08:35:48 +0000200 if let Err(e) = post_payload_work() {
201 error!(
202 "Failed to run post payload work. It is possible that certain tasks
203 like syncing encrypted store might be incomplete. Error: {:?}",
204 e
205 );
206 };
207
208 info!("notifying payload finished");
209 service.notifyPayloadFinished(code)?;
Jooyung Han5c6d4172021-12-06 14:17:52 +0900210 Ok(())
211 }
212 Err(err) => {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900213 let (error_code, message) = translate_error(&err);
214 service.notifyError(error_code, &message)?;
215 Err(err)
216 }
Jooyung Handd0a1732021-11-23 15:26:20 +0900217 }
218}
219
Alice Wangfd222fd2023-05-25 09:37:38 +0000220fn try_run_payload(
221 service: &Strong<dyn IVirtualMachineService>,
222 vm_payload_service_fd: OwnedFd,
223) -> Result<i32> {
Jooyung Han311b1202021-09-14 22:00:16 +0900224 let metadata = load_metadata().context("Failed to load payload metadata")?;
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000225 let dice = DiceDriver::new(Path::new("/dev/open-dice0")).context("Failed to load DICE")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900226
Jooyung Han311b1202021-09-14 22:00:16 +0900227 let mut instance = InstanceDisk::new().context("Failed to load instance.img")?;
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000228 let saved_data =
229 instance.read_microdroid_data(&dice).context("Failed to read identity data")?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900230
Andrew Scullab72ec52022-03-14 09:10:52 +0000231 if is_strict_boot() {
232 // Provisioning must happen on the first boot and never again.
233 if is_new_instance() {
234 ensure!(
235 saved_data.is_none(),
Alan Stokesbbed8872023-10-19 13:17:12 +0100236 MicrodroidError::PayloadInvalidConfig(
237 "Found instance data on first boot.".to_string()
238 )
Andrew Scullab72ec52022-03-14 09:10:52 +0000239 );
240 } else {
241 ensure!(
242 saved_data.is_some(),
Alan Stokesbbed8872023-10-19 13:17:12 +0100243 MicrodroidError::PayloadInvalidConfig("Instance data not found.".to_string())
Andrew Scullab72ec52022-03-14 09:10:52 +0000244 );
245 };
246 }
247
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900248 // Verify the payload before using it.
Inseob Kim11f40d02022-06-13 17:16:00 +0900249 let verified_data = verify_payload(&metadata, saved_data.as_ref())
250 .context("Payload verification failed")
251 .map_err(|e| MicrodroidError::PayloadVerificationFailed(e.to_string()))?;
Inseob Kime379e7d2022-07-22 18:55:18 +0900252
253 // In case identity is ignored (by debug policy), we should reuse existing payload data, even
254 // when the payload is changed. This is to keep the derived secret same as before.
255 let verified_data = if let Some(saved_data) = saved_data {
256 if !is_verified_boot() {
257 if saved_data != verified_data {
258 info!("Detected an update of the payload, but continue (regarding debug policy)")
259 }
260 } else {
261 ensure!(
262 saved_data == verified_data,
263 MicrodroidError::PayloadChanged(String::from(
264 "Detected an update of the payload which isn't supported yet."
265 ))
266 );
267 info!("Saved data is verified.");
268 }
269 saved_data
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900270 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +0900271 info!("Saving verified data.");
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000272 instance
273 .write_microdroid_data(&verified_data, &dice)
274 .context("Failed to write identity data")?;
Inseob Kime379e7d2022-07-22 18:55:18 +0900275 verified_data
276 };
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900277
Alan Stokes1f417c92022-09-29 15:13:28 +0100278 let payload_metadata = metadata.payload.ok_or_else(|| {
Alan Stokesbbed8872023-10-19 13:17:12 +0100279 MicrodroidError::PayloadInvalidConfig("No payload config in metadata".to_string())
Alan Stokes1f417c92022-09-29 15:13:28 +0100280 })?;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100281
Inseob Kimb2519c52022-04-14 02:10:09 +0900282 // To minimize the exposure to untrusted data, derive dice profile as soon as possible.
283 info!("DICE derivation for payload");
Alice Wang62f7e642023-02-10 09:55:13 +0000284 let dice_artifacts = dice_derivation(dice, &verified_data, &payload_metadata)?;
Shikha Panwar95084df2023-07-22 11:47:45 +0000285 let vm_secret = VmSecret::new(dice_artifacts).context("Failed to create VM secrets")?;
Shikha Panwar566c9672022-11-15 14:39:58 +0000286
Alan Stokes9a7f67e2023-11-07 09:37:40 +0000287 if cfg!(dice_changes) {
288 // Now that the DICE derivation is done, it's ok to allow payload code to run.
289
290 // Start apexd to activate APEXes. This may allow code within them to run.
291 system_properties::write("ctl.start", "apexd-vm")?;
292 }
293
Shikha Panwar566c9672022-11-15 14:39:58 +0000294 // Run encryptedstore binary to prepare the storage
295 let encryptedstore_child = if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() {
296 info!("Preparing encryptedstore ...");
Shikha Panwar95084df2023-07-22 11:47:45 +0000297 Some(prepare_encryptedstore(&vm_secret).context("encryptedstore run")?)
Shikha Panwar566c9672022-11-15 14:39:58 +0000298 } else {
299 None
300 };
Inseob Kimb2519c52022-04-14 02:10:09 +0900301
Alan Stokes960c9032022-12-07 16:53:45 +0000302 let mut zipfuse = Zipfuse::default();
303
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900304 // Before reading a file from the APK, start zipfuse
Alan Stokes960c9032022-12-07 16:53:45 +0000305 zipfuse.mount(
Alan Stokes60f82202022-10-07 16:40:07 +0100306 MountForExec::Allowed,
Inseob Kim217038e2021-11-25 11:15:06 +0900307 "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:system_file:s0",
Alan Stokes1125e012023-10-13 12:31:10 +0100308 Path::new(verify::DM_MOUNTED_APK_PATH),
Alice Wang6bbb6da2022-10-26 12:44:06 +0000309 Path::new(VM_APK_CONTENTS_PATH),
Alan Stokes960c9032022-12-07 16:53:45 +0000310 "microdroid_manager.apk.mounted".to_owned(),
311 )?;
Jiyong Park21ce2c52021-08-28 02:32:17 +0900312
Andrew Scull4d262dc2022-10-21 13:14:33 +0000313 // Restricted APIs are only allowed to be used by platform or test components. Infer this from
314 // the use of a VM config file since those can only be used by platform and test components.
315 let allow_restricted_apis = match payload_metadata {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000316 PayloadMetadata::ConfigPath(_) => true,
317 PayloadMetadata::Config(_) => false,
318 _ => false, // default is false for safety
Andrew Scull4d262dc2022-10-21 13:14:33 +0000319 };
320
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100321 let config = load_config(payload_metadata).context("Failed to load payload metadata")?;
Shikha Panwar6f03c942022-04-13 20:26:50 +0000322
Alan Stokes01b3ef02022-09-22 17:43:24 +0100323 let task = config
324 .task
325 .as_ref()
Alan Stokesbbed8872023-10-19 13:17:12 +0100326 .ok_or_else(|| MicrodroidError::PayloadInvalidConfig("No task in VM config".to_string()))?;
Alan Stokes01b3ef02022-09-22 17:43:24 +0100327
Alice Wang061478b2023-04-11 13:26:17 +0000328 ensure!(
329 config.extra_apks.len() == verified_data.extra_apks_data.len(),
330 "config expects {} extra apks, but found {}",
331 config.extra_apks.len(),
332 verified_data.extra_apks_data.len()
333 );
Alan Stokes960c9032022-12-07 16:53:45 +0000334 mount_extra_apks(&config, &mut zipfuse)?;
Jooyung Han634e2d72021-06-10 16:27:38 +0900335
Alan Stokes26efd192023-11-06 16:30:15 +0000336 register_vm_payload_service(
337 allow_restricted_apis,
338 service.clone(),
339 vm_secret,
340 vm_payload_service_fd,
341 )?;
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000342
Shikha Panwar1a6efcd2023-02-03 19:23:43 +0000343 // Set export_tombstones if enabled
Inseob Kimab1037d2023-02-08 17:03:31 +0900344 if should_export_tombstones(&config) {
Shikha Panwar1a6efcd2023-02-03 19:23:43 +0000345 // This property is read by tombstone_handler.
346 system_properties::write("microdroid_manager.export_tombstones.enabled", "1")
347 .context("set microdroid_manager.export_tombstones.enabled")?;
Inseob Kimcd9c1dd2022-07-13 17:13:45 +0900348 }
349
Alan Stokes26efd192023-11-06 16:30:15 +0000350 // Wait until apex config is done. (e.g. linker configuration for apexes)
351 wait_for_property_true(APEX_CONFIG_DONE_PROP).context("Failed waiting for apex config done")?;
352
353 // Trigger init post-fs-data. This will start authfs if we wask it to.
354 if config.enable_authfs {
355 system_properties::write("microdroid_manager.authfs.enabled", "1")
356 .context("failed to write microdroid_manager.authfs.enabled")?;
357 }
358 system_properties::write("microdroid_manager.config_done", "1")
359 .context("failed to write microdroid_manager.config_done")?;
360
Alan Stokes960c9032022-12-07 16:53:45 +0000361 // Wait until zipfuse has mounted the APKs so we can access the payload
362 zipfuse.wait_until_done()?;
Alan Stokes60f82202022-10-07 16:40:07 +0100363
Shikha Panwarddc124b2022-11-28 19:17:54 +0000364 // Wait for encryptedstore to finish mounting the storage (if enabled) before setting
365 // microdroid_manager.init_done. Reason is init stops uneventd after that.
366 // Encryptedstore, however requires ueventd
Shikha Panwar566c9672022-11-15 14:39:58 +0000367 if let Some(mut child) = encryptedstore_child {
368 let exitcode = child.wait().context("Wait for encryptedstore child")?;
369 ensure!(exitcode.success(), "Unable to prepare encrypted storage. Exitcode={}", exitcode);
370 }
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100371
Alan Stokes26efd192023-11-06 16:30:15 +0000372 // Wait for init to have finished booting.
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000373 wait_for_property_true("dev.bootcomplete").context("failed waiting for dev.bootcomplete")?;
Alan Stokes26efd192023-11-06 16:30:15 +0000374
375 // And then tell it we're done so unnecessary services can be shut down.
Shikha Panwar3f6f6a52022-11-29 17:28:36 +0000376 system_properties::write("microdroid_manager.init_done", "1")
377 .context("set microdroid_manager.init_done")?;
Inseob Kimc16b0cc2023-01-26 14:57:24 +0900378
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000379 info!("boot completed, time to run payload");
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100380 exec_task(task, service).context("Failed to run payload")
Alan Stokes01b3ef02022-09-22 17:43:24 +0100381}
382
Alan Stokes03754962023-11-06 15:36:09 +0000383fn post_payload_work() -> Result<()> {
384 // Sync the encrypted storage filesystem (flushes the filesystem caches).
385 if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() {
386 let mountpoint = CString::new(ENCRYPTEDSTORE_MOUNTPOINT).unwrap();
387
388 // SAFETY: `mountpoint` is a valid C string. `syncfs` and `close` are safe for any parameter
389 // values.
390 let ret = unsafe {
391 let dirfd = libc::open(
392 mountpoint.as_ptr(),
393 libc::O_DIRECTORY | libc::O_RDONLY | libc::O_CLOEXEC,
394 );
395 ensure!(dirfd >= 0, "Unable to open {:?}", mountpoint);
396 let ret = libc::syncfs(dirfd);
397 libc::close(dirfd);
398 ret
399 };
400 if ret != 0 {
401 error!("failed to sync encrypted storage.");
402 return Err(anyhow!(std::io::Error::last_os_error()));
403 }
404 }
405 Ok(())
406}
407
Alan Stokes03754962023-11-06 15:36:09 +0000408fn mount_extra_apks(config: &VmPayloadConfig, zipfuse: &mut Zipfuse) -> Result<()> {
409 // For now, only the number of apks is important, as the mount point and dm-verity name is fixed
410 for i in 0..config.extra_apks.len() {
411 let mount_dir = format!("/mnt/extra-apk/{i}");
412 create_dir(Path::new(&mount_dir)).context("Failed to create mount dir for extra apks")?;
413
414 let mount_for_exec =
415 if cfg!(multi_tenant) { MountForExec::Allowed } else { MountForExec::Disallowed };
416 // These run asynchronously in parallel - we wait later for them to complete.
417 zipfuse.mount(
418 mount_for_exec,
419 "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:extra_apk_file:s0",
420 Path::new(&format!("/dev/block/mapper/extra-apk-{i}")),
421 Path::new(&mount_dir),
422 format!("microdroid_manager.extra_apk.mounted.{i}"),
423 )?;
424 }
425
426 Ok(())
427}
428
429fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
430 // The host is running a VirtualMachineService for this VM on a port equal
431 // to the CID of this VM.
432 let port = vsock::get_local_cid().context("Could not determine local CID")?;
433 RpcSession::new()
434 .setup_vsock_client(VMADDR_CID_HOST, port)
435 .context("Could not connect to IVirtualMachineService")
436}
437
438/// Prepares a socket file descriptor for the vm payload service.
439///
440/// # Safety
441///
442/// The caller must ensure that this function is the only place that claims ownership
443/// of the file descriptor and it is called only once.
444unsafe fn prepare_vm_payload_service_socket() -> Result<OwnedFd> {
445 let raw_fd = android_get_control_socket(VM_PAYLOAD_SERVICE_SOCKET_NAME)?;
446
447 // Creating OwnedFd for stdio FDs is not safe.
448 if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) {
449 bail!("File descriptor {raw_fd} is standard I/O descriptor");
450 }
451 // SAFETY: Initializing OwnedFd for a RawFd created by the init.
452 // We checked that the integer value corresponds to a valid FD and that the caller
453 // ensures that this is the only place to claim its ownership.
454 Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) })
455}
456
457fn is_strict_boot() -> bool {
458 Path::new(AVF_STRICT_BOOT).exists()
459}
460
461fn is_new_instance() -> bool {
462 Path::new(AVF_NEW_INSTANCE).exists()
463}
464
465fn is_verified_boot() -> bool {
466 !Path::new(DEBUG_MICRODROID_NO_VERIFIED_BOOT).exists()
467}
468
469fn is_debuggable() -> Result<bool> {
470 Ok(system_properties::read_bool(DEBUGGABLE_PROP, true)?)
471}
472
473fn should_export_tombstones(config: &VmPayloadConfig) -> bool {
474 match config.export_tombstones {
475 Some(b) => b,
476 None => is_debuggable().unwrap_or(false),
477 }
478}
479
480/// Get debug policy value in bool. It's true iff the value is explicitly set to <1>.
481fn get_debug_policy_bool(path: &'static str) -> Result<Option<bool>> {
482 let mut file = match File::open(path) {
483 Ok(dp) => dp,
484 Err(e) => {
485 info!(
486 "Assumes that debug policy is disabled because failed to read debug policy ({e:?})"
487 );
488 return Ok(Some(false));
489 }
490 };
491 let mut log: [u8; 4] = Default::default();
492 file.read_exact(&mut log).context("Malformed data in {path}")?;
493 // DT spec uses big endian although Android is always little endian.
494 Ok(Some(u32::from_be_bytes(log) == 1))
495}
496
Alan Stokes60f82202022-10-07 16:40:07 +0100497enum MountForExec {
498 Allowed,
499 Disallowed,
500}
501
Alan Stokes960c9032022-12-07 16:53:45 +0000502#[derive(Default)]
503struct Zipfuse {
504 ready_properties: Vec<String>,
505}
506
507impl Zipfuse {
508 fn mount(
509 &mut self,
510 noexec: MountForExec,
511 option: &str,
512 zip_path: &Path,
513 mount_dir: &Path,
514 ready_prop: String,
515 ) -> Result<Child> {
516 let mut cmd = Command::new(ZIPFUSE_BIN);
517 if let MountForExec::Disallowed = noexec {
518 cmd.arg("--noexec");
519 }
Alan Stokes1294f942023-08-21 14:34:12 +0100520 // Let root own the files in APK, so we can access them, but set the group to
521 // allow all payloads to have access too.
522 let (uid, gid) = (microdroid_uids::ROOT_UID, microdroid_uids::MICRODROID_PAYLOAD_GID);
523
Alan Stokes960c9032022-12-07 16:53:45 +0000524 cmd.args(["-p", &ready_prop, "-o", option]);
Alan Stokes1294f942023-08-21 14:34:12 +0100525 cmd.args(["-u", &uid.to_string()]);
526 cmd.args(["-g", &gid.to_string()]);
Alan Stokes960c9032022-12-07 16:53:45 +0000527 cmd.arg(zip_path).arg(mount_dir);
528 self.ready_properties.push(ready_prop);
529 cmd.spawn().with_context(|| format!("Failed to run zipfuse for {mount_dir:?}"))
Andrew Scullcc339a12022-07-04 12:44:19 +0000530 }
Alan Stokes960c9032022-12-07 16:53:45 +0000531
532 fn wait_until_done(self) -> Result<()> {
533 // We check the last-started check first in the hope that by the time it is done
534 // all or most of the others will also be done, minimising the number of times we
535 // block on a property.
536 for property in self.ready_properties.into_iter().rev() {
537 wait_for_property_true(&property)
538 .with_context(|| format!("Failed waiting for {property}"))?;
539 }
540 Ok(())
Alan Stokes60f82202022-10-07 16:40:07 +0100541 }
Inseob Kim217038e2021-11-25 11:15:06 +0900542}
543
Alan Stokes60f82202022-10-07 16:40:07 +0100544fn wait_for_property_true(property_name: &str) -> Result<()> {
545 let mut prop = PropertyWatcher::new(property_name)?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900546 loop {
Andrew Walbrand9c766e2023-05-10 15:15:39 +0000547 prop.wait(None)?;
Alan Stokes60f82202022-10-07 16:40:07 +0100548 if system_properties::read_bool(property_name, false)? {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900549 break;
550 }
551 }
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900552 Ok(())
553}
554
Alan Stokes1f417c92022-09-29 15:13:28 +0100555fn load_config(payload_metadata: PayloadMetadata) -> Result<VmPayloadConfig> {
556 match payload_metadata {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000557 PayloadMetadata::ConfigPath(path) => {
Alan Stokes1f417c92022-09-29 15:13:28 +0100558 let path = Path::new(&path);
559 info!("loading config from {:?}...", path);
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100560 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)
561 .with_context(|| format!("Failed to read {:?}", path))?;
Alan Stokes1f417c92022-09-29 15:13:28 +0100562 Ok(serde_json::from_reader(file)?)
563 }
Ludovic Barman93ee3082023-06-20 12:18:43 +0000564 PayloadMetadata::Config(payload_config) => {
Alan Stokes1f417c92022-09-29 15:13:28 +0100565 let task = Task {
566 type_: TaskType::MicrodroidLauncher,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000567 command: payload_config.payload_binary_name,
Alan Stokes1f417c92022-09-29 15:13:28 +0100568 };
569 Ok(VmPayloadConfig {
570 os: OsConfig { name: "microdroid".to_owned() },
571 task: Some(task),
572 apexes: vec![],
573 extra_apks: vec![],
574 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900575 export_tombstones: None,
Alan Stokes1f417c92022-09-29 15:13:28 +0100576 enable_authfs: false,
577 })
578 }
Ludovic Barman93ee3082023-06-20 12:18:43 +0000579 _ => bail!("Failed to match config against a config type."),
Alan Stokes1f417c92022-09-29 15:13:28 +0100580 }
Jooyung Han634e2d72021-06-10 16:27:38 +0900581}
582
Jaewan Kim3124ef02023-03-23 19:25:20 +0900583/// Loads the crashkernel into memory using kexec if debuggable or debug policy says so.
584/// The VM should be loaded with `crashkernel=' parameter in the cmdline to allocate memory
585/// for crashkernel.
Jiyong Park202856e2022-08-22 16:04:26 +0900586fn load_crashkernel_if_supported() -> Result<()> {
587 let supported = std::fs::read_to_string("/proc/cmdline")?.contains(" crashkernel=");
588 info!("ramdump supported: {}", supported);
Jaewan Kim3124ef02023-03-23 19:25:20 +0900589
590 if !supported {
591 return Ok(());
592 }
593
Alan Stokes1125e012023-10-13 12:31:10 +0100594 let debuggable = is_debuggable()?;
Jaewan Kim3124ef02023-03-23 19:25:20 +0900595 let ramdump = get_debug_policy_bool(AVF_DEBUG_POLICY_RAMDUMP)?.unwrap_or_default();
596 let requested = debuggable | ramdump;
597
598 if requested {
Jiyong Park202856e2022-08-22 16:04:26 +0900599 let status = Command::new("/system/bin/kexec_load").status()?;
600 if !status.success() {
601 return Err(anyhow!("Failed to load crashkernel: {:?}", status));
602 }
Jaewan Kim3124ef02023-03-23 19:25:20 +0900603 info!("ramdump is loaded: debuggable={debuggable}, ramdump={ramdump}");
Jiyong Park202856e2022-08-22 16:04:26 +0900604 }
605 Ok(())
606}
607
Inseob Kim090b70b2022-11-16 20:01:14 +0900608/// Executes the given task.
Jooyung Han5c6d4172021-12-06 14:17:52 +0900609fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<i32> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900610 info!("executing main task {:?}...", task);
David Brazdil451cc962022-10-14 14:08:12 +0100611 let mut command = match task.type_ {
Alan Stokes1294f942023-08-21 14:34:12 +0100612 TaskType::Executable => {
Alan Stokes679ddf32023-09-01 11:14:48 +0100613 // TODO(b/297501338): Figure out how to handle non-root for system payloads.
Alan Stokes1294f942023-08-21 14:34:12 +0100614 Command::new(&task.command)
615 }
David Brazdil451cc962022-10-14 14:08:12 +0100616 TaskType::MicrodroidLauncher => {
617 let mut command = Command::new("/system/bin/microdroid_launcher");
618 command.arg(find_library_path(&task.command)?);
Alan Stokes1294f942023-08-21 14:34:12 +0100619 command.uid(microdroid_uids::MICRODROID_PAYLOAD_UID);
620 command.gid(microdroid_uids::MICRODROID_PAYLOAD_GID);
David Brazdil451cc962022-10-14 14:08:12 +0100621 command
622 }
623 };
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000624
Andrew Walbranaac68302023-07-21 19:05:34 +0100625 // SAFETY: We are not accessing any resource of the parent process. This means we can't make any
626 // log calls inside the closure.
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000627 unsafe {
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000628 command.pre_exec(|| {
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000629 // It is OK to continue with payload execution even if the calls below fail, since
630 // whether process can use a capability is controlled by the SELinux. Dropping the
631 // capabilities here is just another defense-in-depth layer.
Andrew Walbranaac68302023-07-21 19:05:34 +0100632 let _ = cap::drop_inheritable_caps();
633 let _ = cap::drop_bounding_set();
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000634 Ok(())
635 });
636 }
637
Inseob Kim090b70b2022-11-16 20:01:14 +0900638 command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
Inseob Kim7f61fe72021-08-20 20:50:47 +0900639
640 info!("notifying payload started");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000641 service.notifyPayloadStarted()?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900642
Inseob Kim86ca0162021-10-20 02:21:02 +0000643 let exit_status = command.spawn()?.wait()?;
Frederick Mayleb5f7b6b2022-11-11 15:24:03 -0800644 match exit_status.code() {
645 Some(exit_code) => Ok(exit_code),
646 None => Err(match exit_status.signal() {
647 Some(signal) => anyhow!(
648 "Payload exited due to signal: {} ({})",
649 signal,
650 Signal::try_from(signal).map_or("unknown", |s| s.as_str())
651 ),
652 None => anyhow!("Payload has neither exit code nor signal"),
653 }),
654 }
Jooyung Han347d9f22021-05-28 00:05:14 +0900655}
Jooyung Han634e2d72021-06-10 16:27:38 +0900656
Jooyung Han634e2d72021-06-10 16:27:38 +0900657fn find_library_path(name: &str) -> Result<String> {
658 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
659 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
660 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
Alice Wang6bbb6da2022-10-26 12:44:06 +0000661 let path = format!("{}/lib/{}/{}", VM_APK_CONTENTS_PATH, abi, name);
Jooyung Han634e2d72021-06-10 16:27:38 +0900662
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100663 let metadata = fs::metadata(&path).with_context(|| format!("Unable to access {}", path))?;
Jooyung Han634e2d72021-06-10 16:27:38 +0900664 if !metadata.is_file() {
665 bail!("{} is not a file", &path);
666 }
667
668 Ok(path)
669}
Jiyong Park21ce2c52021-08-28 02:32:17 +0900670
Shikha Panwar95084df2023-07-22 11:47:45 +0000671fn prepare_encryptedstore(vm_secret: &VmSecret) -> Result<Child> {
Alice Wang7e6c9352023-02-15 15:44:13 +0000672 let mut key = ZVec::new(ENCRYPTEDSTORE_KEYSIZE)?;
Shikha Panwar3d3a70a2023-08-21 20:02:08 +0000673 vm_secret.derive_encryptedstore_key(&mut key)?;
Shikha Panwar566c9672022-11-15 14:39:58 +0000674 let mut cmd = Command::new(ENCRYPTEDSTORE_BIN);
675 cmd.arg("--blkdevice")
676 .arg(ENCRYPTEDSTORE_BACKING_DEVICE)
677 .arg("--key")
678 .arg(hex::encode(&*key))
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000679 .args(["--mountpoint", ENCRYPTEDSTORE_MOUNTPOINT])
Shikha Panwar566c9672022-11-15 14:39:58 +0000680 .spawn()
681 .context("encryptedstore failed")
682}