blob: 4f192dcb3148df0456bd62d29eae9d2af5fed3b2 [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 Han74573482021-06-08 17:10:21 +090019mod metadata;
Jooyung Han347d9f22021-05-28 00:05:14 +090020
Jiyong Parkf7dea252021-09-08 01:42:54 +090021use crate::instance::{ApkData, InstanceDisk, MicrodroidData, RootHash};
Jooyung Han19c1d6c2021-08-06 14:08:16 +090022use anyhow::{anyhow, bail, Context, Result};
23use apkverify::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 Han634e2d72021-06-10 16:27:38 +090028use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
Inseob Kim7f61fe72021-08-20 20:50:47 +090029use nix::ioctl_read_bad;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090030use rustutils::system_properties;
Joel Galenson482704c2021-07-29 15:53:53 -070031use rustutils::system_properties::PropertyWatcher;
Inseob Kim7f61fe72021-08-20 20:50:47 +090032use std::fs::{self, File, OpenOptions};
33use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
Jooyung Hanf48ceb42021-06-01 18:00:04 +090034use std::path::Path;
Jiyong Park8611a6c2021-07-09 18:17:44 +090035use std::process::{Command, Stdio};
36use std::str;
Jiyong Parkbb4a9872021-09-06 15:59:21 +090037use std::time::{Duration, SystemTime};
Jiyong Park8611a6c2021-07-09 18:17:44 +090038use vsock::VsockStream;
Jooyung Han634e2d72021-06-10 16:27:38 +090039
Inseob Kimd0587562021-09-01 21:27:32 +090040use android_system_virtualmachineservice::aidl::android::system::virtualmachineservice::IVirtualMachineService::{
41 VM_BINDER_SERVICE_PORT, VM_STREAM_SERVICE_PORT, IVirtualMachineService,
42};
Inseob Kim1b95f2e2021-08-19 13:17:40 +090043
Jooyung Han634e2d72021-06-10 16:27:38 +090044const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
Jooyung Han19c1d6c2021-08-06 14:08:16 +090045const DM_MOUNTED_APK_PATH: &str = "/dev/block/mapper/microdroid-apk";
Jooyung Han347d9f22021-05-28 00:05:14 +090046
Inseob Kim1b95f2e2021-08-19 13:17:40 +090047/// The CID representing the host VM
48const VMADDR_CID_HOST: u32 = 2;
49
Jiyong Parkbb4a9872021-09-06 15:59:21 +090050const APEX_CONFIG_DONE_PROP: &str = "apex_config.done";
51
Inseob Kim1b95f2e2021-08-19 13:17:40 +090052fn get_vms_rpc_binder() -> Result<Strong<dyn IVirtualMachineService>> {
53 // SAFETY: AIBinder returned by RpcClient has correct reference count, and the ownership can be
54 // safely taken by new_spibinder.
55 let ibinder = unsafe {
56 new_spibinder(binder_rpc_unstable_bindgen::RpcClient(
57 VMADDR_CID_HOST,
Inseob Kimd0587562021-09-01 21:27:32 +090058 VM_BINDER_SERVICE_PORT as u32,
Inseob Kim1b95f2e2021-08-19 13:17:40 +090059 ) as *mut AIBinder)
60 };
61 if let Some(ibinder) = ibinder {
62 <dyn IVirtualMachineService>::try_from(ibinder).context("Cannot connect to RPC service")
63 } else {
64 bail!("Invalid raw AIBinder")
65 }
66}
67
Inseob Kim7f61fe72021-08-20 20:50:47 +090068const IOCTL_VM_SOCKETS_GET_LOCAL_CID: usize = 0x7b9;
69ioctl_read_bad!(
70 /// Gets local cid from /dev/vsock
71 vm_sockets_get_local_cid,
72 IOCTL_VM_SOCKETS_GET_LOCAL_CID,
73 u32
74);
75
76// TODO: remove this after VS can check the peer addresses of binder clients
77fn get_local_cid() -> Result<u32> {
78 let f = OpenOptions::new()
79 .read(true)
80 .write(false)
81 .open("/dev/vsock")
82 .context("failed to open /dev/vsock")?;
83 let mut ret = 0;
84 // SAFETY: the kernel only modifies the given u32 integer.
85 unsafe { vm_sockets_get_local_cid(f.as_raw_fd(), &mut ret) }?;
86 Ok(ret)
87}
88
Jooyung Han634e2d72021-06-10 16:27:38 +090089fn main() -> Result<()> {
Jiyong Park79b88012021-06-25 13:06:25 +090090 kernlog::init()?;
Jooyung Han347d9f22021-05-28 00:05:14 +090091 info!("started.");
92
Jooyung Han74573482021-06-08 17:10:21 +090093 let metadata = metadata::load()?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +090094
Jiyong Parkbb4a9872021-09-06 15:59:21 +090095 let mut instance = InstanceDisk::new()?;
Jiyong Parkf7dea252021-09-08 01:42:54 +090096 let data = instance.read_microdroid_data().context("Failed to read identity data")?;
97 let saved_root_hash: Option<&[u8]> =
98 if let Some(data) = data.as_ref() { Some(&data.apk_data.root_hash) } else { None };
Jiyong Parkbb4a9872021-09-06 15:59:21 +090099
100 // Verify the payload before using it.
Jiyong Parkf7dea252021-09-08 01:42:54 +0900101 let verified_root_hash =
102 verify_payload(saved_root_hash).context("Payload verification failed")?;
103 if let Some(saved_root_hash) = saved_root_hash {
104 if saved_root_hash == verified_root_hash.as_ref() {
105 info!("Saved root_hash is verified.");
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900106 } else {
107 bail!("Detected an update of the APK which isn't supported yet.");
108 }
109 } else {
Jiyong Parkf7dea252021-09-08 01:42:54 +0900110 info!("Saving APK root_hash: {}", to_hex_string(verified_root_hash.as_ref()));
111 let data = MicrodroidData { apk_data: ApkData { root_hash: verified_root_hash } };
112 instance.write_microdroid_data(&data).context("Failed to write identity data")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900113 }
114
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900115 wait_for_apex_config_done()?;
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() {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900119 // Before reading a file from the APK, start zipfuse
120 system_properties::write("ctl.start", "zipfuse")?;
121
Jooyung Han634e2d72021-06-10 16:27:38 +0900122 let config = load_config(Path::new(&metadata.payload_config_path))?;
123
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000124 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 -0700125 if let Err(err) = rustutils::system_properties::write("ro.vmsecret.keymint", fake_secret) {
Andrew Scull6f3e5fe2021-07-02 12:38:21 +0000126 warn!("failed to set ro.vmsecret.keymint: {}", err);
127 }
128
Jooyung Han634e2d72021-06-10 16:27:38 +0900129 // TODO(jooyung): wait until sys.boot_completed?
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
Jiyong Parkf7dea252021-09-08 01:42:54 +0900141// Verify payload before executing it. Full verification (which is slow) is done when the root_hash
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900142// values from the idsig file and the instance disk are different. This function returns the
Jiyong Parkf7dea252021-09-08 01:42:54 +0900143// verified root hash that can be saved to the instance disk.
144fn verify_payload(root_hash: Option<&RootHash>) -> Result<Box<RootHash>> {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900145 let start_time = SystemTime::now();
146
Jiyong Parkf7dea252021-09-08 01:42:54 +0900147 let root_hash_from_idsig = get_apk_root_hash_from_idsig()?;
148 let root_hash_trustful = root_hash == Some(&root_hash_from_idsig);
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900149
Jiyong Parkf7dea252021-09-08 01:42:54 +0900150 // 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 +0900151 // instead of the value read from the idsig file.
Jiyong Parkf7dea252021-09-08 01:42:54 +0900152 if root_hash_trustful {
153 let root_hash = to_hex_string(root_hash.unwrap());
154 system_properties::write("microdroid_manager.apk_root_hash", &root_hash)?;
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900155 }
156
157 // Start apkdmverity and wait for the dm-verify block
158 system_properties::write("ctl.start", "apkdmverity")?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900159 ioutil::wait_for_file(DM_MOUNTED_APK_PATH, WAIT_TIMEOUT)?;
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900160
Jiyong Parkf7dea252021-09-08 01:42:54 +0900161 // Do the full verification if the root_hash is un-trustful. This requires the full scanning of
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900162 // 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 +0900163 // 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 +0900164 // of the VM or APK was updated in the host.
165 // TODO(jooyung): consider multithreading to make this faster
Jiyong Parkf7dea252021-09-08 01:42:54 +0900166 if !root_hash_trustful {
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900167 verify(DM_MOUNTED_APK_PATH).context(format!("failed to verify {}", DM_MOUNTED_APK_PATH))?;
168 }
169
170 info!("payload verification successful. took {:#?}", start_time.elapsed().unwrap());
171
Jiyong Parkf7dea252021-09-08 01:42:54 +0900172 // At this point, we can ensure that the root_hash from the idsig file is trusted, either by
173 // fully verifying the APK or by comparing it with the saved root_hash.
174 Ok(root_hash_from_idsig)
Jiyong Parkbb4a9872021-09-06 15:59:21 +0900175}
176
177// Waits until linker config is generated
178fn wait_for_apex_config_done() -> Result<()> {
179 let mut prop = PropertyWatcher::new(APEX_CONFIG_DONE_PROP)?;
180 loop {
181 prop.wait()?;
182 let val = system_properties::read(APEX_CONFIG_DONE_PROP)?;
183 if val == "true" {
184 break;
185 }
186 }
Jooyung Han19c1d6c2021-08-06 14:08:16 +0900187 Ok(())
188}
189
Jiyong Parkf7dea252021-09-08 01:42:54 +0900190fn get_apk_root_hash_from_idsig() -> Result<Box<RootHash>> {
Jiyong Park21ce2c52021-08-28 02:32:17 +0900191 let mut idsig = File::open("/dev/block/by-name/microdroid-apk-idsig")?;
192 let idsig = V4Signature::from(&mut idsig)?;
193 Ok(idsig.hashing_info.raw_root_hash)
194}
195
Jooyung Han634e2d72021-06-10 16:27:38 +0900196fn load_config(path: &Path) -> Result<VmPayloadConfig> {
197 info!("loading config from {:?}...", path);
198 let file = ioutil::wait_for_file(path, WAIT_TIMEOUT)?;
199 Ok(serde_json::from_reader(file)?)
200}
201
Jiyong Park8611a6c2021-07-09 18:17:44 +0900202/// Executes the given task. Stdout of the task is piped into the vsock stream to the
203/// virtualizationservice in the host side.
Inseob Kim7f61fe72021-08-20 20:50:47 +0900204fn exec_task(task: &Task, service: &Strong<dyn IVirtualMachineService>) -> Result<()> {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900205 info!("executing main task {:?}...", task);
Inseob Kim7f61fe72021-08-20 20:50:47 +0900206 let mut child = build_command(task)?.spawn()?;
207
Inseob Kim2444af92021-08-31 01:22:50 +0900208 let local_cid = get_local_cid()?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900209 info!("notifying payload started");
Inseob Kim2444af92021-08-31 01:22:50 +0900210 service.notifyPayloadStarted(local_cid as i32)?;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900211
Inseob Kim2444af92021-08-31 01:22:50 +0900212 if let Some(code) = child.wait()?.code() {
213 info!("notifying payload finished");
214 service.notifyPayloadFinished(local_cid as i32, code)?;
215
216 if code == 0 {
Jiyong Park8611a6c2021-07-09 18:17:44 +0900217 info!("task successfully finished");
Inseob Kim2444af92021-08-31 01:22:50 +0900218 } else {
219 error!("task exited with exit code: {}", code);
Jiyong Park8611a6c2021-07-09 18:17:44 +0900220 }
Inseob Kim2444af92021-08-31 01:22:50 +0900221 } else {
222 error!("task terminated by signal");
Jiyong Park038b73e2021-06-16 01:57:02 +0900223 }
Inseob Kim2444af92021-08-31 01:22:50 +0900224 Ok(())
Jooyung Han347d9f22021-05-28 00:05:14 +0900225}
Jooyung Han634e2d72021-06-10 16:27:38 +0900226
227fn build_command(task: &Task) -> Result<Command> {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900228 const VMADDR_CID_HOST: u32 = 2;
Inseob Kim7f61fe72021-08-20 20:50:47 +0900229
230 let mut command = match task.type_ {
Jooyung Han634e2d72021-06-10 16:27:38 +0900231 TaskType::Executable => {
232 let mut command = Command::new(&task.command);
233 command.args(&task.args);
234 command
235 }
236 TaskType::MicrodroidLauncher => {
237 let mut command = Command::new("/system/bin/microdroid_launcher");
238 command.arg(find_library_path(&task.command)?).args(&task.args);
239 command
240 }
Inseob Kim7f61fe72021-08-20 20:50:47 +0900241 };
242
Inseob Kimd0587562021-09-01 21:27:32 +0900243 match VsockStream::connect_with_cid_port(VMADDR_CID_HOST, VM_STREAM_SERVICE_PORT as u32) {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900244 Ok(stream) => {
245 // SAFETY: the ownership of the underlying file descriptor is transferred from stream
246 // to the file object, and then into the Command object. When the command is finished,
247 // the file descriptor is closed.
248 let file = unsafe { File::from_raw_fd(stream.into_raw_fd()) };
249 command
250 .stdin(Stdio::from(file.try_clone()?))
251 .stdout(Stdio::from(file.try_clone()?))
252 .stderr(Stdio::from(file));
253 }
254 Err(e) => {
255 error!("failed to connect to virtualization service: {}", e);
256 // Don't fail hard here. Even if we failed to connect to the virtualizationservice,
257 // we keep executing the task. This can happen if the owner of the VM doesn't register
258 // callback to accept the stream. Use /dev/null as the stream so that the task can
259 // make progress without waiting for someone to consume the output.
260 command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
261 }
262 }
263
264 Ok(command)
Jooyung Han634e2d72021-06-10 16:27:38 +0900265}
266
267fn find_library_path(name: &str) -> Result<String> {
268 let mut watcher = PropertyWatcher::new("ro.product.cpu.abilist")?;
269 let value = watcher.read(|_name, value| Ok(value.trim().to_string()))?;
270 let abi = value.split(',').next().ok_or_else(|| anyhow!("no abilist"))?;
271 let path = format!("/mnt/apk/lib/{}/{}", abi, name);
272
273 let metadata = fs::metadata(&path)?;
274 if !metadata.is_file() {
275 bail!("{} is not a file", &path);
276 }
277
278 Ok(path)
279}
Jiyong Park21ce2c52021-08-28 02:32:17 +0900280
281fn to_hex_string(buf: &[u8]) -> String {
282 buf.iter().map(|b| format!("{:02X}", b)).collect()
283}