Use CompOsKeyService as compsvc factory.

Define a Signer trait to encapsulate what we need to do to sign a
digest.

Modify compsvc to hold a signer.

Modify CompOsKeyService to be able to take in a keyblob and produce a
signer, then return a compsvc instance holding that signer.

This doesn't yet do anything with the signer. Eventually we will want
to use it to generate signatures on output artifacts.

Bug: 194267113
Test: atest ComposHostTestCases (with testOdrefesh un-ignored)
Change-Id: I72aead0280914987f7c8d1721c1e12ee0fad1af4
diff --git a/compos/Android.bp b/compos/Android.bp
index ad99d51..2c864e7 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -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 3903cd0..24e52f5 100644
--- a/compos/src/compsvc.rs
+++ b/compos/src/compsvc.rs
@@ -30,6 +30,7 @@
 use minijail::{self, Minijail};
 use std::path::PathBuf;
 
+use crate::signer::Signer;
 use compos_aidl_interface::aidl::com::android::compos::ICompService::{
     BnCompService, ICompService,
 };
@@ -46,8 +47,17 @@
 /// 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, debuggable: bool) -> Strong<dyn ICompService> {
-    let service = CompService { worker_bin: PathBuf::from(WORKER_BIN), task_bin, debuggable };
+pub fn new_binder(
+    task_bin: String,
+    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())
 }
 
@@ -55,6 +65,8 @@
     task_bin: String,
     worker_bin: PathBuf,
     debuggable: bool,
+    #[allow(dead_code)] // TODO: Make use of this
+    signer: Option<Box<dyn Signer>>,
 }
 
 impl CompService {
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
index 111a819..9f12132 100644
--- a/compos/src/compsvc_main.rs
+++ b/compos/src/compsvc_main.rs
@@ -22,6 +22,7 @@
 
 mod common;
 mod compsvc;
+mod signer;
 
 use crate::common::{SERVICE_NAME, VSOCK_PORT};
 use anyhow::{bail, Context, Result};
@@ -59,7 +60,7 @@
     );
 
     let config = parse_args()?;
-    let mut service = compsvc::new_binder(config.task_bin, config.debuggable).as_binder();
+    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.
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>>;
+}