Merge changes from topic "vm_sepolicy"

* changes:
  Run MicrodroidHostTestCase with selinux enforced
  Pass payload disk images as file descriptors rather than paths.
diff --git a/compos/Android.bp b/compos/Android.bp
index 9428210..2c864e7 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -28,7 +28,7 @@
 
 rust_binary {
     name: "compsvc",
-    srcs: ["src/compsvc.rs"],
+    srcs: ["src/compsvc_main.rs"],
     rustlibs: [
         "compos_aidl_interface-rust",
         "libandroid_logger",
@@ -80,6 +80,7 @@
         "libbinder_rpc_unstable_bindgen",
         "libclap",
         "liblog_rust",
+        "libminijail_rust",
         "libring",
         "libscopeguard",
     ],
diff --git a/compos/aidl/com/android/compos/ICompOsKeyService.aidl b/compos/aidl/com/android/compos/ICompOsKeyService.aidl
index a2ff917..eb2caa7 100644
--- a/compos/aidl/com/android/compos/ICompOsKeyService.aidl
+++ b/compos/aidl/com/android/compos/ICompOsKeyService.aidl
@@ -17,6 +17,7 @@
 package com.android.compos;
 
 import com.android.compos.CompOsKeyData;
+import com.android.compos.ICompService;
 
 /** {@hide} */
 interface ICompOsKeyService {
@@ -48,4 +49,13 @@
      */
     // STOPSHIP(b/193241041): We must not expose this from the PVM.
     byte[] sign(in byte[] keyBlob, in byte[] data);
+
+    /**
+     * Return an instance of ICompService that will sign output files with a given encrypted
+     * private key.
+     *
+     * @param keyBlob The encrypted blob containing the private key, as returned by
+     *                generateSigningKey().
+     */
+    ICompService getCompService(in byte[] keyBlob);
 }
diff --git a/compos/src/compos_key_main.rs b/compos/src/compos_key_main.rs
index 9135c18..9d57e4d 100644
--- a/compos/src/compos_key_main.rs
+++ b/compos/src/compos_key_main.rs
@@ -16,12 +16,13 @@
 //! VM using RPC Binder.
 
 mod compos_key_service;
+mod compsvc;
+mod signer;
 
-use crate::compos_key_service::{CompOsKeyService, KeystoreNamespace};
+use crate::compos_key_service::KeystoreNamespace;
 use anyhow::{bail, Context, Result};
 use binder::unstable_api::AsNative;
-use compos_aidl_interface::aidl::com::android::compos::ICompOsKeyService::BnCompOsKeyService;
-use compos_aidl_interface::binder::{add_service, BinderFeatures, ProcessState};
+use compos_aidl_interface::binder::{add_service, ProcessState};
 use log::{info, Level};
 
 const LOG_TAG: &str = "CompOsKeyService";
@@ -41,9 +42,7 @@
 
     let key_namespace =
         if rpc_binder { KeystoreNamespace::VmPayload } else { KeystoreNamespace::Odsign };
-    let service = CompOsKeyService::new(key_namespace)?;
-    let mut service =
-        BnCompOsKeyService::new_binder(service, BinderFeatures::default()).as_binder();
+    let mut service = compos_key_service::new(key_namespace)?.as_binder();
 
     if rpc_binder {
         info!("Starting RPC service");
diff --git a/compos/src/compos_key_service.rs b/compos/src/compos_key_service.rs
index 66451b3..40d0f48 100644
--- a/compos/src/compos_key_service.rs
+++ b/compos/src/compos_key_service.rs
@@ -16,6 +16,8 @@
 //! access to Keystore in the VM, but not persistent storage; instead the host stores the key
 //! on our behalf via this service.
 
+use crate::compsvc;
+use crate::signer::Signer;
 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
     Algorithm::Algorithm, Digest::Digest, KeyParameter::KeyParameter,
     KeyParameterValue::KeyParameterValue, KeyPurpose::KeyPurpose, PaddingMode::PaddingMode,
@@ -27,10 +29,12 @@
 };
 use anyhow::{anyhow, Context, Result};
 use compos_aidl_interface::aidl::com::android::compos::{
-    CompOsKeyData::CompOsKeyData, ICompOsKeyService::ICompOsKeyService,
+    CompOsKeyData::CompOsKeyData,
+    ICompOsKeyService::{BnCompOsKeyService, ICompOsKeyService},
+    ICompService::ICompService,
 };
 use compos_aidl_interface::binder::{
-    self, wait_for_interface, ExceptionCode, Interface, Status, Strong,
+    self, wait_for_interface, BinderFeatures, ExceptionCode, Interface, Status, Strong,
 };
 use log::warn;
 use ring::rand::{SecureRandom, SystemRandom};
@@ -48,6 +52,23 @@
     VmPayload = 140,
 }
 
+/// Constructs a binder object that implements ICompOsKeyService. namespace is the Keystore2 namespace to
+/// use for the keys.
+pub fn new(namespace: KeystoreNamespace) -> Result<Strong<dyn ICompOsKeyService>> {
+    let keystore_service = wait_for_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
+        .context("No Keystore service")?;
+
+    let service = CompOsKeyService {
+        namespace,
+        random: SystemRandom::new(),
+        security_level: keystore_service
+            .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
+            .context("Getting SecurityLevel failed")?,
+    };
+
+    Ok(BnCompOsKeyService::new_binder(service, BinderFeatures::default()))
+}
+
 const KEYSTORE_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
 const PURPOSE_SIGN: KeyParameter =
     KeyParameter { tag: Tag::PURPOSE, value: KeyParameterValue::KeyPurpose(KeyPurpose::SIGN) };
@@ -69,7 +90,8 @@
 const BLOB_KEY_DESCRIPTOR: KeyDescriptor =
     KeyDescriptor { domain: Domain::BLOB, nspace: 0, alias: None, blob: None };
 
-pub struct CompOsKeyService {
+#[derive(Clone)]
+struct CompOsKeyService {
     namespace: KeystoreNamespace,
     random: SystemRandom,
     security_level: Strong<dyn IKeystoreSecurityLevel>,
@@ -96,6 +118,17 @@
         self.do_sign(key_blob, data)
             .map_err(|e| new_binder_exception(ExceptionCode::ILLEGAL_STATE, e.to_string()))
     }
+
+    fn getCompService(&self, key_blob: &[u8]) -> binder::Result<Strong<dyn ICompService>> {
+        let signer =
+            Box::new(CompOsSigner { key_blob: key_blob.to_owned(), key_service: self.clone() });
+        let debuggable = true;
+        Ok(compsvc::new_binder(
+            "/apex/com.android.art/bin/dex2oat64".to_owned(),
+            debuggable,
+            Some(signer),
+        ))
+    }
 }
 
 /// Constructs a new Binder error `Status` with the given `ExceptionCode` and message.
@@ -103,20 +136,18 @@
     Status::new_exception(exception, CString::new(message.as_ref()).ok().as_deref())
 }
 
-impl CompOsKeyService {
-    pub fn new(namespace: KeystoreNamespace) -> Result<Self> {
-        let keystore_service = wait_for_interface::<dyn IKeystoreService>(KEYSTORE_SERVICE_NAME)
-            .context("No Keystore service")?;
+struct CompOsSigner {
+    key_blob: Vec<u8>,
+    key_service: CompOsKeyService,
+}
 
-        Ok(Self {
-            namespace,
-            random: SystemRandom::new(),
-            security_level: keystore_service
-                .getSecurityLevel(SecurityLevel::TRUSTED_ENVIRONMENT)
-                .context("Getting SecurityLevel failed")?,
-        })
+impl Signer for CompOsSigner {
+    fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
+        self.key_service.do_sign(&self.key_blob, data)
     }
+}
 
+impl CompOsKeyService {
     fn do_generate(&self) -> Result<CompOsKeyData> {
         let key_descriptor = KeyDescriptor { nspace: self.namespace as i64, ..BLOB_KEY_DESCRIPTOR };
         let key_parameters =
diff --git a/compos/src/compsvc.rs b/compos/src/compsvc.rs
index 4ad2e03..24e52f5 100644
--- a/compos/src/compsvc.rs
+++ b/compos/src/compsvc.rs
@@ -19,49 +19,57 @@
 //! read/write. The service also attempts to sandbox the execution so that one task cannot leak or
 //! impact future tasks.
 //!
-//! Example:
-//! $ compsvc /system/bin/sleep
-//!
 //! The current architecture / process hierarchy looks like:
 //! - compsvc (handle requests)
 //!   - compsvc_worker (for environment setup)
 //!     - authfs (fd translation)
 //!     - actual task
 
-use anyhow::{bail, Context, Result};
-use binder::unstable_api::AsNative;
-use log::{debug, error};
+use anyhow::Result;
+use log::error;
 use minijail::{self, Minijail};
 use std::path::PathBuf;
 
+use crate::signer::Signer;
 use compos_aidl_interface::aidl::com::android::compos::ICompService::{
     BnCompService, ICompService,
 };
 use compos_aidl_interface::aidl::com::android::compos::Metadata::Metadata;
 use compos_aidl_interface::binder::{
-    add_service, BinderFeatures, Interface, ProcessState, Result as BinderResult, Status,
-    StatusCode, Strong,
+    BinderFeatures, Interface, Result as BinderResult, Status, StatusCode, Strong,
 };
 
-mod common;
-use common::{SERVICE_NAME, VSOCK_PORT};
-
 const WORKER_BIN: &str = "/apex/com.android.compos/bin/compsvc_worker";
+
 // TODO: Replace with a valid directory setup in the VM.
 const AUTHFS_MOUNTPOINT: &str = "/data/local/tmp";
 
-struct CompService {
-    worker_bin: PathBuf,
+/// Constructs a binder object that implements ICompService. task_bin is the path to the binary that will
+/// be run when execute() is called. If debuggable is true then stdout/stderr from the binary will be
+/// available for debugging.
+pub fn new_binder(
     task_bin: String,
-    rpc_binder: bool,
     debuggable: bool,
+    signer: Option<Box<dyn Signer>>,
+) -> Strong<dyn ICompService> {
+    let service = CompService {
+        worker_bin: PathBuf::from(WORKER_BIN.to_owned()),
+        task_bin,
+        debuggable,
+        signer,
+    };
+    BnCompService::new_binder(service, BinderFeatures::default())
+}
+
+struct CompService {
+    task_bin: String,
+    worker_bin: PathBuf,
+    debuggable: bool,
+    #[allow(dead_code)] // TODO: Make use of this
+    signer: Option<Box<dyn Signer>>,
 }
 
 impl CompService {
-    pub fn new_binder(service: CompService) -> Strong<dyn ICompService> {
-        BnCompService::new_binder(service, BinderFeatures::default())
-    }
-
     fn run_worker_in_jail_and_wait(&self, args: &[String]) -> Result<(), minijail::Error> {
         let mut jail = Minijail::new()?;
 
@@ -124,56 +132,3 @@
         }
     }
 }
-
-fn parse_args() -> Result<CompService> {
-    #[rustfmt::skip]
-    let matches = clap::App::new("compsvc")
-        .arg(clap::Arg::with_name("debug")
-             .long("debug"))
-        .arg(clap::Arg::with_name("task_bin")
-             .required(true))
-        .arg(clap::Arg::with_name("rpc_binder")
-             .long("rpc-binder"))
-        .get_matches();
-
-    Ok(CompService {
-        task_bin: matches.value_of("task_bin").unwrap().to_string(),
-        worker_bin: PathBuf::from(WORKER_BIN),
-        rpc_binder: matches.is_present("rpc_binder"),
-        debuggable: matches.is_present("debug"),
-    })
-}
-
-fn main() -> Result<()> {
-    android_logger::init_once(
-        android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
-    );
-
-    let service = parse_args()?;
-
-    if service.rpc_binder {
-        let mut service = CompService::new_binder(service).as_binder();
-        debug!("compsvc is starting as a rpc service.");
-        // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
-        // Plus the binder objects are threadsafe.
-        let retval = unsafe {
-            binder_rpc_unstable_bindgen::RunRpcServer(
-                service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
-                VSOCK_PORT,
-            )
-        };
-        if retval {
-            debug!("RPC server has shut down gracefully");
-            Ok(())
-        } else {
-            bail!("Premature termination of RPC server");
-        }
-    } else {
-        ProcessState::start_thread_pool();
-        debug!("compsvc is starting as a local service.");
-        add_service(SERVICE_NAME, CompService::new_binder(service).as_binder())
-            .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
-        ProcessState::join_thread_pool();
-        bail!("Unexpected exit after join_thread_pool")
-    }
-}
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
new file mode 100644
index 0000000..9f12132
--- /dev/null
+++ b/compos/src/compsvc_main.rs
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+//! A tool to start a standalone compsvc server, either in the host using Binder or in a VM using
+//! RPC binder over vsock.
+//!
+//! Example:
+//! $ compsvc /system/bin/sleep
+
+mod common;
+mod compsvc;
+mod signer;
+
+use crate::common::{SERVICE_NAME, VSOCK_PORT};
+use anyhow::{bail, Context, Result};
+use binder::unstable_api::AsNative;
+use compos_aidl_interface::binder::{add_service, ProcessState};
+use log::debug;
+
+struct Config {
+    task_bin: String,
+    rpc_binder: bool,
+    debuggable: bool,
+}
+
+fn parse_args() -> Result<Config> {
+    #[rustfmt::skip]
+    let matches = clap::App::new("compsvc")
+        .arg(clap::Arg::with_name("debug")
+             .long("debug"))
+        .arg(clap::Arg::with_name("task_bin")
+             .required(true))
+        .arg(clap::Arg::with_name("rpc_binder")
+             .long("rpc-binder"))
+        .get_matches();
+
+    Ok(Config {
+        task_bin: matches.value_of("task_bin").unwrap().to_string(),
+        rpc_binder: matches.is_present("rpc_binder"),
+        debuggable: matches.is_present("debug"),
+    })
+}
+
+fn main() -> Result<()> {
+    android_logger::init_once(
+        android_logger::Config::default().with_tag("compsvc").with_min_level(log::Level::Debug),
+    );
+
+    let config = parse_args()?;
+    let mut service = compsvc::new_binder(config.task_bin, config.debuggable, None).as_binder();
+    if config.rpc_binder {
+        debug!("compsvc is starting as a rpc service.");
+        // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
+        // Plus the binder objects are threadsafe.
+        let retval = unsafe {
+            binder_rpc_unstable_bindgen::RunRpcServer(
+                service.as_native_mut() as *mut binder_rpc_unstable_bindgen::AIBinder,
+                VSOCK_PORT,
+            )
+        };
+        if retval {
+            debug!("RPC server has shut down gracefully");
+            Ok(())
+        } else {
+            bail!("Premature termination of RPC server");
+        }
+    } else {
+        ProcessState::start_thread_pool();
+        debug!("compsvc is starting as a local service.");
+        add_service(SERVICE_NAME, service)
+            .with_context(|| format!("Failed to register service {}", SERVICE_NAME))?;
+        ProcessState::join_thread_pool();
+        bail!("Unexpected exit after join_thread_pool")
+    }
+}
diff --git a/compos/src/signer.rs b/compos/src/signer.rs
new file mode 100644
index 0000000..9ff1477
--- /dev/null
+++ b/compos/src/signer.rs
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+use anyhow::Result;
+
+/// Provides the ability to cryptographically sign messages.
+pub trait Signer: Send + Sync {
+    /// Sign the supplied data. The result is a raw signature over the input data.
+    fn sign(&self, data: &[u8]) -> Result<Vec<u8>>;
+}
diff --git a/microdroid_manager/Android.bp b/microdroid_manager/Android.bp
index 902b5da..dabcf31 100644
--- a/microdroid_manager/Android.bp
+++ b/microdroid_manager/Android.bp
@@ -11,7 +11,6 @@
     rustlibs: [
         "libanyhow",
         "libkernlog",
-        "libkeystore2_system_property-rust",
         "liblibc",
         "liblog_rust",
         "libmicrodroid_metadata",
@@ -19,6 +18,7 @@
         "libprotobuf",
         "libserde",
         "libserde_json",
+        "libsystem_properties-rust",
         "libvsock",
     ],
     init_rc: ["microdroid_manager.rc"],
diff --git a/microdroid_manager/src/main.rs b/microdroid_manager/src/main.rs
index 1506142..9efa68a 100644
--- a/microdroid_manager/src/main.rs
+++ b/microdroid_manager/src/main.rs
@@ -18,7 +18,6 @@
 mod metadata;
 
 use anyhow::{anyhow, bail, Result};
-use keystore2_system_property::PropertyWatcher;
 use log::{error, info, warn};
 use microdroid_payload_config::{Task, TaskType, VmPayloadConfig};
 use std::fs::{self, File};
@@ -27,6 +26,7 @@
 use std::process::{Command, Stdio};
 use std::str;
 use std::time::Duration;
+use system_properties::PropertyWatcher;
 use vsock::VsockStream;
 
 const WAIT_TIMEOUT: Duration = Duration::from_secs(10);
@@ -40,7 +40,7 @@
         let config = load_config(Path::new(&metadata.payload_config_path))?;
 
         let fake_secret = "This is a placeholder for a value that is derived from the images that are loaded in the VM.";
-        if let Err(err) = keystore2_system_property::write("ro.vmsecret.keymint", fake_secret) {
+        if let Err(err) = system_properties::write("ro.vmsecret.keymint", fake_secret) {
             warn!("failed to set ro.vmsecret.keymint: {}", err);
         }