blob: 4953a4cf8632248ca197c088e830cb779e93eea4 [file] [log] [blame]
Jooyung Han347d9f22021-05-28 00:05:14 +09001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Microdroid Manager
16
Jiyong Park21ce2c52021-08-28 02:32:17 +090017mod instance;
Jooyung Hanf48ceb42021-06-01 18:00:04 +090018mod ioutil;
Jooyung Han7a343f92021-09-08 22:53:11 +090019mod payload;
Jooyung Han347d9f22021-05-28 00:05:14 +090020
Jiyong Parkf7dea252021-09-08 01:42:54 +090021use crate::instance::{ApkData, InstanceDisk, MicrodroidData, RootHash};
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090022use anyhow::{anyhow, bail, ensure, Context, Result};
Jiyong Parka41535b2021-09-10 19:31:48 +090023use apkverify::{get_public_key_der, verify};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090024use binder::unstable_api::{new_spibinder, AIBinder};
25use binder::{FromIBinder, Strong};
Jiyong Park21ce2c52021-08-28 02:32:17 +090026use idsig::V4Signature;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090027use log::{error, info, warn};
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090028use microdroid_metadata::{write_metadata, Metadata};
Jooyung Han634e2d72021-06-10 16:27:38 +090029use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
Inseob Kim7f61fe72021-08-20 20:50:47 +090030use nix::ioctl_read_bad;
Jooyung Han4a9b3bf2021-09-10 17:19:00 +090031use payload::{get_apex_data_from_payload, load_metadata, to_metadata};
Jiyong Parkbb4a9872021-09-06 15:59:21 +090032use rustutils::system_properties;
Joel Galenson482704c2021-07-29 15:53:53 -070033use rustutils::system_properties::PropertyWatcher;
Inseob Kim7f61fe72021-08-20 20:50:47 +090034use std::fs::{self, File, OpenOptions};
35use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Jooyung Hanf48ceb42021-06-01 18:00:04 +090036use std::path::Path;
Jiyong Park8611a6c2021-07-09 18:17:44 +090037use std::process::{Command, Stdio};
38use std::str;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090039use std::time::{Duration, SystemTime};
Jiyong Park8611a6c2021-07-09 18:17:44 +090040use vsock::VsockStream;
Jooyung Han634e2d72021-06-10 16:27:38 +090041
Inseob Kimd0587562021-09-01 21:27:32 +090042use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
43 VM_BINDER_SERVICE_PORT, VM_STREAM_SERVICE_PORT, IVirtualMachineService,
44};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090045
Jooyung Han634e2d72021-06-10 16:27:38 +090046const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jooyung Han19c1d6c2021-08-06 14:08:16 +090047const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
Jooyung Han347d9f22021-05-28 00:05:14 +090048
Inseob Kim1b95f2e2021-08-19 13:17:40 +090049/// The CID representing the host VM
50const VMADDR_CID_HOST: u32 = 2;
51
Jiyong Parkbb4a9872021-09-06 15:59:21 +090052const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
53
Inseob Kim1b95f2e2021-08-19 13:17:40 +090054fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
55 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
56 // safely taken by new_spibinder.
57 let ibinder = unsafe {
58 new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
59 VMADDR_CID_HOST,
Inseob Kimd0587562021-09-01 21:27:32 +090060 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090061 ) as *mut AIBinder)
62 };
63 if let Some(ibinder) = ibinder {
64 <dyn IVirtualMachineService>::try_from(ibinder).context("Cannot connect to RPC service")
65 } else {
66 bail!("Invalid raw AIBinder")
67 }
68}
69
Inseob Kim7f61fe72021-08-20 20:50:47 +090070const IOCTL_VM_SOCKETS_GET_LOCAL_CID: usize = 0x7b9;
71ioctl_read_bad!(
72 /// Gets local cid from /dev/vsock
73 vm_sockets_get_local_cid,
74 IOCTL_VM_SOCKETS_GET_LOCAL_CID,
75 u32
76);
77
78// TODO: remove this after VS can check the peer addresses of binder clients
79fn get_local_cid() -> Result<u32> {
80 let f = OpenOptions::new()
81 .read(true)
82 .write(false)
83 .open("/dev/vsock")
84 .context("failed to open /dev/vsock")?;
85 let mut ret = 0;
86 // SAFETY: the kernel only modifies the given u32 integer.
87 unsafe { vm_sockets_get_local_cid(f.as_raw_fd(), &mut ret) }?;
88 Ok(ret)
89}
90
Jooyung Han634e2d72021-06-10 16:27:38 +090091fn main() -> Result<()> {
Jiyong Park79b88012021-06-25 13:06:25 +090092 kernlog::init()?;
Jooyung Han347d9f22021-05-28 00:05:14 +090093 info!("started.");
94
Jooyung Han7a343f92021-09-08 22:53:11 +090095 let metadata = load_metadata()?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +090096
Jiyong Parkbb4a9872021-09-06 15:59:21 +090097 let mut instance = InstanceDisk::new()?;
Jooyung Han7a343f92021-09-08 22:53:11 +090098 let saved_data = instance.read_microdroid_data().context("Failed to read identity data")?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090099
100 // Verify the payload before using it.
Jooyung Han7a343f92021-09-08 22:53:11 +0900101 let verified_data =
102 verify_payload(&metadata, saved_data.as_ref()).context("Payload verification failed")?;
103 if let Some(saved_data) = saved_data {
104 if saved_data == verified_data {
105 info!("Saved data is verified.");
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900106 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +0900107 bail!("Detected an update of the payload which isn't supported yet.");
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900108 }
109 } else {
Jooyung Han7a343f92021-09-08 22:53:11 +0900110 info!("Saving verified data.");
111 instance.write_microdroid_data(&verified_data).context("Failed to write identity data")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900112 }
113
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900114 // Before reading a file from the APK, start zipfuse
115 system_properties::write("ctl.start", "zipfuse")?;
Jiyong Park21ce2c52021-08-28 02:32:17 +0900116
Inseob Kim7f61fe72021-08-20 20:50:47 +0900117 let service = get_vms_rpc_binder().expect("cannot connect to VirtualMachineService");
Jooyung Han74573482021-06-08 17:10:21 +0900118 if !metadata.payload_config_path.is_empty() {
Jooyung Han634e2d72021-06-10 16:27:38 +0900119 let config = load_config(Path::new(&metadata.payload_config_path))?;
120
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000121 let fake_secret = "This is a placeholder for a value that is derived from the images that are loaded in the VM.";
Joel Galenson482704c2021-07-29 15:53:53 -0700122 if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000123 warn!("failed to set ro.vmsecret.keymint: {}", err);
124 }
125
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900126 // Wait until apex config is done. (e.g. linker configuration for apexes)
Jooyung Han634e2d72021-06-10 16:27:38 +0900127 // TODO(jooyung): wait until sys.boot_completed?
Jooyung Hana6d11eb2021-09-10 11:48:05 +0900128 wait_for_apex_config_done()?;
129
Jooyung Han347d9f22021-05-28 00:05:14 +0900130 if let Some(main_task) = &config.task {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900131 exec_task(main_task, &service).map_err(|e| {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900132 error!("failed to execute task: {}", e);
133 e
134 })?;
Jooyung Han347d9f22021-05-28 00:05:14 +0900135 }
136 }
137
138 Ok(())
139}
140
Jooyung Han7a343f92021-09-08 22:53:11 +0900141// Verify payload before executing it. For APK payload, Full verification (which is slow) is done
142// when the root_hash values from the idsig file and the instance disk are different. This function
143// returns the verified root hash (for APK payload) and pubkeys (for APEX payloads) that can be
144// saved to the instance disk.
145fn verify_payload(
146 metadata: &Metadata,
147 saved_data: Option<&MicrodroidData>,
148) -> Result<MicrodroidData> {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900149 let start_time = SystemTime::now();
150
Jooyung Han7a343f92021-09-08 22:53:11 +0900151 let root_hash = saved_data.map(|d| &d.apk_data.root_hash);
Jiyong Parkf7dea252021-09-08 01:42:54 +0900152 let root_hash_from_idsig = get_apk_root_hash_from_idsig()?;
153 let root_hash_trustful = root_hash == Some(&root_hash_from_idsig);
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900154
Jiyong Parkf7dea252021-09-08 01:42:54 +0900155 // If root_hash can be trusted, pass it to apkdmverity so that it uses the passed root_hash
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900156 // instead of the value read from the idsig file.
Jiyong Parkf7dea252021-09-08 01:42:54 +0900157 if root_hash_trustful {
158 let root_hash = to_hex_string(root_hash.unwrap());
159 system_properties::write("microdroid_manager.apk_root_hash", &root_hash)?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900160 }
161
162 // Start apkdmverity and wait for the dm-verify block
163 system_properties::write("ctl.start", "apkdmverity")?;
Jooyung Han7a343f92021-09-08 22:53:11 +0900164
Jooyung Hanc8deb472021-09-13 13:48:25 +0900165 // While waiting for apkdmverity to mount APK, gathers public keys and root digests from
166 // APEX payload.
Jooyung Han7a343f92021-09-08 22:53:11 +0900167 let apex_data_from_payload = get_apex_data_from_payload(metadata)?;
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900168 if let Some(saved_data) = saved_data.map(|d| &d.apex_data) {
Jooyung Hanc8deb472021-09-13 13:48:25 +0900169 // We don't support APEX updates. (assuming that update will change root digest)
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900170 ensure!(saved_data == &apex_data_from_payload, "APEX payloads has changed.");
171 let apex_metadata = to_metadata(&apex_data_from_payload);
Jooyung Hanc8deb472021-09-13 13:48:25 +0900172 // Pass metadata(with public keys and root digests) to apexd so that it uses the passed
173 // metadata instead of the default one (/dev/block/by-name/payload-metadata)
Jooyung Han4a9b3bf2021-09-10 17:19:00 +0900174 OpenOptions::new()
175 .create_new(true)
176 .write(true)
177 .open("/apex/vm-payload-metadata")
178 .context("Failed to open /apex/vm-payload-metadata")
179 .and_then(|f| write_metadata(&apex_metadata, f))?;
180 }
181 // Start apexd to activate APEXes
182 system_properties::write("ctl.start", "apexd-vm")?;
Jooyung Han7a343f92021-09-08 22:53:11 +0900183
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900184 ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900185
Jiyong Parkf7dea252021-09-08 01:42:54 +0900186 // Do the full verification if the root_hash is un-trustful. This requires the full scanning of
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900187 // the APK file and therefore can be very slow if the APK is large. Note that this step is
Jiyong Parkf7dea252021-09-08 01:42:54 +0900188 // taken only when the root_hash is un-trustful which can be either when this is the first boot
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900189 // of the VM or APK was updated in the host.
190 // TODO(jooyung): consider multithreading to make this faster
Jiyong Parka41535b2021-09-10 19:31:48 +0900191 let apk_pubkey = if !root_hash_trustful {
192 verify(DM_MOUNTED_APK_PATH).context(format!("failed to verify {}", DM_MOUNTED_APK_PATH))?
193 } else {
194 get_public_key_der(DM_MOUNTED_APK_PATH)?
195 };
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900196
197 info!("payload verification successful. took {:#?}", start_time.elapsed().unwrap());
198
Jiyong Parkf7dea252021-09-08 01:42:54 +0900199 // At this point, we can ensure that the root_hash from the idsig file is trusted, either by
200 // fully verifying the APK or by comparing it with the saved root_hash.
Jooyung Han7a343f92021-09-08 22:53:11 +0900201 Ok(MicrodroidData {
Jiyong Parka41535b2021-09-10 19:31:48 +0900202 apk_data: ApkData { root_hash: root_hash_from_idsig, pubkey: apk_pubkey },
Jooyung Han7a343f92021-09-08 22:53:11 +0900203 apex_data: apex_data_from_payload,
204 })
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900205}
206
207// Waits until linker config is generated
208fn wait_for_apex_config_done() -> Result<()> {
209 let mut prop = PropertyWatcher::new(APEX_CONFIG_DONE_PROP)?;
210 loop {
211 prop.wait()?;
212 let val = system_properties::read(APEX_CONFIG_DONE_PROP)?;
213 if val == "true" {
214 break;
215 }
216 }
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900217 Ok(())
218}
219
Jiyong Parkf7dea252021-09-08 01:42:54 +0900220fn get_apk_root_hash_from_idsig() -> Result<Box<RootHash>> {
Jiyong Park21ce2c52021-08-28 02:32:17 +0900221 let mut idsig = File::open("/dev/block/by-name/microdroid-apk-idsig")?;
222 let idsig = V4Signature::from(&mut idsig)?;
223 Ok(idsig.hashing_info.raw_root_hash)
224}
225
Jooyung Han634e2d72021-06-10 16:27:38 +0900226fn load_config(path: &Path) -> Result<VmPayloadConfig> {
227 info!("loading config from {:?}...", path);
228 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
229 Ok(serde_json::from_reader(file)?)
230}
231
Jiyong Park8611a6c2021-07-09 18:17:44 +0900232/// Executes the given task. Stdout of the task is piped into the vsock stream to the
233/// virtualizationservice in the host side.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900234fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900235 info!("executing main task {:?}...", task);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900236 let mut child = build_command(task)?.spawn()?;
237
Inseob Kim2444af92021-08-31 01:22:50 +0900238 let local_cid = get_local_cid()?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900239 info!("notifying payload started");
Inseob Kim2444af92021-08-31 01:22:50 +0900240 service.notifyPayloadStarted(local_cid as i32)?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900241
Inseob Kim2444af92021-08-31 01:22:50 +0900242 if let Some(code) = child.wait()?.code() {
243 info!("notifying payload finished");
244 service.notifyPayloadFinished(local_cid as i32, code)?;
245
246 if code == 0 {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900247 info!("task successfully finished");
Inseob Kim2444af92021-08-31 01:22:50 +0900248 } else {
249 error!("task exited with exit code: {}", code);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900250 }
Inseob Kim2444af92021-08-31 01:22:50 +0900251 } else {
252 error!("task terminated by signal");
Jiyong Park038b73e2021-06-16 01:57:02 +0900253 }
Inseob Kim2444af92021-08-31 01:22:50 +0900254 Ok(())
Jooyung Han347d9f22021-05-28 00:05:14 +0900255}
Jooyung Han634e2d72021-06-10 16:27:38 +0900256
257fn build_command(task: &Task) -> Result<Command> {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900258 const VMADDR_CID_HOST: u32 = 2;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900259
260 let mut command = match task.type_ {
Jooyung Han634e2d72021-06-10 16:27:38 +0900261 TaskType::Executable => {
262 let mut command = Command::new(&task.command);
263 command.args(&task.args);
264 command
265 }
266 TaskType::MicrodroidLauncher => {
267 let mut command = Command::new("/system/bin/microdroid_launcher");
268 command.arg(find_library_path(&task.command)?).args(&task.args);
269 command
270 }
Inseob Kim7f61fe72021-08-20 20:50:47 +0900271 };
272
Inseob Kimd0587562021-09-01 21:27:32 +0900273 match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32) {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900274 Ok(stream) => {
275 // SAFETY: the ownership of the underlying file descriptor is transferred from stream
276 // to the file object, and then into the Command object. When the command is finished,
277 // the file descriptor is closed.
278 let file = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
279 command
280 .stdin(Stdio::from(file.try_clone()?))
281 .stdout(Stdio::from(file.try_clone()?))
282 .stderr(Stdio::from(file));
283 }
284 Err(e) => {
285 error!("failed to connect to virtualization service: {}", e);
286 // Don't fail hard here. Even if we failed to connect to the virtualizationservice,
287 // we keep executing the task. This can happen if the owner of the VM doesn't register
288 // callback to accept the stream. Use /dev/null as the stream so that the task can
289 // make progress without waiting for someone to consume the output.
290 command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
291 }
292 }
293
294 Ok(command)
Jooyung Han634e2d72021-06-10 16:27:38 +0900295}
296
297fn find_library_path(name: &str) -> Result<String> {
298 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
299 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
300 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
301 let path = format!("/mnt/apk/lib/{}/{}", abi, name);
302
303 let metadata = fs::metadata(&path)?;
304 if !metadata.is_file() {
305 bail!("{} is not a file", &path);
306 }
307
308 Ok(path)
309}
Jiyong Park21ce2c52021-08-28 02:32:17 +0900310
311fn to_hex_string(buf: &[u8]) -> String {
312 buf.iter().map(|b| format!("{:02X}", b)).collect()
313}