blob: 57ad35d9cf5766d4467358df3a1ad8577ebe7527 [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};
Nikita Ioffeabb6d8a2024-03-12 23:01:47 +000046use nix::mount::{umount2, MntFlags};
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;
Shikha Panwar0503cb02024-01-05 10:11:28 +000053use secretkeeper_comm::data_types::ID_SIZE;
Alan Stokes3ba10fd2022-10-06 15:46:51 +010054use std::borrow::Cow::{Borrowed, Owned};
Inseob Kim7ff121c2022-11-14 18:13:23 +090055use std::env;
Shikha Panwardef7ef92023-01-06 08:35:48 +000056use std::ffi::CString;
Alan Stokes1125e012023-10-13 12:31:10 +010057use std::fs::{self, create_dir, File, OpenOptions};
Jaewan Kim3124ef02023-03-23 19:25:20 +090058use std::io::{Read, Write};
Jiyong Park198eb972024-09-11 08:29:22 +090059use std::os::unix::io::OwnedFd;
Nikita Ioffe3452ee22022-12-15 00:31:56 +000060use std::os::unix::process::CommandExt;
Frederick Mayleb5f7b6b2022-11-11 15:24:03 -080061use std::os::unix::process::ExitStatusExt;
Jooyung Hanf48ceb42021-06-01 18:00:04 +090062use std::path::Path;
Inseob Kim217038e2021-11-25 11:15:06 +090063use std::process::{Child, Command, Stdio};
Jiyong Park8611a6c2021-07-09 18:17:44 +090064use std::str;
Alan Stokes1125e012023-10-13 12:31:10 +010065use std::time::Duration;
Shikha Panwar95084df2023-07-22 11:47:45 +000066use vm_secret::VmSecret;
Jooyung Han634e2d72021-06-10 16:27:38 +090067
68const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jaewan Kim1f0135b2024-01-31 14:59:47 +090069const AVF_STRICT_BOOT: &str = "/proc/device-tree/chosen/avf,strict-boot";
70const AVF_NEW_INSTANCE: &str = "/proc/device-tree/chosen/avf,new-instance";
71const AVF_DEBUG_POLICY_RAMDUMP: &str = "/proc/device-tree/avf/guest/common/ramdump";
Inseob Kime379e7d2022-07-22 18:55:18 +090072const DEBUG_MICRODROID_NO_VERIFIED_BOOT: &str =
Jaewan Kim1f0135b2024-01-31 14:59:47 +090073 "/proc/device-tree/virtualization/guest/debug-microdroid,no-verified-boot";
Shikha Panwar14abe442024-02-23 15:04:27 +000074const SECRETKEEPER_KEY: &str = "/proc/device-tree/avf/secretkeeper_public_key";
75const INSTANCE_ID_PATH: &str = "/proc/device-tree/avf/untrusted/instance-id";
Shikha Panware45e9422024-02-28 21:18:10 +000076const DEFER_ROLLBACK_PROTECTION: &str = "/proc/device-tree/avf/untrusted/defer-rollback-protection";
Jooyung Han347d9f22021-05-28 00:05:14 +090077
Alan Stokes4fb201c2023-02-08 17:39:05 +000078const ENCRYPTEDSTORE_BIN: &str = "/system/bin/encryptedstore";
79const ZIPFUSE_BIN: &str = "/system/bin/zipfuse";
80
Jiyong Parkbb4a9872021-09-06 15:59:21 +090081const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
Seungjae Yoofa22bb02022-12-08 16:38:42 +090082const DEBUGGABLE_PROP: &str = "ro.boot.microdroid.debuggable";
Jiyong Parkbb4a9872021-09-06 15:59:21 +090083
Inseob Kim11f40d02022-06-13 17:16:00 +090084// SYNC WITH virtualizationservice/src/crosvm.rs
85const FAILURE_SERIAL_DEVICE: &str = "/dev/ttyS1";
86
Shikha Panwar566c9672022-11-15 14:39:58 +000087const ENCRYPTEDSTORE_BACKING_DEVICE: &str = "/dev/block/by-name/encryptedstore";
Alice Wang62f7e642023-02-10 09:55:13 +000088const ENCRYPTEDSTORE_KEYSIZE: usize = 32;
Shikha Panwar566c9672022-11-15 14:39:58 +000089
Nikita Ioffeabb6d8a2024-03-12 23:01:47 +000090const DICE_CHAIN_FILE: &str = "/microdroid_resources/dice_chain.raw";
91
Jooyung Handd0a1732021-11-23 15:26:20 +090092#[derive(thiserror::Error, Debug)]
93enum MicrodroidError {
Inseob Kim11f40d02022-06-13 17:16:00 +090094 #[error("Cannot connect to virtualization service: {0}")]
95 FailedToConnectToVirtualizationService(String),
Jooyung Handd0a1732021-11-23 15:26:20 +090096 #[error("Payload has changed: {0}")]
97 PayloadChanged(String),
98 #[error("Payload verification has failed: {0}")]
99 PayloadVerificationFailed(String),
Jooyung Han5c6d4172021-12-06 14:17:52 +0900100 #[error("Payload config is invalid: {0}")]
Alan Stokesbbed8872023-10-19 13:17:12 +0100101 PayloadInvalidConfig(String),
Jooyung Handd0a1732021-11-23 15:26:20 +0900102}
103
Alan Stokes2bead0d2022-09-05 16:58:34 +0100104fn translate_error(err: &Error) -> (ErrorCode, String) {
Jooyung Handd0a1732021-11-23 15:26:20 +0900105 if let Some(e) = err.downcast_ref::<MicrodroidError>() {
106 match e {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100107 MicrodroidError::PayloadChanged(msg) => (ErrorCode::PAYLOAD_CHANGED, msg.to_string()),
Jooyung Handd0a1732021-11-23 15:26:20 +0900108 MicrodroidError::PayloadVerificationFailed(msg) => {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100109 (ErrorCode::PAYLOAD_VERIFICATION_FAILED, msg.to_string())
Jooyung Handd0a1732021-11-23 15:26:20 +0900110 }
Alan Stokesbbed8872023-10-19 13:17:12 +0100111 MicrodroidError::PayloadInvalidConfig(msg) => {
112 (ErrorCode::PAYLOAD_INVALID_CONFIG, msg.to_string())
Alan Stokes2bead0d2022-09-05 16:58:34 +0100113 }
Inseob Kim11f40d02022-06-13 17:16:00 +0900114 // Connection failure won't be reported to VS; return the default value
115 MicrodroidError::FailedToConnectToVirtualizationService(msg) => {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100116 (ErrorCode::UNKNOWN, msg.to_string())
Inseob Kim11f40d02022-06-13 17:16:00 +0900117 }
Jooyung Handd0a1732021-11-23 15:26:20 +0900118 }
119 } else {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100120 (ErrorCode::UNKNOWN, err.to_string())
Jooyung Handd0a1732021-11-23 15:26:20 +0900121 }
122}
123
Inseob Kim11f40d02022-06-13 17:16:00 +0900124fn write_death_reason_to_serial(err: &Error) -> Result<()> {
125 let death_reason = if let Some(e) = err.downcast_ref::<MicrodroidError>() {
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100126 Borrowed(match e {
Inseob Kim11f40d02022-06-13 17:16:00 +0900127 MicrodroidError::FailedToConnectToVirtualizationService(_) => {
128 "MICRODROID_FAILED_TO_CONNECT_TO_VIRTUALIZATION_SERVICE"
129 }
130 MicrodroidError::PayloadChanged(_) => "MICRODROID_PAYLOAD_HAS_CHANGED",
131 MicrodroidError::PayloadVerificationFailed(_) => {
132 "MICRODROID_PAYLOAD_VERIFICATION_FAILED"
133 }
Alan Stokesbbed8872023-10-19 13:17:12 +0100134 MicrodroidError::PayloadInvalidConfig(_) => "MICRODROID_INVALID_PAYLOAD_CONFIG",
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100135 })
Inseob Kim11f40d02022-06-13 17:16:00 +0900136 } else {
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100137 // Send context information back after a separator, to ease diagnosis.
138 // These errors occur before the payload runs, so this should not leak sensitive
139 // information.
140 Owned(format!("MICRODROID_UNKNOWN_RUNTIME_ERROR|{:?}", err))
Inseob Kim11f40d02022-06-13 17:16:00 +0900141 };
142
Frederick Mayle402fd2e2024-11-14 17:56:32 -0800143 let mut serial_file = OpenOptions::new().read(false).write(true).open(FAILURE_SERIAL_DEVICE)?;
144 serial_file.write_all(death_reason.as_bytes()).context("serial device write_all failed")?;
145 // Block until the serial port trasmits all the data to the host.
146 nix::sys::termios::tcdrain(&serial_file).context("tcdrain failed")?;
Inseob Kim11f40d02022-06-13 17:16:00 +0900147
148 Ok(())
149}
150
Shikha Panwar14abe442024-02-23 15:04:27 +0000151/// The (host allocated) instance_id can be found at node /avf/untrusted/ in the device tree.
152fn get_instance_id() -> Result<Option<[u8; ID_SIZE]>> {
153 let path = Path::new(INSTANCE_ID_PATH);
154 let instance_id = if path.exists() {
155 Some(
156 fs::read(path)?
157 .try_into()
158 .map_err(|x: Vec<_>| anyhow!("Expected {ID_SIZE} bytes, found {:?}", x.len()))?,
159 )
160 } else {
161 // TODO(b/325094712): x86 support for Device tree in nested guest is limited/broken/
162 // untested. So instance_id will not be present in cuttlefish.
163 None
164 };
165 Ok(instance_id)
166}
167
Shikha Panware45e9422024-02-28 21:18:10 +0000168fn should_defer_rollback_protection() -> bool {
169 Path::new(DEFER_ROLLBACK_PROTECTION).exists()
170}
171
Inseob Kim437f1052022-06-21 11:30:22 +0900172fn main() -> Result<()> {
Jiyong Park198eb972024-09-11 08:29:22 +0900173 // SAFETY: This is very early in the process. Nobody has taken ownership of the inherited FDs
174 // yet.
175 unsafe { rustutils::inherited_fd::init_once()? };
176
Inseob Kim7ff121c2022-11-14 18:13:23 +0900177 // If debuggable, print full backtrace to console log with stdio_to_kmsg
Alan Stokes1125e012023-10-13 12:31:10 +0100178 if is_debuggable()? {
Inseob Kim7ff121c2022-11-14 18:13:23 +0900179 env::set_var("RUST_BACKTRACE", "full");
180 }
181
Inseob Kim437f1052022-06-21 11:30:22 +0900182 scopeguard::defer! {
183 info!("Shutting down...");
Jooyung Hanbfe086f2021-10-28 10:15:45 +0900184 if let Err(e) = system_properties::write("sys.powerctl", "shutdown") {
185 error!("failed to shutdown {:?}", e);
186 }
Jooyung Han311b1202021-09-14 22:00:16 +0900187 }
Inseob Kim437f1052022-06-21 11:30:22 +0900188
189 try_main().map_err(|e| {
190 error!("Failed with {:?}.", e);
191 if let Err(e) = write_death_reason_to_serial(&e) {
192 error!("Failed to write death reason {:?}", e);
193 }
194 e
195 })
Jooyung Han311b1202021-09-14 22:00:16 +0900196}
197
198fn try_main() -> Result<()> {
Jiyong Park2b6346d2023-06-19 13:37:42 +0900199 android_logger::init_once(
200 android_logger::Config::default()
201 .with_tag("microdroid_manager")
Jeff Vander Stoep57da1572024-01-31 10:52:16 +0100202 .with_max_level(log::LevelFilter::Info),
Jiyong Park2b6346d2023-06-19 13:37:42 +0900203 );
Jooyung Han347d9f22021-05-28 00:05:14 +0900204 info!("started.");
205
Jiyong Park198eb972024-09-11 08:29:22 +0900206 let vm_payload_service_fd = android_get_control_socket(VM_PAYLOAD_SERVICE_SOCKET_NAME)?;
Inseob Kim090b70b2022-11-16 20:01:14 +0900207
Jiyong Park202856e2022-08-22 16:04:26 +0900208 load_crashkernel_if_supported().context("Failed to load crashkernel")?;
209
Alice Wangeff58392023-07-04 13:32:09 +0000210 swap::init_swap().context("Failed to initialize swap")?;
Keir Fraser933f0ac2022-10-12 08:23:28 +0000211 info!("swap enabled.");
212
Inseob Kim11f40d02022-06-13 17:16:00 +0900213 let service = get_vms_rpc_binder()
214 .context("cannot connect to VirtualMachineService")
215 .map_err(|e| MicrodroidError::FailedToConnectToVirtualizationService(e.to_string()))?;
Seungjae Yoofd9a0622022-10-14 10:01:29 +0900216
Alice Wangfd222fd2023-05-25 09:37:38 +0000217 match try_run_payload(&service, vm_payload_service_fd) {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900218 Ok(code) => {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900219 if code == 0 {
220 info!("task successfully finished");
221 } else {
222 error!("task exited with exit code: {}", code);
223 }
Shikha Panwardef7ef92023-01-06 08:35:48 +0000224 if let Err(e) = post_payload_work() {
225 error!(
226 "Failed to run post payload work. It is possible that certain tasks
227 like syncing encrypted store might be incomplete. Error: {:?}",
228 e
229 );
230 };
231
232 info!("notifying payload finished");
233 service.notifyPayloadFinished(code)?;
Jooyung Han5c6d4172021-12-06 14:17:52 +0900234 Ok(())
235 }
236 Err(err) => {
Jooyung Han5c6d4172021-12-06 14:17:52 +0900237 let (error_code, message) = translate_error(&err);
238 service.notifyError(error_code, &message)?;
239 Err(err)
240 }
Jooyung Handd0a1732021-11-23 15:26:20 +0900241 }
242}
243
Shikha Panwar185ba932024-03-12 22:35:09 +0000244fn verify_payload_with_instance_img(
245 metadata: &Metadata,
246 dice: &DiceDriver,
247) -> Result<MicrodroidData> {
Jooyung Han311b1202021-09-14 22:00:16 +0900248 let mut instance = InstanceDisk::new().context("Failed to load instance.img")?;
Shikha Panwar185ba932024-03-12 22:35:09 +0000249 let saved_data = instance.read_microdroid_data(dice).context("Failed to read identity data")?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900250
Andrew Scullab72ec52022-03-14 09:10:52 +0000251 if is_strict_boot() {
252 // Provisioning must happen on the first boot and never again.
Shikha Panwar5b7b4942024-12-18 15:32:49 +0000253 if is_new_instance_legacy() {
Andrew Scullab72ec52022-03-14 09:10:52 +0000254 ensure!(
255 saved_data.is_none(),
Alan Stokesbbed8872023-10-19 13:17:12 +0100256 MicrodroidError::PayloadInvalidConfig(
257 "Found instance data on first boot.".to_string()
258 )
Andrew Scullab72ec52022-03-14 09:10:52 +0000259 );
260 } else {
261 ensure!(
262 saved_data.is_some(),
Alan Stokesbbed8872023-10-19 13:17:12 +0100263 MicrodroidError::PayloadInvalidConfig("Instance data not found.".to_string())
Andrew Scullab72ec52022-03-14 09:10:52 +0000264 );
265 };
266 }
267
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900268 // Verify the payload before using it.
Shikha Panwar185ba932024-03-12 22:35:09 +0000269 let extracted_data = verify_payload(metadata, saved_data.as_ref())
Inseob Kim11f40d02022-06-13 17:16:00 +0900270 .context("Payload verification failed")
Inseob Kimbe8afd62024-09-03 11:12:10 +0900271 .map_err(|e| MicrodroidError::PayloadVerificationFailed(format!("{:?}", e)))?;
Inseob Kime379e7d2022-07-22 18:55:18 +0900272
273 // In case identity is ignored (by debug policy), we should reuse existing payload data, even
274 // when the payload is changed. This is to keep the derived secret same as before.
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000275 let instance_data = if let Some(saved_data) = saved_data {
Inseob Kime379e7d2022-07-22 18:55:18 +0900276 if !is_verified_boot() {
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000277 if saved_data != extracted_data {
Inseob Kime379e7d2022-07-22 18:55:18 +0900278 info!("Detected an update of the payload, but continue (regarding debug policy)")
279 }
280 } else {
281 ensure!(
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000282 saved_data == extracted_data,
Inseob Kime379e7d2022-07-22 18:55:18 +0900283 MicrodroidError::PayloadChanged(String::from(
284 "Detected an update of the payload which isn't supported yet."
285 ))
286 );
287 info!("Saved data is verified.");
288 }
289 saved_data
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900290 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +0900291 info!("Saving verified data.");
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000292 instance
Shikha Panwar185ba932024-03-12 22:35:09 +0000293 .write_microdroid_data(&extracted_data, dice)
Andrew Sculld64ae7d2022-10-05 17:41:43 +0000294 .context("Failed to write identity data")?;
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000295 extracted_data
Inseob Kime379e7d2022-07-22 18:55:18 +0900296 };
Shikha Panwar185ba932024-03-12 22:35:09 +0000297 Ok(instance_data)
298}
299
Shikha Panwar5b7b4942024-12-18 15:32:49 +0000300// The VM instance run can be
301// 1. Either Newly created - which can happen if this is really a new VM instance (or a malicious
302// Android has deleted relevant secrets)
303// 2. Or Re-run from an already seen VM instance.
304#[derive(PartialEq, Eq)]
305enum VmInstanceState {
306 Unknown,
307 NewlyCreated,
308 PreviouslySeen,
309}
310
Shikha Panwar185ba932024-03-12 22:35:09 +0000311fn try_run_payload(
312 service: &Strong<dyn IVirtualMachineService>,
313 vm_payload_service_fd: OwnedFd,
314) -> Result<i32> {
315 let metadata = load_metadata().context("Failed to load payload metadata")?;
Nikita Ioffeabb6d8a2024-03-12 23:01:47 +0000316 let dice = if Path::new(DICE_CHAIN_FILE).exists() {
317 DiceDriver::from_file(Path::new(DICE_CHAIN_FILE))
318 .context("Failed to load DICE from file")?
319 } else {
320 DiceDriver::new(Path::new("/dev/open-dice0"), is_strict_boot())
321 .context("Failed to load DICE from driver")?
322 };
Shikha Panwar185ba932024-03-12 22:35:09 +0000323
Shikha Panware45e9422024-02-28 21:18:10 +0000324 // Microdroid skips checking payload against instance image iff the device supports
325 // secretkeeper. In that case Microdroid use VmSecret::V2, which provide protection against
326 // rollback of boot images and packages.
327 let instance_data = if should_defer_rollback_protection() {
Shikha Panwar185ba932024-03-12 22:35:09 +0000328 verify_payload(&metadata, None)?
329 } else {
330 verify_payload_with_instance_img(&metadata, &dice)?
331 };
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900332
Alan Stokes1f417c92022-09-29 15:13:28 +0100333 let payload_metadata = metadata.payload.ok_or_else(|| {
Alan Stokesbbed8872023-10-19 13:17:12 +0100334 MicrodroidError::PayloadInvalidConfig("No payload config in metadata".to_string())
Alan Stokes1f417c92022-09-29 15:13:28 +0100335 })?;
Alan Stokes0d1ef782022-09-27 13:46:35 +0100336
Inseob Kimb2519c52022-04-14 02:10:09 +0900337 // To minimize the exposure to untrusted data, derive dice profile as soon as possible.
338 info!("DICE derivation for payload");
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000339 let dice_artifacts = dice_derivation(dice, &instance_data, &payload_metadata)?;
Shikha Panwar5b7b4942024-12-18 15:32:49 +0000340 let mut state = VmInstanceState::Unknown;
341 let vm_secret = VmSecret::new(dice_artifacts, service, &mut state)
342 .context("Failed to create VM secrets")?;
343
344 let is_new_instance = match state {
345 VmInstanceState::NewlyCreated => true,
346 VmInstanceState::PreviouslySeen => false,
347 VmInstanceState::Unknown => {
348 // VmSecret instantiation was not able to determine the state. This should only happen
349 // for legacy secret mechanism (V1) - in which case fallback to legacy
350 // instance.img based determination of state.
351 ensure!(
352 !should_defer_rollback_protection(),
353 "VmInstanceState is Unknown whilst guest is expected to use V2 based secrets.
354 This should've never happened"
355 );
356 is_new_instance_legacy()
357 }
358 };
Shikha Panwar566c9672022-11-15 14:39:58 +0000359
Alan Stokes9a7f67e2023-11-07 09:37:40 +0000360 if cfg!(dice_changes) {
361 // Now that the DICE derivation is done, it's ok to allow payload code to run.
362
363 // Start apexd to activate APEXes. This may allow code within them to run.
364 system_properties::write("ctl.start", "apexd-vm")?;
Nikita Ioffeabb6d8a2024-03-12 23:01:47 +0000365
366 // Unmounting /microdroid_resources is a defence-in-depth effort to ensure that payload
367 // can't get hold of dice chain stored there.
368 umount2("/microdroid_resources", MntFlags::MNT_DETACH)?;
Alan Stokes9a7f67e2023-11-07 09:37:40 +0000369 }
370
Shikha Panwar566c9672022-11-15 14:39:58 +0000371 // Run encryptedstore binary to prepare the storage
372 let encryptedstore_child = if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() {
373 info!("Preparing encryptedstore ...");
Shikha Panwar95084df2023-07-22 11:47:45 +0000374 Some(prepare_encryptedstore(&vm_secret).context("encryptedstore run")?)
Shikha Panwar566c9672022-11-15 14:39:58 +0000375 } else {
376 None
377 };
Inseob Kimb2519c52022-04-14 02:10:09 +0900378
Alan Stokes960c9032022-12-07 16:53:45 +0000379 let mut zipfuse = Zipfuse::default();
380
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900381 // Before reading a file from the APK, start zipfuse
Alan Stokes960c9032022-12-07 16:53:45 +0000382 zipfuse.mount(
Alan Stokes60f82202022-10-07 16:40:07 +0100383 MountForExec::Allowed,
Inseob Kim217038e2021-11-25 11:15:06 +0900384 "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:system_file:s0",
Alan Stokes1125e012023-10-13 12:31:10 +0100385 Path::new(verify::DM_MOUNTED_APK_PATH),
Alice Wang6bbb6da2022-10-26 12:44:06 +0000386 Path::new(VM_APK_CONTENTS_PATH),
Alan Stokes960c9032022-12-07 16:53:45 +0000387 "microdroid_manager.apk.mounted".to_owned(),
388 )?;
Jiyong Park21ce2c52021-08-28 02:32:17 +0900389
Andrew Scull4d262dc2022-10-21 13:14:33 +0000390 // Restricted APIs are only allowed to be used by platform or test components. Infer this from
391 // the use of a VM config file since those can only be used by platform and test components.
392 let allow_restricted_apis = match payload_metadata {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000393 PayloadMetadata::ConfigPath(_) => true,
394 PayloadMetadata::Config(_) => false,
395 _ => false, // default is false for safety
Andrew Scull4d262dc2022-10-21 13:14:33 +0000396 };
397
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100398 let config = load_config(payload_metadata).context("Failed to load payload metadata")?;
Shikha Panwar6f03c942022-04-13 20:26:50 +0000399
Alan Stokes01b3ef02022-09-22 17:43:24 +0100400 let task = config
401 .task
402 .as_ref()
Alan Stokesbbed8872023-10-19 13:17:12 +0100403 .ok_or_else(|| MicrodroidError::PayloadInvalidConfig("No task in VM config".to_string()))?;
Alan Stokes01b3ef02022-09-22 17:43:24 +0100404
Alice Wang061478b2023-04-11 13:26:17 +0000405 ensure!(
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000406 config.extra_apks.len() == instance_data.extra_apks_data.len(),
Alice Wang061478b2023-04-11 13:26:17 +0000407 "config expects {} extra apks, but found {}",
408 config.extra_apks.len(),
Alan Stokes26a6a5c2023-11-10 16:18:43 +0000409 instance_data.extra_apks_data.len()
Alice Wang061478b2023-04-11 13:26:17 +0000410 );
Alan Stokes960c9032022-12-07 16:53:45 +0000411 mount_extra_apks(&config, &mut zipfuse)?;
Jooyung Han634e2d72021-06-10 16:27:38 +0900412
Alan Stokes26efd192023-11-06 16:30:15 +0000413 register_vm_payload_service(
414 allow_restricted_apis,
415 service.clone(),
416 vm_secret,
417 vm_payload_service_fd,
Shikha Panwar5b7b4942024-12-18 15:32:49 +0000418 is_new_instance,
Alan Stokes26efd192023-11-06 16:30:15 +0000419 )?;
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000420
Shikha Panwar1a6efcd2023-02-03 19:23:43 +0000421 // Set export_tombstones if enabled
Inseob Kimab1037d2023-02-08 17:03:31 +0900422 if should_export_tombstones(&config) {
Shikha Panwar1a6efcd2023-02-03 19:23:43 +0000423 // This property is read by tombstone_handler.
424 system_properties::write("microdroid_manager.export_tombstones.enabled", "1")
425 .context("set microdroid_manager.export_tombstones.enabled")?;
Inseob Kimcd9c1dd2022-07-13 17:13:45 +0900426 }
427
Alan Stokes26efd192023-11-06 16:30:15 +0000428 // Wait until apex config is done. (e.g. linker configuration for apexes)
429 wait_for_property_true(APEX_CONFIG_DONE_PROP).context("Failed waiting for apex config done")?;
430
431 // Trigger init post-fs-data. This will start authfs if we wask it to.
432 if config.enable_authfs {
433 system_properties::write("microdroid_manager.authfs.enabled", "1")
434 .context("failed to write microdroid_manager.authfs.enabled")?;
435 }
436 system_properties::write("microdroid_manager.config_done", "1")
437 .context("failed to write microdroid_manager.config_done")?;
438
Alan Stokes960c9032022-12-07 16:53:45 +0000439 // Wait until zipfuse has mounted the APKs so we can access the payload
440 zipfuse.wait_until_done()?;
Alan Stokes60f82202022-10-07 16:40:07 +0100441
Shikha Panwarddc124b2022-11-28 19:17:54 +0000442 // Wait for encryptedstore to finish mounting the storage (if enabled) before setting
443 // microdroid_manager.init_done. Reason is init stops uneventd after that.
444 // Encryptedstore, however requires ueventd
Shikha Panwar566c9672022-11-15 14:39:58 +0000445 if let Some(mut child) = encryptedstore_child {
446 let exitcode = child.wait().context("Wait for encryptedstore child")?;
447 ensure!(exitcode.success(), "Unable to prepare encrypted storage. Exitcode={}", exitcode);
448 }
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100449
Alan Stokes26efd192023-11-06 16:30:15 +0000450 // Wait for init to have finished booting.
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000451 wait_for_property_true("dev.bootcomplete").context("failed waiting for dev.bootcomplete")?;
Alan Stokes26efd192023-11-06 16:30:15 +0000452
453 // And then tell it we're done so unnecessary services can be shut down.
Shikha Panwar3f6f6a52022-11-29 17:28:36 +0000454 system_properties::write("microdroid_manager.init_done", "1")
455 .context("set microdroid_manager.init_done")?;
Inseob Kimc16b0cc2023-01-26 14:57:24 +0900456
Nikita Ioffe57bc8d72022-11-27 00:50:50 +0000457 info!("boot completed, time to run payload");
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100458 exec_task(task, service).context("Failed to run payload")
Alan Stokes01b3ef02022-09-22 17:43:24 +0100459}
460
Alan Stokes03754962023-11-06 15:36:09 +0000461fn post_payload_work() -> Result<()> {
462 // Sync the encrypted storage filesystem (flushes the filesystem caches).
463 if Path::new(ENCRYPTEDSTORE_BACKING_DEVICE).exists() {
464 let mountpoint = CString::new(ENCRYPTEDSTORE_MOUNTPOINT).unwrap();
465
466 // SAFETY: `mountpoint` is a valid C string. `syncfs` and `close` are safe for any parameter
467 // values.
468 let ret = unsafe {
469 let dirfd = libc::open(
470 mountpoint.as_ptr(),
471 libc::O_DIRECTORY | libc::O_RDONLY | libc::O_CLOEXEC,
472 );
473 ensure!(dirfd >= 0, "Unable to open {:?}", mountpoint);
474 let ret = libc::syncfs(dirfd);
475 libc::close(dirfd);
476 ret
477 };
478 if ret != 0 {
479 error!("failed to sync encrypted storage.");
480 return Err(anyhow!(std::io::Error::last_os_error()));
481 }
482 }
483 Ok(())
484}
485
Alan Stokes03754962023-11-06 15:36:09 +0000486fn mount_extra_apks(config: &VmPayloadConfig, zipfuse: &mut Zipfuse) -> Result<()> {
487 // For now, only the number of apks is important, as the mount point and dm-verity name is fixed
488 for i in 0..config.extra_apks.len() {
489 let mount_dir = format!("/mnt/extra-apk/{i}");
490 create_dir(Path::new(&mount_dir)).context("Failed to create mount dir for extra apks")?;
491
492 let mount_for_exec =
493 if cfg!(multi_tenant) { MountForExec::Allowed } else { MountForExec::Disallowed };
494 // These run asynchronously in parallel - we wait later for them to complete.
495 zipfuse.mount(
496 mount_for_exec,
497 "fscontext=u:object_r:zipfusefs:s0,context=u:object_r:extra_apk_file:s0",
498 Path::new(&format!("/dev/block/mapper/extra-apk-{i}")),
499 Path::new(&mount_dir),
500 format!("microdroid_manager.extra_apk.mounted.{i}"),
501 )?;
502 }
503
504 Ok(())
505}
506
507fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
508 // The host is running a VirtualMachineService for this VM on a port equal
509 // to the CID of this VM.
510 let port = vsock::get_local_cid().context("Could not determine local CID")?;
511 RpcSession::new()
512 .setup_vsock_client(VMADDR_CID_HOST, port)
513 .context("Could not connect to IVirtualMachineService")
514}
515
Alan Stokes03754962023-11-06 15:36:09 +0000516fn is_strict_boot() -> bool {
517 Path::new(AVF_STRICT_BOOT).exists()
518}
519
Shikha Panwar5b7b4942024-12-18 15:32:49 +0000520fn is_new_instance_legacy() -> bool {
Alan Stokes03754962023-11-06 15:36:09 +0000521 Path::new(AVF_NEW_INSTANCE).exists()
522}
523
524fn is_verified_boot() -> bool {
525 !Path::new(DEBUG_MICRODROID_NO_VERIFIED_BOOT).exists()
526}
527
528fn is_debuggable() -> Result<bool> {
529 Ok(system_properties::read_bool(DEBUGGABLE_PROP, true)?)
530}
531
532fn should_export_tombstones(config: &VmPayloadConfig) -> bool {
533 match config.export_tombstones {
534 Some(b) => b,
535 None => is_debuggable().unwrap_or(false),
536 }
537}
538
539/// Get debug policy value in bool. It's true iff the value is explicitly set to <1>.
540fn get_debug_policy_bool(path: &'static str) -> Result<Option<bool>> {
541 let mut file = match File::open(path) {
542 Ok(dp) => dp,
543 Err(e) => {
544 info!(
545 "Assumes that debug policy is disabled because failed to read debug policy ({e:?})"
546 );
547 return Ok(Some(false));
548 }
549 };
550 let mut log: [u8; 4] = Default::default();
551 file.read_exact(&mut log).context("Malformed data in {path}")?;
552 // DT spec uses big endian although Android is always little endian.
553 Ok(Some(u32::from_be_bytes(log) == 1))
554}
555
Alan Stokes60f82202022-10-07 16:40:07 +0100556enum MountForExec {
557 Allowed,
558 Disallowed,
559}
560
Alan Stokes960c9032022-12-07 16:53:45 +0000561#[derive(Default)]
562struct Zipfuse {
563 ready_properties: Vec<String>,
564}
565
566impl Zipfuse {
567 fn mount(
568 &mut self,
569 noexec: MountForExec,
570 option: &str,
571 zip_path: &Path,
572 mount_dir: &Path,
573 ready_prop: String,
574 ) -> Result<Child> {
575 let mut cmd = Command::new(ZIPFUSE_BIN);
576 if let MountForExec::Disallowed = noexec {
577 cmd.arg("--noexec");
578 }
Alan Stokes1294f942023-08-21 14:34:12 +0100579 // Let root own the files in APK, so we can access them, but set the group to
580 // allow all payloads to have access too.
581 let (uid, gid) = (microdroid_uids::ROOT_UID, microdroid_uids::MICRODROID_PAYLOAD_GID);
582
Alan Stokes960c9032022-12-07 16:53:45 +0000583 cmd.args(["-p", &ready_prop, "-o", option]);
Alan Stokes1294f942023-08-21 14:34:12 +0100584 cmd.args(["-u", &uid.to_string()]);
585 cmd.args(["-g", &gid.to_string()]);
Alan Stokes960c9032022-12-07 16:53:45 +0000586 cmd.arg(zip_path).arg(mount_dir);
587 self.ready_properties.push(ready_prop);
588 cmd.spawn().with_context(|| format!("Failed to run zipfuse for {mount_dir:?}"))
Andrew Scullcc339a12022-07-04 12:44:19 +0000589 }
Alan Stokes960c9032022-12-07 16:53:45 +0000590
591 fn wait_until_done(self) -> Result<()> {
592 // We check the last-started check first in the hope that by the time it is done
593 // all or most of the others will also be done, minimising the number of times we
594 // block on a property.
595 for property in self.ready_properties.into_iter().rev() {
596 wait_for_property_true(&property)
597 .with_context(|| format!("Failed waiting for {property}"))?;
598 }
599 Ok(())
Alan Stokes60f82202022-10-07 16:40:07 +0100600 }
Inseob Kim217038e2021-11-25 11:15:06 +0900601}
602
Alan Stokes60f82202022-10-07 16:40:07 +0100603fn wait_for_property_true(property_name: &str) -> Result<()> {
604 let mut prop = PropertyWatcher::new(property_name)?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900605 loop {
Andrew Walbrand9c766e2023-05-10 15:15:39 +0000606 prop.wait(None)?;
Alan Stokes60f82202022-10-07 16:40:07 +0100607 if system_properties::read_bool(property_name, false)? {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900608 break;
609 }
610 }
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900611 Ok(())
612}
613
Alan Stokes1f417c92022-09-29 15:13:28 +0100614fn load_config(payload_metadata: PayloadMetadata) -> Result<VmPayloadConfig> {
615 match payload_metadata {
Ludovic Barman93ee3082023-06-20 12:18:43 +0000616 PayloadMetadata::ConfigPath(path) => {
Alan Stokes1f417c92022-09-29 15:13:28 +0100617 let path = Path::new(&path);
618 info!("loading config from {:?}...", path);
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100619 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)
620 .with_context(|| format!("Failed to read {:?}", path))?;
Alan Stokes1f417c92022-09-29 15:13:28 +0100621 Ok(serde_json::from_reader(file)?)
622 }
Ludovic Barman93ee3082023-06-20 12:18:43 +0000623 PayloadMetadata::Config(payload_config) => {
Alan Stokes1f417c92022-09-29 15:13:28 +0100624 let task = Task {
625 type_: TaskType::MicrodroidLauncher,
Alan Stokes8f12f2b2023-01-09 09:19:20 +0000626 command: payload_config.payload_binary_name,
Alan Stokes1f417c92022-09-29 15:13:28 +0100627 };
Alan Stokesfda70842023-12-20 17:50:14 +0000628 // We don't care about the paths, only the number of extra APKs really matters.
629 let extra_apks = (0..payload_config.extra_apk_count)
630 .map(|i| ApkConfig { path: format!("extra-apk-{i}") })
631 .collect();
Alan Stokes1f417c92022-09-29 15:13:28 +0100632 Ok(VmPayloadConfig {
633 os: OsConfig { name: "microdroid".to_owned() },
634 task: Some(task),
635 apexes: vec![],
Alan Stokesfda70842023-12-20 17:50:14 +0000636 extra_apks,
Alan Stokes1f417c92022-09-29 15:13:28 +0100637 prefer_staged: false,
Inseob Kimab1037d2023-02-08 17:03:31 +0900638 export_tombstones: None,
Alan Stokes1f417c92022-09-29 15:13:28 +0100639 enable_authfs: false,
Vincent Donnefort538a2c62024-03-20 16:01:10 +0000640 hugepages: false,
Alan Stokes1f417c92022-09-29 15:13:28 +0100641 })
642 }
Ludovic Barman93ee3082023-06-20 12:18:43 +0000643 _ => bail!("Failed to match config against a config type."),
Alan Stokes1f417c92022-09-29 15:13:28 +0100644 }
Jooyung Han634e2d72021-06-10 16:27:38 +0900645}
646
Jaewan Kim3124ef02023-03-23 19:25:20 +0900647/// Loads the crashkernel into memory using kexec if debuggable or debug policy says so.
648/// The VM should be loaded with `crashkernel=' parameter in the cmdline to allocate memory
649/// for crashkernel.
Jiyong Park202856e2022-08-22 16:04:26 +0900650fn load_crashkernel_if_supported() -> Result<()> {
651 let supported = std::fs::read_to_string("/proc/cmdline")?.contains(" crashkernel=");
652 info!("ramdump supported: {}", supported);
Jaewan Kim3124ef02023-03-23 19:25:20 +0900653
654 if !supported {
655 return Ok(());
656 }
657
Alan Stokes1125e012023-10-13 12:31:10 +0100658 let debuggable = is_debuggable()?;
Jaewan Kim3124ef02023-03-23 19:25:20 +0900659 let ramdump = get_debug_policy_bool(AVF_DEBUG_POLICY_RAMDUMP)?.unwrap_or_default();
660 let requested = debuggable | ramdump;
661
662 if requested {
Jiyong Park202856e2022-08-22 16:04:26 +0900663 let status = Command::new("/system/bin/kexec_load").status()?;
664 if !status.success() {
Jiyong Park263262c2024-09-11 16:39:12 +0900665 return Err(anyhow!("Failed to load crashkernel: {status}"));
Jiyong Park202856e2022-08-22 16:04:26 +0900666 }
Jaewan Kim3124ef02023-03-23 19:25:20 +0900667 info!("ramdump is loaded: debuggable={debuggable}, ramdump={ramdump}");
Jiyong Park202856e2022-08-22 16:04:26 +0900668 }
669 Ok(())
670}
671
Inseob Kim090b70b2022-11-16 20:01:14 +0900672/// Executes the given task.
Jooyung Han5c6d4172021-12-06 14:17:52 +0900673fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<i32> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900674 info!("executing main task {:?}...", task);
David Brazdil451cc962022-10-14 14:08:12 +0100675 let mut command = match task.type_ {
Alan Stokes1294f942023-08-21 14:34:12 +0100676 TaskType::Executable => {
Alan Stokes679ddf32023-09-01 11:14:48 +0100677 // TODO(b/297501338): Figure out how to handle non-root for system payloads.
Alan Stokes1294f942023-08-21 14:34:12 +0100678 Command::new(&task.command)
679 }
David Brazdil451cc962022-10-14 14:08:12 +0100680 TaskType::MicrodroidLauncher => {
681 let mut command = Command::new("/system/bin/microdroid_launcher");
682 command.arg(find_library_path(&task.command)?);
Alan Stokes1294f942023-08-21 14:34:12 +0100683 command.uid(microdroid_uids::MICRODROID_PAYLOAD_UID);
684 command.gid(microdroid_uids::MICRODROID_PAYLOAD_GID);
David Brazdil451cc962022-10-14 14:08:12 +0100685 command
686 }
687 };
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000688
Andrew Walbranaac68302023-07-21 19:05:34 +0100689 // SAFETY: We are not accessing any resource of the parent process. This means we can't make any
690 // log calls inside the closure.
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000691 unsafe {
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000692 command.pre_exec(|| {
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000693 // It is OK to continue with payload execution even if the calls below fail, since
694 // whether process can use a capability is controlled by the SELinux. Dropping the
695 // capabilities here is just another defense-in-depth layer.
Andrew Walbranaac68302023-07-21 19:05:34 +0100696 let _ = cap::drop_inheritable_caps();
697 let _ = cap::drop_bounding_set();
Nikita Ioffe3452ee22022-12-15 00:31:56 +0000698 Ok(())
699 });
700 }
701
Jiyong Parke0abf772024-12-18 16:17:46 +0900702 // Never accept input from outside
703 command.stdin(Stdio::null());
704
705 // If the VM is debuggable, let stdout/stderr go outside via /dev/kmsg to ease the debugging
706 let (stdout, stderr) = if is_debuggable()? {
707 use std::os::fd::FromRawFd;
708 let kmsg_fd = env::var("ANDROID_FILE__dev_kmsg").unwrap().parse::<i32>().unwrap();
709 // SAFETY: no one closes kmsg_fd
710 unsafe { (Stdio::from_raw_fd(kmsg_fd), Stdio::from_raw_fd(kmsg_fd)) }
711 } else {
712 (Stdio::null(), Stdio::null())
713 };
714 command.stdout(stdout);
715 command.stderr(stderr);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900716
717 info!("notifying payload started");
Inseob Kimc7d28c72021-10-25 14:28:10 +0000718 service.notifyPayloadStarted()?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900719
Inseob Kim86ca0162021-10-20 02:21:02 +0000720 let exit_status = command.spawn()?.wait()?;
Frederick Mayleb5f7b6b2022-11-11 15:24:03 -0800721 match exit_status.code() {
722 Some(exit_code) => Ok(exit_code),
723 None => Err(match exit_status.signal() {
724 Some(signal) => anyhow!(
725 "Payload exited due to signal: {} ({})",
726 signal,
727 Signal::try_from(signal).map_or("unknown", |s| s.as_str())
728 ),
729 None => anyhow!("Payload has neither exit code nor signal"),
730 }),
731 }
Jooyung Han347d9f22021-05-28 00:05:14 +0900732}
Jooyung Han634e2d72021-06-10 16:27:38 +0900733
Jooyung Han634e2d72021-06-10 16:27:38 +0900734fn find_library_path(name: &str) -> Result<String> {
735 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
736 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
737 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
Alice Wang6bbb6da2022-10-26 12:44:06 +0000738 let path = format!("{}/lib/{}/{}", VM_APK_CONTENTS_PATH, abi, name);
Jooyung Han634e2d72021-06-10 16:27:38 +0900739
Alan Stokes3ba10fd2022-10-06 15:46:51 +0100740 let metadata = fs::metadata(&path).with_context(|| format!("Unable to access {}", path))?;
Jooyung Han634e2d72021-06-10 16:27:38 +0900741 if !metadata.is_file() {
742 bail!("{} is not a file", &path);
743 }
744
745 Ok(path)
746}
Jiyong Park21ce2c52021-08-28 02:32:17 +0900747
Shikha Panwar95084df2023-07-22 11:47:45 +0000748fn prepare_encryptedstore(vm_secret: &VmSecret) -> Result<Child> {
Alice Wang7e6c9352023-02-15 15:44:13 +0000749 let mut key = ZVec::new(ENCRYPTEDSTORE_KEYSIZE)?;
Shikha Panwar3d3a70a2023-08-21 20:02:08 +0000750 vm_secret.derive_encryptedstore_key(&mut key)?;
Shikha Panwar566c9672022-11-15 14:39:58 +0000751 let mut cmd = Command::new(ENCRYPTEDSTORE_BIN);
752 cmd.arg("--blkdevice")
753 .arg(ENCRYPTEDSTORE_BACKING_DEVICE)
754 .arg("--key")
755 .arg(hex::encode(&*key))
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000756 .args(["--mountpoint", ENCRYPTEDSTORE_MOUNTPOINT])
Shikha Panwar566c9672022-11-15 14:39:58 +0000757 .spawn()
758 .context("encryptedstore failed")
759}