Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2021 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 17 | use anyhow::{anyhow, bail, Context, Result}; |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 18 | use log::error; |
| 19 | use minijail::{self, Minijail}; |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 20 | use std::fs::File; |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 21 | use std::os::unix::io::{AsRawFd, RawFd}; |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 22 | use std::path::Path; |
| 23 | |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 24 | use crate::fsverity; |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 25 | use authfs_aidl_interface::aidl::com::android::virt::fs::{ |
| 26 | AuthFsConfig::AuthFsConfig, IAuthFs::IAuthFs, IAuthFsService::IAuthFsService, |
| 27 | InputFdAnnotation::InputFdAnnotation, OutputFdAnnotation::OutputFdAnnotation, |
| 28 | }; |
| 29 | use authfs_aidl_interface::binder::{ParcelFileDescriptor, Strong}; |
| 30 | use compos_aidl_interface::aidl::com::android::compos::Metadata::Metadata; |
| 31 | |
| 32 | /// The number that represents the file descriptor number expecting by the task. The number may be |
| 33 | /// meaningless in the current process. |
| 34 | pub type PseudoRawFd = i32; |
| 35 | |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 36 | pub enum CompilerOutput { |
| 37 | /// Fs-verity digests of output files, if the compiler finishes successfully. |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 38 | Digests { |
| 39 | oat: fsverity::Sha256Digest, |
| 40 | vdex: fsverity::Sha256Digest, |
| 41 | image: fsverity::Sha256Digest, |
| 42 | }, |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 43 | /// Exit code returned by the compiler, if not 0. |
| 44 | ExitCode(i8), |
| 45 | } |
| 46 | |
| 47 | struct CompilerOutputParcelFds { |
| 48 | oat: ParcelFileDescriptor, |
| 49 | vdex: ParcelFileDescriptor, |
| 50 | image: ParcelFileDescriptor, |
| 51 | } |
| 52 | |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 53 | /// Runs the compiler with given flags with file descriptors described in `metadata` retrieved via |
| 54 | /// `authfs_service`. Returns exit code of the compiler process. |
| 55 | pub fn compile( |
| 56 | compiler_path: &Path, |
| 57 | compiler_args: &[String], |
| 58 | authfs_service: Strong<dyn IAuthFsService>, |
| 59 | metadata: &Metadata, |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 60 | ) -> Result<CompilerOutput> { |
| 61 | // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable |
| 62 | // is out of scope. |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 63 | let authfs_config = build_authfs_config(metadata); |
| 64 | let authfs = authfs_service.mount(&authfs_config)?; |
| 65 | |
| 66 | // The task expects to receive FD numbers that match its flags (e.g. --zip-fd=42) prepared |
| 67 | // on the host side. Since the local FD opened from authfs (e.g. /authfs/42) may not match |
| 68 | // the task's expectation, prepare a FD mapping and let minijail prepare the correct FD |
| 69 | // setup. |
| 70 | let fd_mapping = |
| 71 | open_authfs_files_for_fd_mapping(&authfs, &authfs_config).context("Open on authfs")?; |
| 72 | |
| 73 | let jail = |
| 74 | spawn_jailed_task(compiler_path, compiler_args, fd_mapping).context("Spawn dex2oat")?; |
| 75 | let jail_result = jail.wait(); |
| 76 | |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 77 | let parcel_fds = parse_compiler_args(&authfs, compiler_args)?; |
| 78 | let oat_file: &File = parcel_fds.oat.as_ref(); |
| 79 | let vdex_file: &File = parcel_fds.vdex.as_ref(); |
| 80 | let image_file: &File = parcel_fds.image.as_ref(); |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 81 | |
| 82 | match jail_result { |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 83 | Ok(()) => Ok(CompilerOutput::Digests { |
Victor Hsieh | 9ed2718 | 2021-08-25 15:52:42 -0700 | [diff] [blame] | 84 | oat: fsverity::measure(oat_file.as_raw_fd())?, |
| 85 | vdex: fsverity::measure(vdex_file.as_raw_fd())?, |
| 86 | image: fsverity::measure(image_file.as_raw_fd())?, |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 87 | }), |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 88 | Err(minijail::Error::ReturnCode(exit_code)) => { |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 89 | error!("dex2oat failed with exit code {}", exit_code); |
| 90 | Ok(CompilerOutput::ExitCode(exit_code as i8)) |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 91 | } |
| 92 | Err(e) => { |
| 93 | bail!("Unexpected minijail error: {}", e) |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
Victor Hsieh | 6e34038 | 2021-08-13 12:18:02 -0700 | [diff] [blame] | 98 | fn parse_compiler_args( |
| 99 | authfs: &Strong<dyn IAuthFs>, |
| 100 | args: &[String], |
| 101 | ) -> Result<CompilerOutputParcelFds> { |
| 102 | const OAT_FD_PREFIX: &str = "--oat-fd="; |
| 103 | const VDEX_FD_PREFIX: &str = "--output-vdex-fd="; |
| 104 | const IMAGE_FD_PREFIX: &str = "--image-fd="; |
| 105 | const APP_IMAGE_FD_PREFIX: &str = "--app-image-fd="; |
| 106 | |
| 107 | let mut oat = None; |
| 108 | let mut vdex = None; |
| 109 | let mut image = None; |
| 110 | |
| 111 | for arg in args { |
| 112 | if let Some(value) = arg.strip_prefix(OAT_FD_PREFIX) { |
| 113 | let fd = value.parse::<RawFd>().context("Invalid --oat-fd flag")?; |
| 114 | debug_assert!(oat.is_none()); |
| 115 | oat = Some(authfs.openFile(fd, false)?); |
| 116 | } else if let Some(value) = arg.strip_prefix(VDEX_FD_PREFIX) { |
| 117 | let fd = value.parse::<RawFd>().context("Invalid --output-vdex-fd flag")?; |
| 118 | debug_assert!(vdex.is_none()); |
| 119 | vdex = Some(authfs.openFile(fd, false)?); |
| 120 | } else if let Some(value) = arg.strip_prefix(IMAGE_FD_PREFIX) { |
| 121 | let fd = value.parse::<RawFd>().context("Invalid --image-fd flag")?; |
| 122 | debug_assert!(image.is_none()); |
| 123 | image = Some(authfs.openFile(fd, false)?); |
| 124 | } else if let Some(value) = arg.strip_prefix(APP_IMAGE_FD_PREFIX) { |
| 125 | let fd = value.parse::<RawFd>().context("Invalid --app-image-fd flag")?; |
| 126 | debug_assert!(image.is_none()); |
| 127 | image = Some(authfs.openFile(fd, false)?); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | Ok(CompilerOutputParcelFds { |
| 132 | oat: oat.ok_or_else(|| anyhow!("Missing --oat-fd"))?, |
| 133 | vdex: vdex.ok_or_else(|| anyhow!("Missing --vdex-fd"))?, |
| 134 | image: image.ok_or_else(|| anyhow!("Missing --image-fd or --app-image-fd"))?, |
| 135 | }) |
| 136 | } |
| 137 | |
Victor Hsieh | 51789de | 2021-08-06 16:50:49 -0700 | [diff] [blame] | 138 | fn build_authfs_config(metadata: &Metadata) -> AuthFsConfig { |
| 139 | AuthFsConfig { |
| 140 | port: 3264, // TODO: support dynamic port |
| 141 | inputFdAnnotations: metadata |
| 142 | .input_fd_annotations |
| 143 | .iter() |
| 144 | .map(|x| InputFdAnnotation { fd: x.fd, fileSize: x.file_size }) |
| 145 | .collect(), |
| 146 | outputFdAnnotations: metadata |
| 147 | .output_fd_annotations |
| 148 | .iter() |
| 149 | .map(|x| OutputFdAnnotation { fd: x.fd }) |
| 150 | .collect(), |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | fn open_authfs_files_for_fd_mapping( |
| 155 | authfs: &Strong<dyn IAuthFs>, |
| 156 | config: &AuthFsConfig, |
| 157 | ) -> Result<Vec<(ParcelFileDescriptor, PseudoRawFd)>> { |
| 158 | let mut fd_mapping = Vec::new(); |
| 159 | |
| 160 | let results: Result<Vec<_>> = config |
| 161 | .inputFdAnnotations |
| 162 | .iter() |
| 163 | .map(|annotation| Ok((authfs.openFile(annotation.fd, false)?, annotation.fd))) |
| 164 | .collect(); |
| 165 | fd_mapping.append(&mut results?); |
| 166 | |
| 167 | let results: Result<Vec<_>> = config |
| 168 | .outputFdAnnotations |
| 169 | .iter() |
| 170 | .map(|annotation| Ok((authfs.openFile(annotation.fd, true)?, annotation.fd))) |
| 171 | .collect(); |
| 172 | fd_mapping.append(&mut results?); |
| 173 | |
| 174 | Ok(fd_mapping) |
| 175 | } |
| 176 | |
| 177 | fn spawn_jailed_task( |
| 178 | executable: &Path, |
| 179 | args: &[String], |
| 180 | fd_mapping: Vec<(ParcelFileDescriptor, PseudoRawFd)>, |
| 181 | ) -> Result<Minijail> { |
| 182 | // TODO(b/185175567): Run in a more restricted sandbox. |
| 183 | let jail = Minijail::new()?; |
| 184 | let preserve_fds: Vec<_> = fd_mapping.iter().map(|(f, id)| (f.as_raw_fd(), *id)).collect(); |
| 185 | let _pid = jail.run_remap(executable, preserve_fds.as_slice(), args)?; |
| 186 | Ok(jail) |
| 187 | } |