blob: e8f55f86d8cd30f1fa94c4c5fa051934b50c44ab [file] [log] [blame]
Victor Hsieh51789de2021-08-06 16:50:49 -07001/*
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
Alan Stokesfadcef22022-01-24 17:00:59 +000017use anyhow::{anyhow, bail, Context, Result};
Victor Hsieh616f8222022-01-14 13:06:32 -080018use log::{debug, info, warn};
Victor Hsieh51789de2021-08-06 16:50:49 -070019use minijail::{self, Minijail};
Alan Stokes92472512022-01-04 11:48:38 +000020use regex::Regex;
Alan Stokesfadcef22022-01-24 17:00:59 +000021use std::collections::HashMap;
Victor Hsiehf9968692021-11-18 11:34:39 -080022use std::env;
Alan Stokes92472512022-01-04 11:48:38 +000023use std::ffi::OsString;
Victor Hsieh616f8222022-01-14 13:06:32 -080024use std::fs::read_dir;
Alan Stokes35bac3c2021-12-16 14:37:24 +000025use std::path::{self, Path, PathBuf};
Alan Stokes92472512022-01-04 11:48:38 +000026use std::process::Command;
Victor Hsieh51789de2021-08-06 16:50:49 -070027
Alan Stokes46a1dff2021-12-14 10:56:05 +000028use crate::artifact_signer::ArtifactSigner;
Alan Stokes223a7462022-01-20 14:12:24 +000029use crate::signing_key::Signer;
Victor Hsieh51789de2021-08-06 16:50:49 -070030use authfs_aidl_interface::aidl::com::android::virt::fs::{
Victor Hsieh015bcb52021-11-17 17:28:01 -080031 AuthFsConfig::{
Victor Hsiehf9968692021-11-18 11:34:39 -080032 AuthFsConfig, InputDirFdAnnotation::InputDirFdAnnotation,
Victor Hsieh616f8222022-01-14 13:06:32 -080033 OutputDirFdAnnotation::OutputDirFdAnnotation,
Victor Hsieh015bcb52021-11-17 17:28:01 -080034 },
Victor Hsieh015bcb52021-11-17 17:28:01 -080035 IAuthFsService::IAuthFsService,
Victor Hsieh51789de2021-08-06 16:50:49 -070036};
Alan Stokesfadcef22022-01-24 17:00:59 +000037use authfs_aidl_interface::binder::Strong;
Alan Stokes46a1dff2021-12-14 10:56:05 +000038use compos_common::odrefresh::ExitCode;
Victor Hsieh51789de2021-08-06 16:50:49 -070039
Victor Hsiehf9968692021-11-18 11:34:39 -080040const FD_SERVER_PORT: i32 = 3264; // TODO: support dynamic port
41
Alan Stokes46a1dff2021-12-14 10:56:05 +000042pub struct OdrefreshContext<'a> {
Victor Hsiehf9968692021-11-18 11:34:39 -080043 system_dir_fd: i32,
44 output_dir_fd: i32,
Alan Stokes9646db92021-12-14 13:22:33 +000045 staging_dir_fd: i32,
Alan Stokes46a1dff2021-12-14 10:56:05 +000046 target_dir_name: &'a str,
47 zygote_arch: &'a str,
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -080048 system_server_compiler_filter: &'a str,
Alan Stokes46a1dff2021-12-14 10:56:05 +000049}
50
51impl<'a> OdrefreshContext<'a> {
52 pub fn new(
53 system_dir_fd: i32,
54 output_dir_fd: i32,
55 staging_dir_fd: i32,
56 target_dir_name: &'a str,
57 zygote_arch: &'a str,
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -080058 system_server_compiler_filter: &'a str,
Alan Stokes46a1dff2021-12-14 10:56:05 +000059 ) -> Result<Self> {
60 if system_dir_fd < 0 || output_dir_fd < 0 || staging_dir_fd < 0 {
61 bail!("The remote FDs are expected to be non-negative");
62 }
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -080063 if !matches!(zygote_arch, "zygote64" | "zygote64_32") {
Alan Stokes46a1dff2021-12-14 10:56:05 +000064 bail!("Invalid zygote arch");
65 }
Alan Stokes35bac3c2021-12-16 14:37:24 +000066 // Disallow any sort of path traversal
67 if target_dir_name.contains(path::MAIN_SEPARATOR) {
68 bail!("Invalid target directory {}", target_dir_name);
69 }
70
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -080071 // We're not validating/allowlisting the compiler filter, and just assume the compiler will
72 // reject an invalid string. We need to accept "verify" filter anyway, and potential
73 // performance degration by the attacker is not currently in scope. This also allows ART to
74 // specify new compiler filter and configure through system property without change to
75 // CompOS.
76
77 Ok(Self {
78 system_dir_fd,
79 output_dir_fd,
80 staging_dir_fd,
81 target_dir_name,
82 zygote_arch,
83 system_server_compiler_filter,
84 })
Alan Stokes46a1dff2021-12-14 10:56:05 +000085 }
86}
87
88pub fn odrefresh(
89 odrefresh_path: &Path,
90 context: OdrefreshContext,
Victor Hsiehf9968692021-11-18 11:34:39 -080091 authfs_service: Strong<dyn IAuthFsService>,
Alan Stokes46a1dff2021-12-14 10:56:05 +000092 signer: Signer,
93) -> Result<ExitCode> {
Victor Hsiehf9968692021-11-18 11:34:39 -080094 // Mount authfs (via authfs_service). The authfs instance unmounts once the `authfs` variable
95 // is out of scope.
96 let authfs_config = AuthFsConfig {
97 port: FD_SERVER_PORT,
98 inputDirFdAnnotations: vec![InputDirFdAnnotation {
Alan Stokes46a1dff2021-12-14 10:56:05 +000099 fd: context.system_dir_fd,
Victor Hsieh99782572022-01-05 15:38:33 -0800100 // 0 is the index of extra_apks in vm_config_extra_apk.json
101 manifestPath: "/mnt/extra-apk/0/assets/build_manifest.pb".to_string(),
102 prefix: "system/".to_string(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800103 }],
Alan Stokes9646db92021-12-14 13:22:33 +0000104 outputDirFdAnnotations: vec![
Alan Stokes46a1dff2021-12-14 10:56:05 +0000105 OutputDirFdAnnotation { fd: context.output_dir_fd },
106 OutputDirFdAnnotation { fd: context.staging_dir_fd },
Alan Stokes9646db92021-12-14 13:22:33 +0000107 ],
Victor Hsiehf9968692021-11-18 11:34:39 -0800108 ..Default::default()
109 };
110 let authfs = authfs_service.mount(&authfs_config)?;
111 let mountpoint = PathBuf::from(authfs.getMountPoint()?);
112
Alan Stokesfadcef22022-01-24 17:00:59 +0000113 // Make a copy of our environment as the basis of the one we will give odrefresh
114 let mut odrefresh_vars = EnvMap::from_current_env();
115
Victor Hsiehf9968692021-11-18 11:34:39 -0800116 let mut android_root = mountpoint.clone();
Alan Stokes46a1dff2021-12-14 10:56:05 +0000117 android_root.push(context.system_dir_fd.to_string());
Victor Hsiehf9968692021-11-18 11:34:39 -0800118 android_root.push("system");
Alan Stokesfadcef22022-01-24 17:00:59 +0000119 odrefresh_vars.set("ANDROID_ROOT", path_to_str(&android_root)?);
Alan Stokes46a1dff2021-12-14 10:56:05 +0000120 debug!("ANDROID_ROOT={:?}", &android_root);
Victor Hsiehf9968692021-11-18 11:34:39 -0800121
Alan Stokes46a1dff2021-12-14 10:56:05 +0000122 let art_apex_data = mountpoint.join(context.output_dir_fd.to_string());
Alan Stokesfadcef22022-01-24 17:00:59 +0000123 odrefresh_vars.set("ART_APEX_DATA", path_to_str(&art_apex_data)?);
Alan Stokes46a1dff2021-12-14 10:56:05 +0000124 debug!("ART_APEX_DATA={:?}", &art_apex_data);
Victor Hsieh64df53d2021-11-30 17:09:51 -0800125
Alan Stokes46a1dff2021-12-14 10:56:05 +0000126 let staging_dir = mountpoint.join(context.staging_dir_fd.to_string());
Victor Hsiehf9968692021-11-18 11:34:39 -0800127
Alan Stokesfadcef22022-01-24 17:00:59 +0000128 set_classpaths(&mut odrefresh_vars, &android_root)?;
Alan Stokes92472512022-01-04 11:48:38 +0000129
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800130 let mut args = vec![
Victor Hsiehf9968692021-11-18 11:34:39 -0800131 "odrefresh".to_string(),
Alan Stokes48c1d2b2022-01-10 15:54:04 +0000132 "--compilation-os-mode".to_string(),
Alan Stokes46a1dff2021-12-14 10:56:05 +0000133 format!("--zygote-arch={}", context.zygote_arch),
134 format!("--dalvik-cache={}", context.target_dir_name),
Victor Hsiehf9968692021-11-18 11:34:39 -0800135 format!("--staging-dir={}", staging_dir.display()),
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800136 "--no-refresh".to_string(),
Victor Hsiehf9968692021-11-18 11:34:39 -0800137 ];
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800138
139 if !context.system_server_compiler_filter.is_empty() {
140 args.push(format!(
141 "--system-server-compiler-filter={}",
142 context.system_server_compiler_filter
143 ));
144 }
Alan Stokes48c1d2b2022-01-10 15:54:04 +0000145
146 args.push("--compile".to_string());
Victor Hsieh9bfbc5f2021-12-16 11:45:10 -0800147
Alan Stokes9646db92021-12-14 13:22:33 +0000148 debug!("Running odrefresh with args: {:?}", &args);
Alan Stokesfadcef22022-01-24 17:00:59 +0000149 let jail = spawn_jailed_task(odrefresh_path, &args, &odrefresh_vars.into_env())
Victor Hsiehf9968692021-11-18 11:34:39 -0800150 .context("Spawn odrefresh")?;
Alan Stokes46a1dff2021-12-14 10:56:05 +0000151 let exit_code = match jail.wait() {
152 Ok(_) => Result::<u8>::Ok(0),
153 Err(minijail::Error::ReturnCode(exit_code)) => Ok(exit_code),
Victor Hsiehf9968692021-11-18 11:34:39 -0800154 Err(e) => {
155 bail!("Unexpected minijail error: {}", e)
156 }
Alan Stokes46a1dff2021-12-14 10:56:05 +0000157 }?;
158
Alan Stokes126fd512021-12-16 15:00:01 +0000159 let exit_code = ExitCode::from_i32(exit_code.into())?;
Alan Stokes46a1dff2021-12-14 10:56:05 +0000160 info!("odrefresh exited with {:?}", exit_code);
161
162 if exit_code == ExitCode::CompilationSuccess {
163 // authfs only shows us the files we created, so it's ok to just sign everything under
164 // the target directory.
165 let target_dir = art_apex_data.join(context.target_dir_name);
166 let mut artifact_signer = ArtifactSigner::new(&target_dir);
167 add_artifacts(&target_dir, &mut artifact_signer)?;
168
169 artifact_signer.write_info_and_signature(signer, &target_dir.join("compos.info"))?;
Victor Hsiehf9968692021-11-18 11:34:39 -0800170 }
Alan Stokes46a1dff2021-12-14 10:56:05 +0000171
172 Ok(exit_code)
173}
174
Alan Stokesfadcef22022-01-24 17:00:59 +0000175fn path_to_str(path: &Path) -> Result<&str> {
176 path.to_str().ok_or_else(|| anyhow!("Bad path {:?}", path))
177}
178
179fn set_classpaths(odrefresh_vars: &mut EnvMap, android_root: &Path) -> Result<()> {
Alan Stokes92472512022-01-04 11:48:38 +0000180 let export_lines = run_derive_classpath(android_root)?;
Alan Stokesfadcef22022-01-24 17:00:59 +0000181 load_classpath_vars(odrefresh_vars, &export_lines)
Alan Stokes92472512022-01-04 11:48:38 +0000182}
183
184fn run_derive_classpath(android_root: &Path) -> Result<String> {
185 let classpaths_root = android_root.join("etc/classpaths");
186
187 let mut bootclasspath_arg = OsString::new();
188 bootclasspath_arg.push("--bootclasspath-fragment=");
189 bootclasspath_arg.push(classpaths_root.join("bootclasspath.pb"));
190
191 let mut systemserverclasspath_arg = OsString::new();
192 systemserverclasspath_arg.push("--systemserverclasspath-fragment=");
193 systemserverclasspath_arg.push(classpaths_root.join("systemserverclasspath.pb"));
194
195 let result = Command::new("/apex/com.android.sdkext/bin/derive_classpath")
196 .arg(bootclasspath_arg)
197 .arg(systemserverclasspath_arg)
198 .arg("/proc/self/fd/1")
199 .output()
200 .context("Failed to run derive_classpath")?;
201
202 if !result.status.success() {
203 bail!("derive_classpath returned {}", result.status);
204 }
205
206 String::from_utf8(result.stdout).context("Converting derive_classpath output")
207}
208
Alan Stokesfadcef22022-01-24 17:00:59 +0000209fn load_classpath_vars(odrefresh_vars: &mut EnvMap, export_lines: &str) -> Result<()> {
Alan Stokes92472512022-01-04 11:48:38 +0000210 // Each line should be in the format "export <var name> <value>"
211 let pattern = Regex::new(r"^export ([^ ]+) ([^ ]+)$").context("Failed to construct Regex")?;
212 for line in export_lines.lines() {
213 if let Some(captures) = pattern.captures(line) {
214 let name = &captures[1];
215 let value = &captures[2];
Alan Stokesfadcef22022-01-24 17:00:59 +0000216 odrefresh_vars.set(name, value);
Alan Stokes92472512022-01-04 11:48:38 +0000217 } else {
218 warn!("Malformed line from derive_classpath: {}", line);
219 }
220 }
221
222 Ok(())
223}
224
Alan Stokes46a1dff2021-12-14 10:56:05 +0000225fn add_artifacts(target_dir: &Path, artifact_signer: &mut ArtifactSigner) -> Result<()> {
226 for entry in
227 read_dir(&target_dir).with_context(|| format!("Traversing {}", target_dir.display()))?
228 {
229 let entry = entry?;
230 let file_type = entry.file_type()?;
231 if file_type.is_dir() {
232 add_artifacts(&entry.path(), artifact_signer)?;
233 } else if file_type.is_file() {
234 artifact_signer.add_artifact(&entry.path())?;
235 } else {
236 // authfs shouldn't create anything else, but just in case
237 bail!("Unexpected file type in artifacts: {:?}", entry);
238 }
239 }
240 Ok(())
Victor Hsiehf9968692021-11-18 11:34:39 -0800241}
242
Alan Stokesfadcef22022-01-24 17:00:59 +0000243fn spawn_jailed_task(executable: &Path, args: &[String], env_vars: &[String]) -> Result<Minijail> {
Victor Hsieh51789de2021-08-06 16:50:49 -0700244 // TODO(b/185175567): Run in a more restricted sandbox.
245 let jail = Minijail::new()?;
Alan Stokesfadcef22022-01-24 17:00:59 +0000246 let keep_fds = [];
247 let command = minijail::Command::new_for_path(executable, &keep_fds, args, Some(env_vars))?;
248 let _pid = jail.run_command(command)?;
Victor Hsieh51789de2021-08-06 16:50:49 -0700249 Ok(jail)
250}
Alan Stokesfadcef22022-01-24 17:00:59 +0000251
252struct EnvMap(HashMap<String, String>);
253
254impl EnvMap {
255 fn from_current_env() -> Self {
256 Self(env::vars().collect())
257 }
258
259 fn set(&mut self, key: &str, value: &str) {
260 self.0.insert(key.to_owned(), value.to_owned());
261 }
262
263 fn into_env(self) -> Vec<String> {
264 // execve() expects an array of "k=v" strings, rather than a list of (k, v) pairs.
265 self.0.into_iter().map(|(k, v)| k + "=" + &v).collect()
266 }
267}