Jooyung Han | 347d9f2 | 2021-05-28 00:05:14 +0900 | [diff] [blame] | 1 | // 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 Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 17 | mod dice; |
Jiyong Park | 21ce2c5 | 2021-08-28 02:32:17 +0900 | [diff] [blame] | 18 | mod instance; |
Jooyung Han | f48ceb4 | 2021-06-01 18:00:04 +0900 | [diff] [blame] | 19 | mod ioutil; |
Jooyung Han | 7a343f9 | 2021-09-08 22:53:11 +0900 | [diff] [blame] | 20 | mod payload; |
Keir Fraser | 933f0ac | 2022-10-12 08:23:28 +0000 | [diff] [blame] | 21 | mod swap; |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 22 | mod verify; |
Alice Wang | 59a9e56 | 2022-10-04 15:24:10 +0000 | [diff] [blame] | 23 | mod vm_payload_service; |
Shikha Panwar | 95084df | 2023-07-22 11:47:45 +0000 | [diff] [blame] | 24 | mod vm_secret; |
Jooyung Han | 347d9f2 | 2021-05-28 00:05:14 +0900 | [diff] [blame] | 25 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 26 | use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode; |
David Brazdil | 73988ea | 2022-11-11 15:10:32 +0000 | [diff] [blame] | 27 | use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::IVirtualMachineService; |
Inseob Kim | 090b70b | 2022-11-16 20:01:14 +0900 | [diff] [blame] | 28 | use android_system_virtualization_payload::aidl::android::system::virtualization::payload::IVmPayloadService::{ |
| 29 | VM_APK_CONTENTS_PATH, |
| 30 | VM_PAYLOAD_SERVICE_SOCKET_NAME, |
Shikha Panwar | ddc124b | 2022-11-28 19:17:54 +0000 | [diff] [blame] | 31 | ENCRYPTEDSTORE_MOUNTPOINT, |
Inseob Kim | 090b70b | 2022-11-16 20:01:14 +0900 | [diff] [blame] | 32 | }; |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 33 | |
| 34 | use crate::dice::dice_derivation; |
Alan Stokes | 0375496 | 2023-11-06 15:36:09 +0000 | [diff] [blame] | 35 | use crate::instance::{InstanceDisk, MicrodroidData}; |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 36 | use crate::verify::verify_payload; |
| 37 | use crate::vm_payload_service::register_vm_payload_service; |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 38 | use anyhow::{anyhow, bail, ensure, Context, Error, Result}; |
Alice Wang | 43c884b | 2022-10-24 09:42:40 +0000 | [diff] [blame] | 39 | use binder::Strong; |
Nikita Ioffe | e18cc13 | 2024-02-28 16:13:36 +0000 | [diff] [blame^] | 40 | use dice_driver::DiceDriver; |
Alice Wang | 7e6c935 | 2023-02-15 15:44:13 +0000 | [diff] [blame] | 41 | use keystore2_crypto::ZVec; |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 42 | use libc::VMADDR_CID_HOST; |
| 43 | use log::{error, info}; |
Shikha Panwar | 5803dc7 | 2024-03-06 12:00:50 +0000 | [diff] [blame] | 44 | use microdroid_metadata::PayloadMetadata; |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 45 | use microdroid_payload_config::{ApkConfig, OsConfig, Task, TaskType, VmPayloadConfig}; |
Frederick Mayle | b5f7b6b | 2022-11-11 15:24:03 -0800 | [diff] [blame] | 46 | use nix::sys::signal::Signal; |
Alan Stokes | 0375496 | 2023-11-06 15:36:09 +0000 | [diff] [blame] | 47 | use payload::load_metadata; |
David Brazdil | a2125dd | 2022-12-14 16:37:44 +0000 | [diff] [blame] | 48 | use rpcbinder::RpcSession; |
Inseob Kim | 090b70b | 2022-11-16 20:01:14 +0900 | [diff] [blame] | 49 | use rustutils::sockets::android_get_control_socket; |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 50 | use rustutils::system_properties; |
Joel Galenson | 482704c | 2021-07-29 15:53:53 -0700 | [diff] [blame] | 51 | use rustutils::system_properties::PropertyWatcher; |
Shikha Panwar | 0503cb0 | 2024-01-05 10:11:28 +0000 | [diff] [blame] | 52 | use secretkeeper_comm::data_types::ID_SIZE; |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 53 | use std::borrow::Cow::{Borrowed, Owned}; |
Inseob Kim | 7ff121c | 2022-11-14 18:13:23 +0900 | [diff] [blame] | 54 | use std::env; |
Shikha Panwar | def7ef9 | 2023-01-06 08:35:48 +0000 | [diff] [blame] | 55 | use std::ffi::CString; |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 56 | use std::fs::{self, create_dir, File, OpenOptions}; |
Jaewan Kim | 3124ef0 | 2023-03-23 19:25:20 +0900 | [diff] [blame] | 57 | use std::io::{Read, Write}; |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 58 | use std::os::unix::io::{FromRawFd, OwnedFd}; |
Nikita Ioffe | 3452ee2 | 2022-12-15 00:31:56 +0000 | [diff] [blame] | 59 | use std::os::unix::process::CommandExt; |
Frederick Mayle | b5f7b6b | 2022-11-11 15:24:03 -0800 | [diff] [blame] | 60 | use std::os::unix::process::ExitStatusExt; |
Jooyung Han | f48ceb4 | 2021-06-01 18:00:04 +0900 | [diff] [blame] | 61 | use std::path::Path; |
Inseob Kim | 217038e | 2021-11-25 11:15:06 +0900 | [diff] [blame] | 62 | use std::process::{Child, Command, Stdio}; |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 63 | use std::str; |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 64 | use std::time::Duration; |
Shikha Panwar | 95084df | 2023-07-22 11:47:45 +0000 | [diff] [blame] | 65 | use vm_secret::VmSecret; |
Jooyung Han | 634e2d7 | 2021-06-10 16:27:38 +0900 | [diff] [blame] | 66 | |
| 67 | const WAIT_TIMEOUT: Duration = Duration::from_secs(10); |
Jaewan Kim | 1f0135b | 2024-01-31 14:59:47 +0900 | [diff] [blame] | 68 | const AVF_STRICT_BOOT: &str = "/proc/device-tree/chosen/avf,strict-boot"; |
| 69 | const AVF_NEW_INSTANCE: &str = "/proc/device-tree/chosen/avf,new-instance"; |
| 70 | const AVF_DEBUG_POLICY_RAMDUMP: &str = "/proc/device-tree/avf/guest/common/ramdump"; |
Inseob Kim | e379e7d | 2022-07-22 18:55:18 +0900 | [diff] [blame] | 71 | const DEBUG_MICRODROID_NO_VERIFIED_BOOT: &str = |
Jaewan Kim | 1f0135b | 2024-01-31 14:59:47 +0900 | [diff] [blame] | 72 | "/proc/device-tree/virtualization/guest/debug-microdroid,no-verified-boot"; |
Shikha Panwar | 14abe44 | 2024-02-23 15:04:27 +0000 | [diff] [blame] | 73 | const SECRETKEEPER_KEY: &str = "/proc/device-tree/avf/secretkeeper_public_key"; |
| 74 | const INSTANCE_ID_PATH: &str = "/proc/device-tree/avf/untrusted/instance-id"; |
Jooyung Han | 347d9f2 | 2021-05-28 00:05:14 +0900 | [diff] [blame] | 75 | |
Alan Stokes | 4fb201c | 2023-02-08 17:39:05 +0000 | [diff] [blame] | 76 | const ENCRYPTEDSTORE_BIN: &str = "/system/bin/encryptedstore"; |
| 77 | const ZIPFUSE_BIN: &str = "/system/bin/zipfuse"; |
| 78 | |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 79 | const APEX_CONFIG_DONE_PROP: &str = "apex_config.done"; |
Seungjae Yoo | fa22bb0 | 2022-12-08 16:38:42 +0900 | [diff] [blame] | 80 | const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable"; |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 81 | |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 82 | // SYNC WITH virtualizationservice/src/crosvm.rs |
| 83 | const FAILURE_SERIAL_DEVICE: &str = "/dev/ttyS1"; |
| 84 | |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 85 | const ENCRYPTEDSTORE_BACKING_DEVICE: &str = "/dev/block/by-name/encryptedstore"; |
Alice Wang | 62f7e64 | 2023-02-10 09:55:13 +0000 | [diff] [blame] | 86 | const ENCRYPTEDSTORE_KEYSIZE: usize = 32; |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 87 | |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 88 | #[derive(thiserror::Error, Debug)] |
| 89 | enum MicrodroidError { |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 90 | #[error("Cannot connect to virtualization service: {0}")] |
| 91 | FailedToConnectToVirtualizationService(String), |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 92 | #[error("Payload has changed: {0}")] |
| 93 | PayloadChanged(String), |
| 94 | #[error("Payload verification has failed: {0}")] |
| 95 | PayloadVerificationFailed(String), |
Jooyung Han | 5c6d417 | 2021-12-06 14:17:52 +0900 | [diff] [blame] | 96 | #[error("Payload config is invalid: {0}")] |
Alan Stokes | bbed887 | 2023-10-19 13:17:12 +0100 | [diff] [blame] | 97 | PayloadInvalidConfig(String), |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 98 | } |
| 99 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 100 | fn translate_error(err: &Error) -> (ErrorCode, String) { |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 101 | if let Some(e) = err.downcast_ref::<MicrodroidError>() { |
| 102 | match e { |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 103 | MicrodroidError::PayloadChanged(msg) => (ErrorCode::PAYLOAD_CHANGED, msg.to_string()), |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 104 | MicrodroidError::PayloadVerificationFailed(msg) => { |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 105 | (ErrorCode::PAYLOAD_VERIFICATION_FAILED, msg.to_string()) |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 106 | } |
Alan Stokes | bbed887 | 2023-10-19 13:17:12 +0100 | [diff] [blame] | 107 | MicrodroidError::PayloadInvalidConfig(msg) => { |
| 108 | (ErrorCode::PAYLOAD_INVALID_CONFIG, msg.to_string()) |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 109 | } |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 110 | // Connection failure won't be reported to VS; return the default value |
| 111 | MicrodroidError::FailedToConnectToVirtualizationService(msg) => { |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 112 | (ErrorCode::UNKNOWN, msg.to_string()) |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 113 | } |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 114 | } |
| 115 | } else { |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 116 | (ErrorCode::UNKNOWN, err.to_string()) |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 117 | } |
| 118 | } |
| 119 | |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 120 | fn write_death_reason_to_serial(err: &Error) -> Result<()> { |
| 121 | let death_reason = if let Some(e) = err.downcast_ref::<MicrodroidError>() { |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 122 | Borrowed(match e { |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 123 | 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 Stokes | bbed887 | 2023-10-19 13:17:12 +0100 | [diff] [blame] | 130 | MicrodroidError::PayloadInvalidConfig(_) => "MICRODROID_INVALID_PAYLOAD_CONFIG", |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 131 | }) |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 132 | } else { |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 133 | // 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 Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 137 | }; |
| 138 | |
Pierre-Clément Tosi | d225af5 | 2023-09-15 15:59:20 +0100 | [diff] [blame] | 139 | for chunk in death_reason.as_bytes().chunks(16) { |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 140 | // TODO(b/220071963): Sometimes, sending more than 16 bytes at once makes MM hang. |
Pierre-Clément Tosi | d225af5 | 2023-09-15 15:59:20 +0100 | [diff] [blame] | 141 | OpenOptions::new().read(false).write(true).open(FAILURE_SERIAL_DEVICE)?.write_all(chunk)?; |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 142 | } |
| 143 | |
| 144 | Ok(()) |
| 145 | } |
| 146 | |
Shikha Panwar | 14abe44 | 2024-02-23 15:04:27 +0000 | [diff] [blame] | 147 | /// The (host allocated) instance_id can be found at node /avf/untrusted/ in the device tree. |
| 148 | fn 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 Kim | 437f105 | 2022-06-21 11:30:22 +0900 | [diff] [blame] | 164 | fn main() -> Result<()> { |
Inseob Kim | 7ff121c | 2022-11-14 18:13:23 +0900 | [diff] [blame] | 165 | // If debuggable, print full backtrace to console log with stdio_to_kmsg |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 166 | if is_debuggable()? { |
Inseob Kim | 7ff121c | 2022-11-14 18:13:23 +0900 | [diff] [blame] | 167 | env::set_var("RUST_BACKTRACE", "full"); |
| 168 | } |
| 169 | |
Inseob Kim | 437f105 | 2022-06-21 11:30:22 +0900 | [diff] [blame] | 170 | scopeguard::defer! { |
| 171 | info!("Shutting down..."); |
Jooyung Han | bfe086f | 2021-10-28 10:15:45 +0900 | [diff] [blame] | 172 | if let Err(e) = system_properties::write("sys.powerctl", "shutdown") { |
| 173 | error!("failed to shutdown {:?}", e); |
| 174 | } |
Jooyung Han | 311b120 | 2021-09-14 22:00:16 +0900 | [diff] [blame] | 175 | } |
Inseob Kim | 437f105 | 2022-06-21 11:30:22 +0900 | [diff] [blame] | 176 | |
| 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 Han | 311b120 | 2021-09-14 22:00:16 +0900 | [diff] [blame] | 184 | } |
| 185 | |
| 186 | fn try_main() -> Result<()> { |
Jiyong Park | 2b6346d | 2023-06-19 13:37:42 +0900 | [diff] [blame] | 187 | android_logger::init_once( |
| 188 | android_logger::Config::default() |
| 189 | .with_tag("microdroid_manager") |
Jeff Vander Stoep | 57da157 | 2024-01-31 10:52:16 +0100 | [diff] [blame] | 190 | .with_max_level(log::LevelFilter::Info), |
Jiyong Park | 2b6346d | 2023-06-19 13:37:42 +0900 | [diff] [blame] | 191 | ); |
Jooyung Han | 347d9f2 | 2021-05-28 00:05:14 +0900 | [diff] [blame] | 192 | info!("started."); |
| 193 | |
Alice Wang | fd222fd | 2023-05-25 09:37:38 +0000 | [diff] [blame] | 194 | // SAFETY: This is the only place we take the ownership of the fd of the vm payload service. |
| 195 | // |
Alice Wang | 2a5306e | 2023-06-05 09:18:32 +0000 | [diff] [blame] | 196 | // 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 Wang | fd222fd | 2023-05-25 09:37:38 +0000 | [diff] [blame] | 200 | let vm_payload_service_fd = unsafe { prepare_vm_payload_service_socket()? }; |
Inseob Kim | 090b70b | 2022-11-16 20:01:14 +0900 | [diff] [blame] | 201 | |
Jiyong Park | 202856e | 2022-08-22 16:04:26 +0900 | [diff] [blame] | 202 | load_crashkernel_if_supported().context("Failed to load crashkernel")?; |
| 203 | |
Alice Wang | eff5839 | 2023-07-04 13:32:09 +0000 | [diff] [blame] | 204 | swap::init_swap().context("Failed to initialize swap")?; |
Keir Fraser | 933f0ac | 2022-10-12 08:23:28 +0000 | [diff] [blame] | 205 | info!("swap enabled."); |
| 206 | |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 207 | let service = get_vms_rpc_binder() |
| 208 | .context("cannot connect to VirtualMachineService") |
| 209 | .map_err(|e| MicrodroidError::FailedToConnectToVirtualizationService(e.to_string()))?; |
Seungjae Yoo | fd9a062 | 2022-10-14 10:01:29 +0900 | [diff] [blame] | 210 | |
Alice Wang | fd222fd | 2023-05-25 09:37:38 +0000 | [diff] [blame] | 211 | match try_run_payload(&service, vm_payload_service_fd) { |
Jooyung Han | 5c6d417 | 2021-12-06 14:17:52 +0900 | [diff] [blame] | 212 | Ok(code) => { |
Jooyung Han | 5c6d417 | 2021-12-06 14:17:52 +0900 | [diff] [blame] | 213 | if code == 0 { |
| 214 | info!("task successfully finished"); |
| 215 | } else { |
| 216 | error!("task exited with exit code: {}", code); |
| 217 | } |
Shikha Panwar | def7ef9 | 2023-01-06 08:35:48 +0000 | [diff] [blame] | 218 | 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 Han | 5c6d417 | 2021-12-06 14:17:52 +0900 | [diff] [blame] | 228 | Ok(()) |
| 229 | } |
| 230 | Err(err) => { |
Jooyung Han | 5c6d417 | 2021-12-06 14:17:52 +0900 | [diff] [blame] | 231 | let (error_code, message) = translate_error(&err); |
| 232 | service.notifyError(error_code, &message)?; |
| 233 | Err(err) |
| 234 | } |
Jooyung Han | dd0a173 | 2021-11-23 15:26:20 +0900 | [diff] [blame] | 235 | } |
| 236 | } |
| 237 | |
Shikha Panwar | 5803dc7 | 2024-03-06 12:00:50 +0000 | [diff] [blame] | 238 | fn try_run_payload( |
| 239 | service: &Strong<dyn IVirtualMachineService>, |
| 240 | vm_payload_service_fd: OwnedFd, |
| 241 | ) -> Result<i32> { |
| 242 | let metadata = load_metadata().context("Failed to load payload metadata")?; |
Nikita Ioffe | e18cc13 | 2024-02-28 16:13:36 +0000 | [diff] [blame^] | 243 | let dice = DiceDriver::new(Path::new("/dev/open-dice0"), is_strict_boot()) |
| 244 | .context("Failed to load DICE")?; |
Shikha Panwar | 5803dc7 | 2024-03-06 12:00:50 +0000 | [diff] [blame] | 245 | |
Jooyung Han | 311b120 | 2021-09-14 22:00:16 +0900 | [diff] [blame] | 246 | let mut instance = InstanceDisk::new().context("Failed to load instance.img")?; |
Shikha Panwar | 5803dc7 | 2024-03-06 12:00:50 +0000 | [diff] [blame] | 247 | let saved_data = |
| 248 | instance.read_microdroid_data(&dice).context("Failed to read identity data")?; |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 249 | |
Andrew Scull | ab72ec5 | 2022-03-14 09:10:52 +0000 | [diff] [blame] | 250 | if is_strict_boot() { |
| 251 | // Provisioning must happen on the first boot and never again. |
| 252 | if is_new_instance() { |
| 253 | ensure!( |
| 254 | saved_data.is_none(), |
Alan Stokes | bbed887 | 2023-10-19 13:17:12 +0100 | [diff] [blame] | 255 | MicrodroidError::PayloadInvalidConfig( |
| 256 | "Found instance data on first boot.".to_string() |
| 257 | ) |
Andrew Scull | ab72ec5 | 2022-03-14 09:10:52 +0000 | [diff] [blame] | 258 | ); |
| 259 | } else { |
| 260 | ensure!( |
| 261 | saved_data.is_some(), |
Alan Stokes | bbed887 | 2023-10-19 13:17:12 +0100 | [diff] [blame] | 262 | MicrodroidError::PayloadInvalidConfig("Instance data not found.".to_string()) |
Andrew Scull | ab72ec5 | 2022-03-14 09:10:52 +0000 | [diff] [blame] | 263 | ); |
| 264 | }; |
| 265 | } |
| 266 | |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 267 | // Verify the payload before using it. |
Shikha Panwar | 5803dc7 | 2024-03-06 12:00:50 +0000 | [diff] [blame] | 268 | let extracted_data = verify_payload(&metadata, saved_data.as_ref()) |
Inseob Kim | 11f40d0 | 2022-06-13 17:16:00 +0900 | [diff] [blame] | 269 | .context("Payload verification failed") |
| 270 | .map_err(|e| MicrodroidError::PayloadVerificationFailed(e.to_string()))?; |
Inseob Kim | e379e7d | 2022-07-22 18:55:18 +0900 | [diff] [blame] | 271 | |
| 272 | // In case identity is ignored (by debug policy), we should reuse existing payload data, even |
| 273 | // when the payload is changed. This is to keep the derived secret same as before. |
Alan Stokes | 26a6a5c | 2023-11-10 16:18:43 +0000 | [diff] [blame] | 274 | let instance_data = if let Some(saved_data) = saved_data { |
Inseob Kim | e379e7d | 2022-07-22 18:55:18 +0900 | [diff] [blame] | 275 | if !is_verified_boot() { |
Alan Stokes | 26a6a5c | 2023-11-10 16:18:43 +0000 | [diff] [blame] | 276 | if saved_data != extracted_data { |
Inseob Kim | e379e7d | 2022-07-22 18:55:18 +0900 | [diff] [blame] | 277 | info!("Detected an update of the payload, but continue (regarding debug policy)") |
| 278 | } |
| 279 | } else { |
| 280 | ensure!( |
Alan Stokes | 26a6a5c | 2023-11-10 16:18:43 +0000 | [diff] [blame] | 281 | saved_data == extracted_data, |
Inseob Kim | e379e7d | 2022-07-22 18:55:18 +0900 | [diff] [blame] | 282 | MicrodroidError::PayloadChanged(String::from( |
| 283 | "Detected an update of the payload which isn't supported yet." |
| 284 | )) |
| 285 | ); |
| 286 | info!("Saved data is verified."); |
| 287 | } |
| 288 | saved_data |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 289 | } else { |
Jooyung Han | 7a343f9 | 2021-09-08 22:53:11 +0900 | [diff] [blame] | 290 | info!("Saving verified data."); |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 291 | instance |
Shikha Panwar | 5803dc7 | 2024-03-06 12:00:50 +0000 | [diff] [blame] | 292 | .write_microdroid_data(&extracted_data, &dice) |
Andrew Scull | d64ae7d | 2022-10-05 17:41:43 +0000 | [diff] [blame] | 293 | .context("Failed to write identity data")?; |
Alan Stokes | 26a6a5c | 2023-11-10 16:18:43 +0000 | [diff] [blame] | 294 | extracted_data |
Inseob Kim | e379e7d | 2022-07-22 18:55:18 +0900 | [diff] [blame] | 295 | }; |
Jooyung Han | 19c1d6c | 2021-08-06 14:08:16 +0900 | [diff] [blame] | 296 | |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 297 | let payload_metadata = metadata.payload.ok_or_else(|| { |
Alan Stokes | bbed887 | 2023-10-19 13:17:12 +0100 | [diff] [blame] | 298 | MicrodroidError::PayloadInvalidConfig("No payload config in metadata".to_string()) |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 299 | })?; |
Alan Stokes | 0d1ef78 | 2022-09-27 13:46:35 +0100 | [diff] [blame] | 300 | |
Inseob Kim | b2519c5 | 2022-04-14 02:10:09 +0900 | [diff] [blame] | 301 | // To minimize the exposure to untrusted data, derive dice profile as soon as possible. |
| 302 | info!("DICE derivation for payload"); |
Alan Stokes | 26a6a5c | 2023-11-10 16:18:43 +0000 | [diff] [blame] | 303 | let dice_artifacts = dice_derivation(dice, &instance_data, &payload_metadata)?; |
Shikha Panwar | 5d6a675 | 2023-12-14 22:08:26 +0000 | [diff] [blame] | 304 | let vm_secret = |
Shikha Panwar | 14abe44 | 2024-02-23 15:04:27 +0000 | [diff] [blame] | 305 | VmSecret::new(dice_artifacts, service).context("Failed to create VM secrets")?; |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 306 | |
Alan Stokes | 9a7f67e | 2023-11-07 09:37:40 +0000 | [diff] [blame] | 307 | if cfg!(dice_changes) { |
| 308 | // Now that the DICE derivation is done, it's ok to allow payload code to run. |
| 309 | |
| 310 | // Start apexd to activate APEXes. This may allow code within them to run. |
| 311 | system_properties::write("ctl.start", "apexd-vm")?; |
| 312 | } |
| 313 | |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 314 | // Run encryptedstore binary to prepare the storage |
| 315 | let encryptedstore_child = if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() { |
| 316 | info!("Preparing encryptedstore ..."); |
Shikha Panwar | 95084df | 2023-07-22 11:47:45 +0000 | [diff] [blame] | 317 | Some(prepare_encryptedstore(&vm_secret).context("encryptedstore run")?) |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 318 | } else { |
| 319 | None |
| 320 | }; |
Inseob Kim | b2519c5 | 2022-04-14 02:10:09 +0900 | [diff] [blame] | 321 | |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 322 | let mut zipfuse = Zipfuse::default(); |
| 323 | |
Jooyung Han | a6d11eb | 2021-09-10 11:48:05 +0900 | [diff] [blame] | 324 | // Before reading a file from the APK, start zipfuse |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 325 | zipfuse.mount( |
Alan Stokes | 60f8220 | 2022-10-07 16:40:07 +0100 | [diff] [blame] | 326 | MountForExec::Allowed, |
Inseob Kim | 217038e | 2021-11-25 11:15:06 +0900 | [diff] [blame] | 327 | "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:system_file:s0", |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 328 | Path::new(verify::DM_MOUNTED_APK_PATH), |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 329 | Path::new(VM_APK_CONTENTS_PATH), |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 330 | "microdroid_manager.apk.mounted".to_owned(), |
| 331 | )?; |
Jiyong Park | 21ce2c5 | 2021-08-28 02:32:17 +0900 | [diff] [blame] | 332 | |
Andrew Scull | 4d262dc | 2022-10-21 13:14:33 +0000 | [diff] [blame] | 333 | // Restricted APIs are only allowed to be used by platform or test components. Infer this from |
| 334 | // the use of a VM config file since those can only be used by platform and test components. |
| 335 | let allow_restricted_apis = match payload_metadata { |
Ludovic Barman | 93ee308 | 2023-06-20 12:18:43 +0000 | [diff] [blame] | 336 | PayloadMetadata::ConfigPath(_) => true, |
| 337 | PayloadMetadata::Config(_) => false, |
| 338 | _ => false, // default is false for safety |
Andrew Scull | 4d262dc | 2022-10-21 13:14:33 +0000 | [diff] [blame] | 339 | }; |
| 340 | |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 341 | let config = load_config(payload_metadata).context("Failed to load payload metadata")?; |
Shikha Panwar | 6f03c94 | 2022-04-13 20:26:50 +0000 | [diff] [blame] | 342 | |
Alan Stokes | 01b3ef0 | 2022-09-22 17:43:24 +0100 | [diff] [blame] | 343 | let task = config |
| 344 | .task |
| 345 | .as_ref() |
Alan Stokes | bbed887 | 2023-10-19 13:17:12 +0100 | [diff] [blame] | 346 | .ok_or_else(|| MicrodroidError::PayloadInvalidConfig("No task in VM config".to_string()))?; |
Alan Stokes | 01b3ef0 | 2022-09-22 17:43:24 +0100 | [diff] [blame] | 347 | |
Alice Wang | 061478b | 2023-04-11 13:26:17 +0000 | [diff] [blame] | 348 | ensure!( |
Alan Stokes | 26a6a5c | 2023-11-10 16:18:43 +0000 | [diff] [blame] | 349 | config.extra_apks.len() == instance_data.extra_apks_data.len(), |
Alice Wang | 061478b | 2023-04-11 13:26:17 +0000 | [diff] [blame] | 350 | "config expects {} extra apks, but found {}", |
| 351 | config.extra_apks.len(), |
Alan Stokes | 26a6a5c | 2023-11-10 16:18:43 +0000 | [diff] [blame] | 352 | instance_data.extra_apks_data.len() |
Alice Wang | 061478b | 2023-04-11 13:26:17 +0000 | [diff] [blame] | 353 | ); |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 354 | mount_extra_apks(&config, &mut zipfuse)?; |
Jooyung Han | 634e2d7 | 2021-06-10 16:27:38 +0900 | [diff] [blame] | 355 | |
Alan Stokes | 26efd19 | 2023-11-06 16:30:15 +0000 | [diff] [blame] | 356 | register_vm_payload_service( |
| 357 | allow_restricted_apis, |
| 358 | service.clone(), |
| 359 | vm_secret, |
| 360 | vm_payload_service_fd, |
| 361 | )?; |
Nikita Ioffe | 57bc8d7 | 2022-11-27 00:50:50 +0000 | [diff] [blame] | 362 | |
Shikha Panwar | 1a6efcd | 2023-02-03 19:23:43 +0000 | [diff] [blame] | 363 | // Set export_tombstones if enabled |
Inseob Kim | ab1037d | 2023-02-08 17:03:31 +0900 | [diff] [blame] | 364 | if should_export_tombstones(&config) { |
Shikha Panwar | 1a6efcd | 2023-02-03 19:23:43 +0000 | [diff] [blame] | 365 | // This property is read by tombstone_handler. |
| 366 | system_properties::write("microdroid_manager.export_tombstones.enabled", "1") |
| 367 | .context("set microdroid_manager.export_tombstones.enabled")?; |
Inseob Kim | cd9c1dd | 2022-07-13 17:13:45 +0900 | [diff] [blame] | 368 | } |
| 369 | |
Alan Stokes | 26efd19 | 2023-11-06 16:30:15 +0000 | [diff] [blame] | 370 | // Wait until apex config is done. (e.g. linker configuration for apexes) |
| 371 | wait_for_property_true(APEX_CONFIG_DONE_PROP).context("Failed waiting for apex config done")?; |
| 372 | |
| 373 | // Trigger init post-fs-data. This will start authfs if we wask it to. |
| 374 | if config.enable_authfs { |
| 375 | system_properties::write("microdroid_manager.authfs.enabled", "1") |
| 376 | .context("failed to write microdroid_manager.authfs.enabled")?; |
| 377 | } |
| 378 | system_properties::write("microdroid_manager.config_done", "1") |
| 379 | .context("failed to write microdroid_manager.config_done")?; |
| 380 | |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 381 | // Wait until zipfuse has mounted the APKs so we can access the payload |
| 382 | zipfuse.wait_until_done()?; |
Alan Stokes | 60f8220 | 2022-10-07 16:40:07 +0100 | [diff] [blame] | 383 | |
Shikha Panwar | ddc124b | 2022-11-28 19:17:54 +0000 | [diff] [blame] | 384 | // Wait for encryptedstore to finish mounting the storage (if enabled) before setting |
| 385 | // microdroid_manager.init_done. Reason is init stops uneventd after that. |
| 386 | // Encryptedstore, however requires ueventd |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 387 | if let Some(mut child) = encryptedstore_child { |
| 388 | let exitcode = child.wait().context("Wait for encryptedstore child")?; |
| 389 | ensure!(exitcode.success(), "Unable to prepare encrypted storage. Exitcode={}", exitcode); |
| 390 | } |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 391 | |
Alan Stokes | 26efd19 | 2023-11-06 16:30:15 +0000 | [diff] [blame] | 392 | // Wait for init to have finished booting. |
Nikita Ioffe | 57bc8d7 | 2022-11-27 00:50:50 +0000 | [diff] [blame] | 393 | wait_for_property_true("dev.bootcomplete").context("failed waiting for dev.bootcomplete")?; |
Alan Stokes | 26efd19 | 2023-11-06 16:30:15 +0000 | [diff] [blame] | 394 | |
| 395 | // And then tell it we're done so unnecessary services can be shut down. |
Shikha Panwar | 3f6f6a5 | 2022-11-29 17:28:36 +0000 | [diff] [blame] | 396 | system_properties::write("microdroid_manager.init_done", "1") |
| 397 | .context("set microdroid_manager.init_done")?; |
Inseob Kim | c16b0cc | 2023-01-26 14:57:24 +0900 | [diff] [blame] | 398 | |
Nikita Ioffe | 57bc8d7 | 2022-11-27 00:50:50 +0000 | [diff] [blame] | 399 | info!("boot completed, time to run payload"); |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 400 | exec_task(task, service).context("Failed to run payload") |
Alan Stokes | 01b3ef0 | 2022-09-22 17:43:24 +0100 | [diff] [blame] | 401 | } |
| 402 | |
Alan Stokes | 0375496 | 2023-11-06 15:36:09 +0000 | [diff] [blame] | 403 | fn post_payload_work() -> Result<()> { |
| 404 | // Sync the encrypted storage filesystem (flushes the filesystem caches). |
| 405 | if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() { |
| 406 | let mountpoint = CString::new(ENCRYPTEDSTORE_MOUNTPOINT).unwrap(); |
| 407 | |
| 408 | // SAFETY: `mountpoint` is a valid C string. `syncfs` and `close` are safe for any parameter |
| 409 | // values. |
| 410 | let ret = unsafe { |
| 411 | let dirfd = libc::open( |
| 412 | mountpoint.as_ptr(), |
| 413 | libc::O_DIRECTORY | libc::O_RDONLY | libc::O_CLOEXEC, |
| 414 | ); |
| 415 | ensure!(dirfd >= 0, "Unable to open {:?}", mountpoint); |
| 416 | let ret = libc::syncfs(dirfd); |
| 417 | libc::close(dirfd); |
| 418 | ret |
| 419 | }; |
| 420 | if ret != 0 { |
| 421 | error!("failed to sync encrypted storage."); |
| 422 | return Err(anyhow!(std::io::Error::last_os_error())); |
| 423 | } |
| 424 | } |
| 425 | Ok(()) |
| 426 | } |
| 427 | |
Alan Stokes | 0375496 | 2023-11-06 15:36:09 +0000 | [diff] [blame] | 428 | fn mount_extra_apks(config: &VmPayloadConfig, zipfuse: &mut Zipfuse) -> Result<()> { |
| 429 | // For now, only the number of apks is important, as the mount point and dm-verity name is fixed |
| 430 | for i in 0..config.extra_apks.len() { |
| 431 | let mount_dir = format!("/mnt/extra-apk/{i}"); |
| 432 | create_dir(Path::new(&mount_dir)).context("Failed to create mount dir for extra apks")?; |
| 433 | |
| 434 | let mount_for_exec = |
| 435 | if cfg!(multi_tenant) { MountForExec::Allowed } else { MountForExec::Disallowed }; |
| 436 | // These run asynchronously in parallel - we wait later for them to complete. |
| 437 | zipfuse.mount( |
| 438 | mount_for_exec, |
| 439 | "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:extra_apk_file:s0", |
| 440 | Path::new(&format!("/dev/block/mapper/extra-apk-{i}")), |
| 441 | Path::new(&mount_dir), |
| 442 | format!("microdroid_manager.extra_apk.mounted.{i}"), |
| 443 | )?; |
| 444 | } |
| 445 | |
| 446 | Ok(()) |
| 447 | } |
| 448 | |
| 449 | fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> { |
| 450 | // The host is running a VirtualMachineService for this VM on a port equal |
| 451 | // to the CID of this VM. |
| 452 | let port = vsock::get_local_cid().context("Could not determine local CID")?; |
| 453 | RpcSession::new() |
| 454 | .setup_vsock_client(VMADDR_CID_HOST, port) |
| 455 | .context("Could not connect to IVirtualMachineService") |
| 456 | } |
| 457 | |
| 458 | /// Prepares a socket file descriptor for the vm payload service. |
| 459 | /// |
| 460 | /// # Safety |
| 461 | /// |
| 462 | /// The caller must ensure that this function is the only place that claims ownership |
| 463 | /// of the file descriptor and it is called only once. |
| 464 | unsafe fn prepare_vm_payload_service_socket() -> Result<OwnedFd> { |
| 465 | let raw_fd = android_get_control_socket(VM_PAYLOAD_SERVICE_SOCKET_NAME)?; |
| 466 | |
| 467 | // Creating OwnedFd for stdio FDs is not safe. |
| 468 | if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) { |
| 469 | bail!("File descriptor {raw_fd} is standard I/O descriptor"); |
| 470 | } |
| 471 | // SAFETY: Initializing OwnedFd for a RawFd created by the init. |
| 472 | // We checked that the integer value corresponds to a valid FD and that the caller |
| 473 | // ensures that this is the only place to claim its ownership. |
| 474 | Ok(unsafe { OwnedFd::from_raw_fd(raw_fd) }) |
| 475 | } |
| 476 | |
| 477 | fn is_strict_boot() -> bool { |
| 478 | Path::new(AVF_STRICT_BOOT).exists() |
| 479 | } |
| 480 | |
| 481 | fn is_new_instance() -> bool { |
| 482 | Path::new(AVF_NEW_INSTANCE).exists() |
| 483 | } |
| 484 | |
| 485 | fn is_verified_boot() -> bool { |
| 486 | !Path::new(DEBUG_MICRODROID_NO_VERIFIED_BOOT).exists() |
| 487 | } |
| 488 | |
| 489 | fn is_debuggable() -> Result<bool> { |
| 490 | Ok(system_properties::read_bool(DEBUGGABLE_PROP, true)?) |
| 491 | } |
| 492 | |
| 493 | fn should_export_tombstones(config: &VmPayloadConfig) -> bool { |
| 494 | match config.export_tombstones { |
| 495 | Some(b) => b, |
| 496 | None => is_debuggable().unwrap_or(false), |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /// Get debug policy value in bool. It's true iff the value is explicitly set to <1>. |
| 501 | fn get_debug_policy_bool(path: &'static str) -> Result<Option<bool>> { |
| 502 | let mut file = match File::open(path) { |
| 503 | Ok(dp) => dp, |
| 504 | Err(e) => { |
| 505 | info!( |
| 506 | "Assumes that debug policy is disabled because failed to read debug policy ({e:?})" |
| 507 | ); |
| 508 | return Ok(Some(false)); |
| 509 | } |
| 510 | }; |
| 511 | let mut log: [u8; 4] = Default::default(); |
| 512 | file.read_exact(&mut log).context("Malformed data in {path}")?; |
| 513 | // DT spec uses big endian although Android is always little endian. |
| 514 | Ok(Some(u32::from_be_bytes(log) == 1)) |
| 515 | } |
| 516 | |
Alan Stokes | 60f8220 | 2022-10-07 16:40:07 +0100 | [diff] [blame] | 517 | enum MountForExec { |
| 518 | Allowed, |
| 519 | Disallowed, |
| 520 | } |
| 521 | |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 522 | #[derive(Default)] |
| 523 | struct Zipfuse { |
| 524 | ready_properties: Vec<String>, |
| 525 | } |
| 526 | |
| 527 | impl Zipfuse { |
| 528 | fn mount( |
| 529 | &mut self, |
| 530 | noexec: MountForExec, |
| 531 | option: &str, |
| 532 | zip_path: &Path, |
| 533 | mount_dir: &Path, |
| 534 | ready_prop: String, |
| 535 | ) -> Result<Child> { |
| 536 | let mut cmd = Command::new(ZIPFUSE_BIN); |
| 537 | if let MountForExec::Disallowed = noexec { |
| 538 | cmd.arg("--noexec"); |
| 539 | } |
Alan Stokes | 1294f94 | 2023-08-21 14:34:12 +0100 | [diff] [blame] | 540 | // Let root own the files in APK, so we can access them, but set the group to |
| 541 | // allow all payloads to have access too. |
| 542 | let (uid, gid) = (microdroid_uids::ROOT_UID, microdroid_uids::MICRODROID_PAYLOAD_GID); |
| 543 | |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 544 | cmd.args(["-p", &ready_prop, "-o", option]); |
Alan Stokes | 1294f94 | 2023-08-21 14:34:12 +0100 | [diff] [blame] | 545 | cmd.args(["-u", &uid.to_string()]); |
| 546 | cmd.args(["-g", &gid.to_string()]); |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 547 | cmd.arg(zip_path).arg(mount_dir); |
| 548 | self.ready_properties.push(ready_prop); |
| 549 | cmd.spawn().with_context(|| format!("Failed to run zipfuse for {mount_dir:?}")) |
Andrew Scull | cc339a1 | 2022-07-04 12:44:19 +0000 | [diff] [blame] | 550 | } |
Alan Stokes | 960c903 | 2022-12-07 16:53:45 +0000 | [diff] [blame] | 551 | |
| 552 | fn wait_until_done(self) -> Result<()> { |
| 553 | // We check the last-started check first in the hope that by the time it is done |
| 554 | // all or most of the others will also be done, minimising the number of times we |
| 555 | // block on a property. |
| 556 | for property in self.ready_properties.into_iter().rev() { |
| 557 | wait_for_property_true(&property) |
| 558 | .with_context(|| format!("Failed waiting for {property}"))?; |
| 559 | } |
| 560 | Ok(()) |
Alan Stokes | 60f8220 | 2022-10-07 16:40:07 +0100 | [diff] [blame] | 561 | } |
Inseob Kim | 217038e | 2021-11-25 11:15:06 +0900 | [diff] [blame] | 562 | } |
| 563 | |
Alan Stokes | 60f8220 | 2022-10-07 16:40:07 +0100 | [diff] [blame] | 564 | fn wait_for_property_true(property_name: &str) -> Result<()> { |
| 565 | let mut prop = PropertyWatcher::new(property_name)?; |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 566 | loop { |
Andrew Walbran | d9c766e | 2023-05-10 15:15:39 +0000 | [diff] [blame] | 567 | prop.wait(None)?; |
Alan Stokes | 60f8220 | 2022-10-07 16:40:07 +0100 | [diff] [blame] | 568 | if system_properties::read_bool(property_name, false)? { |
Jiyong Park | bb4a987 | 2021-09-06 15:59:21 +0900 | [diff] [blame] | 569 | break; |
| 570 | } |
| 571 | } |
Jooyung Han | 19c1d6c | 2021-08-06 14:08:16 +0900 | [diff] [blame] | 572 | Ok(()) |
| 573 | } |
| 574 | |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 575 | fn load_config(payload_metadata: PayloadMetadata) -> Result<VmPayloadConfig> { |
| 576 | match payload_metadata { |
Ludovic Barman | 93ee308 | 2023-06-20 12:18:43 +0000 | [diff] [blame] | 577 | PayloadMetadata::ConfigPath(path) => { |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 578 | let path = Path::new(&path); |
| 579 | info!("loading config from {:?}...", path); |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 580 | let file = ioutil::wait_for_file(path, WAIT_TIMEOUT) |
| 581 | .with_context(|| format!("Failed to read {:?}", path))?; |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 582 | Ok(serde_json::from_reader(file)?) |
| 583 | } |
Ludovic Barman | 93ee308 | 2023-06-20 12:18:43 +0000 | [diff] [blame] | 584 | PayloadMetadata::Config(payload_config) => { |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 585 | let task = Task { |
| 586 | type_: TaskType::MicrodroidLauncher, |
Alan Stokes | 8f12f2b | 2023-01-09 09:19:20 +0000 | [diff] [blame] | 587 | command: payload_config.payload_binary_name, |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 588 | }; |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 589 | // We don't care about the paths, only the number of extra APKs really matters. |
| 590 | let extra_apks = (0..payload_config.extra_apk_count) |
| 591 | .map(|i| ApkConfig { path: format!("extra-apk-{i}") }) |
| 592 | .collect(); |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 593 | Ok(VmPayloadConfig { |
| 594 | os: OsConfig { name: "microdroid".to_owned() }, |
| 595 | task: Some(task), |
| 596 | apexes: vec![], |
Alan Stokes | fda7084 | 2023-12-20 17:50:14 +0000 | [diff] [blame] | 597 | extra_apks, |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 598 | prefer_staged: false, |
Inseob Kim | ab1037d | 2023-02-08 17:03:31 +0900 | [diff] [blame] | 599 | export_tombstones: None, |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 600 | enable_authfs: false, |
| 601 | }) |
| 602 | } |
Ludovic Barman | 93ee308 | 2023-06-20 12:18:43 +0000 | [diff] [blame] | 603 | _ => bail!("Failed to match config against a config type."), |
Alan Stokes | 1f417c9 | 2022-09-29 15:13:28 +0100 | [diff] [blame] | 604 | } |
Jooyung Han | 634e2d7 | 2021-06-10 16:27:38 +0900 | [diff] [blame] | 605 | } |
| 606 | |
Jaewan Kim | 3124ef0 | 2023-03-23 19:25:20 +0900 | [diff] [blame] | 607 | /// Loads the crashkernel into memory using kexec if debuggable or debug policy says so. |
| 608 | /// The VM should be loaded with `crashkernel=' parameter in the cmdline to allocate memory |
| 609 | /// for crashkernel. |
Jiyong Park | 202856e | 2022-08-22 16:04:26 +0900 | [diff] [blame] | 610 | fn load_crashkernel_if_supported() -> Result<()> { |
| 611 | let supported = std::fs::read_to_string("/proc/cmdline")?.contains(" crashkernel="); |
| 612 | info!("ramdump supported: {}", supported); |
Jaewan Kim | 3124ef0 | 2023-03-23 19:25:20 +0900 | [diff] [blame] | 613 | |
| 614 | if !supported { |
| 615 | return Ok(()); |
| 616 | } |
| 617 | |
Alan Stokes | 1125e01 | 2023-10-13 12:31:10 +0100 | [diff] [blame] | 618 | let debuggable = is_debuggable()?; |
Jaewan Kim | 3124ef0 | 2023-03-23 19:25:20 +0900 | [diff] [blame] | 619 | let ramdump = get_debug_policy_bool(AVF_DEBUG_POLICY_RAMDUMP)?.unwrap_or_default(); |
| 620 | let requested = debuggable | ramdump; |
| 621 | |
| 622 | if requested { |
Jiyong Park | 202856e | 2022-08-22 16:04:26 +0900 | [diff] [blame] | 623 | let status = Command::new("/system/bin/kexec_load").status()?; |
| 624 | if !status.success() { |
| 625 | return Err(anyhow!("Failed to load crashkernel: {:?}", status)); |
| 626 | } |
Jaewan Kim | 3124ef0 | 2023-03-23 19:25:20 +0900 | [diff] [blame] | 627 | info!("ramdump is loaded: debuggable={debuggable}, ramdump={ramdump}"); |
Jiyong Park | 202856e | 2022-08-22 16:04:26 +0900 | [diff] [blame] | 628 | } |
| 629 | Ok(()) |
| 630 | } |
| 631 | |
Inseob Kim | 090b70b | 2022-11-16 20:01:14 +0900 | [diff] [blame] | 632 | /// Executes the given task. |
Jooyung Han | 5c6d417 | 2021-12-06 14:17:52 +0900 | [diff] [blame] | 633 | fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<i32> { |
Jiyong Park | 8611a6c | 2021-07-09 18:17:44 +0900 | [diff] [blame] | 634 | info!("executing main task {:?}...", task); |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 635 | let mut command = match task.type_ { |
Alan Stokes | 1294f94 | 2023-08-21 14:34:12 +0100 | [diff] [blame] | 636 | TaskType::Executable => { |
Alan Stokes | 679ddf3 | 2023-09-01 11:14:48 +0100 | [diff] [blame] | 637 | // TODO(b/297501338): Figure out how to handle non-root for system payloads. |
Alan Stokes | 1294f94 | 2023-08-21 14:34:12 +0100 | [diff] [blame] | 638 | Command::new(&task.command) |
| 639 | } |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 640 | TaskType::MicrodroidLauncher => { |
| 641 | let mut command = Command::new("/system/bin/microdroid_launcher"); |
| 642 | command.arg(find_library_path(&task.command)?); |
Alan Stokes | 1294f94 | 2023-08-21 14:34:12 +0100 | [diff] [blame] | 643 | command.uid(microdroid_uids::MICRODROID_PAYLOAD_UID); |
| 644 | command.gid(microdroid_uids::MICRODROID_PAYLOAD_GID); |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame] | 645 | command |
| 646 | } |
| 647 | }; |
Nikita Ioffe | 3452ee2 | 2022-12-15 00:31:56 +0000 | [diff] [blame] | 648 | |
Andrew Walbran | aac6830 | 2023-07-21 19:05:34 +0100 | [diff] [blame] | 649 | // SAFETY: We are not accessing any resource of the parent process. This means we can't make any |
| 650 | // log calls inside the closure. |
Nikita Ioffe | 3452ee2 | 2022-12-15 00:31:56 +0000 | [diff] [blame] | 651 | unsafe { |
Nikita Ioffe | 3452ee2 | 2022-12-15 00:31:56 +0000 | [diff] [blame] | 652 | command.pre_exec(|| { |
Nikita Ioffe | 3452ee2 | 2022-12-15 00:31:56 +0000 | [diff] [blame] | 653 | // It is OK to continue with payload execution even if the calls below fail, since |
| 654 | // whether process can use a capability is controlled by the SELinux. Dropping the |
| 655 | // capabilities here is just another defense-in-depth layer. |
Andrew Walbran | aac6830 | 2023-07-21 19:05:34 +0100 | [diff] [blame] | 656 | let _ = cap::drop_inheritable_caps(); |
| 657 | let _ = cap::drop_bounding_set(); |
Nikita Ioffe | 3452ee2 | 2022-12-15 00:31:56 +0000 | [diff] [blame] | 658 | Ok(()) |
| 659 | }); |
| 660 | } |
| 661 | |
Inseob Kim | 090b70b | 2022-11-16 20:01:14 +0900 | [diff] [blame] | 662 | command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 663 | |
| 664 | info!("notifying payload started"); |
Inseob Kim | c7d28c7 | 2021-10-25 14:28:10 +0000 | [diff] [blame] | 665 | service.notifyPayloadStarted()?; |
Inseob Kim | 7f61fe7 | 2021-08-20 20:50:47 +0900 | [diff] [blame] | 666 | |
Inseob Kim | 86ca016 | 2021-10-20 02:21:02 +0000 | [diff] [blame] | 667 | let exit_status = command.spawn()?.wait()?; |
Frederick Mayle | b5f7b6b | 2022-11-11 15:24:03 -0800 | [diff] [blame] | 668 | match exit_status.code() { |
| 669 | Some(exit_code) => Ok(exit_code), |
| 670 | None => Err(match exit_status.signal() { |
| 671 | Some(signal) => anyhow!( |
| 672 | "Payload exited due to signal: {} ({})", |
| 673 | signal, |
| 674 | Signal::try_from(signal).map_or("unknown", |s| s.as_str()) |
| 675 | ), |
| 676 | None => anyhow!("Payload has neither exit code nor signal"), |
| 677 | }), |
| 678 | } |
Jooyung Han | 347d9f2 | 2021-05-28 00:05:14 +0900 | [diff] [blame] | 679 | } |
Jooyung Han | 634e2d7 | 2021-06-10 16:27:38 +0900 | [diff] [blame] | 680 | |
Jooyung Han | 634e2d7 | 2021-06-10 16:27:38 +0900 | [diff] [blame] | 681 | fn find_library_path(name: &str) -> Result<String> { |
| 682 | let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?; |
| 683 | let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?; |
| 684 | let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?; |
Alice Wang | 6bbb6da | 2022-10-26 12:44:06 +0000 | [diff] [blame] | 685 | let path = format!("{}/lib/{}/{}", VM_APK_CONTENTS_PATH, abi, name); |
Jooyung Han | 634e2d7 | 2021-06-10 16:27:38 +0900 | [diff] [blame] | 686 | |
Alan Stokes | 3ba10fd | 2022-10-06 15:46:51 +0100 | [diff] [blame] | 687 | let metadata = fs::metadata(&path).with_context(|| format!("Unable to access {}", path))?; |
Jooyung Han | 634e2d7 | 2021-06-10 16:27:38 +0900 | [diff] [blame] | 688 | if !metadata.is_file() { |
| 689 | bail!("{} is not a file", &path); |
| 690 | } |
| 691 | |
| 692 | Ok(path) |
| 693 | } |
Jiyong Park | 21ce2c5 | 2021-08-28 02:32:17 +0900 | [diff] [blame] | 694 | |
Shikha Panwar | 95084df | 2023-07-22 11:47:45 +0000 | [diff] [blame] | 695 | fn prepare_encryptedstore(vm_secret: &VmSecret) -> Result<Child> { |
Alice Wang | 7e6c935 | 2023-02-15 15:44:13 +0000 | [diff] [blame] | 696 | let mut key = ZVec::new(ENCRYPTEDSTORE_KEYSIZE)?; |
Shikha Panwar | 3d3a70a | 2023-08-21 20:02:08 +0000 | [diff] [blame] | 697 | vm_secret.derive_encryptedstore_key(&mut key)?; |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 698 | let mut cmd = Command::new(ENCRYPTEDSTORE_BIN); |
| 699 | cmd.arg("--blkdevice") |
| 700 | .arg(ENCRYPTEDSTORE_BACKING_DEVICE) |
| 701 | .arg("--key") |
| 702 | .arg(hex::encode(&*key)) |
Shikha Panwar | 9fd198f | 2022-11-18 17:43:43 +0000 | [diff] [blame] | 703 | .args(["--mountpoint", ENCRYPTEDSTORE_MOUNTPOINT]) |
Shikha Panwar | 566c967 | 2022-11-15 14:39:58 +0000 | [diff] [blame] | 704 | .spawn() |
| 705 | .context("encryptedstore failed") |
| 706 | } |