Rewrite key management & signing

Extend compos_helper to support signing, use it from CompOS.

Expose the public key from the VM. Rename compos_verify_key to
compos_verify and get it to verify the signature against the current
instance's public key.

Also move DICE access to compos_key_main. There's no use having it in
the library - neither the tests nor compos_verify can use it - and it
complicates the build rules.

There's a lot more that can be deleted, but I'll do that in a
follow-up; this is big enough already.

Bug: 218494522
Test: atest CompOsSigningHostTest CompOsDenialHostTest
Change-Id: I2d71f68a595d5ddadb2e7b16937fa6855f5db0ab
diff --git a/compos/src/artifact_signer.rs b/compos/src/artifact_signer.rs
index b5eb8cb..a15df28 100644
--- a/compos/src/artifact_signer.rs
+++ b/compos/src/artifact_signer.rs
@@ -17,10 +17,8 @@
 //! Support for generating and signing an info file listing names and digests of generated
 //! artifacts.
 
-#![allow(dead_code)] // Will be used soon
-
+use crate::compos_key;
 use crate::fsverity;
-use crate::signing_key::DiceSigner;
 use anyhow::{anyhow, Context, Result};
 use odsign_proto::odsign_info::OdsignInfo;
 use protobuf::Message;
@@ -63,12 +61,12 @@
 
     /// Consume this ArtifactSigner and write details of all its artifacts to the given path,
     /// with accompanying sigature file.
-    pub fn write_info_and_signature(self, signer: DiceSigner, info_path: &Path) -> Result<()> {
+    pub fn write_info_and_signature(self, info_path: &Path) -> Result<()> {
         let mut info = OdsignInfo::new();
         info.mut_file_hashes().extend(self.file_digests.into_iter());
         let bytes = info.write_to_bytes()?;
 
-        let signature = signer.sign(&bytes)?;
+        let signature = compos_key::sign(&bytes)?;
 
         let mut file =
             File::create(info_path).with_context(|| format!("Creating {}", info_path.display()))?;
diff --git a/compos/src/compos_key.rs b/compos/src/compos_key.rs
new file mode 100644
index 0000000..eb6248f
--- /dev/null
+++ b/compos/src/compos_key.rs
@@ -0,0 +1,64 @@
+/*
+ * Copyright 2022 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::{bail, Context, Result};
+use std::io::Write;
+use std::process::{Command, Stdio};
+
+const COMPOS_KEY_HELPER_PATH: &str = "/apex/com.android.compos/bin/compos_key_helper";
+
+pub fn get_public_key() -> Result<Vec<u8>> {
+    let child = Command::new(COMPOS_KEY_HELPER_PATH)
+        .arg("public_key")
+        .stdin(Stdio::null())
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped())
+        .spawn()?;
+    let result = child.wait_with_output()?;
+    if !result.status.success() {
+        bail!("Helper failed: {:?}", result);
+    }
+    Ok(result.stdout)
+}
+
+pub fn sign(data: &[u8]) -> Result<Vec<u8>> {
+    let mut child = Command::new(COMPOS_KEY_HELPER_PATH)
+        .arg("sign")
+        .stdin(Stdio::piped())
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped())
+        .spawn()?;
+
+    // No output is written until the entire input is consumed, so this shouldn't deadlock.
+    let result =
+        child.stdin.take().unwrap().write_all(data).context("Failed to write data to be signed");
+    if result.is_ok() {
+        let result = child.wait_with_output()?;
+        if !result.status.success() {
+            bail!("Helper failed: {}", result.status);
+        }
+        return Ok(result.stdout);
+    }
+
+    // The child may have exited already, but if it hasn't then we need to make sure it does.
+    let _ignored = child.kill();
+
+    let result = result.with_context(|| match child.wait() {
+        Ok(exit_status) => format!("Child exited: {}", exit_status),
+        Err(wait_err) => format!("Wait for child failed: {:?}", wait_err),
+    });
+    Err(result.unwrap_err())
+}
diff --git a/compos/src/compsvc.rs b/compos/src/compsvc.rs
index 5f3ee62..df36ed9 100644
--- a/compos/src/compsvc.rs
+++ b/compos/src/compsvc.rs
@@ -29,6 +29,7 @@
 
 use crate::artifact_signer::ArtifactSigner;
 use crate::compilation::{odrefresh, OdrefreshContext};
+use crate::compos_key;
 use crate::dice::Dice;
 use crate::signing_key::DiceSigningKey;
 use authfs_aidl_interface::aidl::com::android::virt::fs::IAuthFsService::IAuthFsService;
@@ -108,8 +109,7 @@
                 let mut artifact_signer = ArtifactSigner::new(&output_dir);
                 add_artifacts(&output_dir, &mut artifact_signer)?;
 
-                let signer = to_binder_result(self.signing_key.new_signer(key))?;
-                artifact_signer.write_info_and_signature(signer, &output_dir.join("compos.info"))
+                artifact_signer.write_info_and_signature(&output_dir.join("compos.info"))
             })
             .context("odrefresh failed"),
         )?;
@@ -128,6 +128,10 @@
             true
         })
     }
+
+    fn getPublicKey(&self) -> BinderResult<Vec<u8>> {
+        to_binder_result(compos_key::get_public_key())
+    }
 }
 
 fn get_authfs_service() -> BinderResult<Strong<dyn IAuthFsService>> {
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
index 16e3031..f0af752 100644
--- a/compos/src/compsvc_main.rs
+++ b/compos/src/compsvc_main.rs
@@ -19,6 +19,7 @@
 mod artifact_signer;
 mod blob_encryption;
 mod compilation;
+mod compos_key;
 mod compsvc;
 mod dice;
 mod fsverity;
diff --git a/compos/src/signing_key.rs b/compos/src/signing_key.rs
index 90beecf..b1a3238 100644
--- a/compos/src/signing_key.rs
+++ b/compos/src/signing_key.rs
@@ -17,8 +17,6 @@
 //! RSA key pair generation, persistence (with the private key encrypted), verification and
 //! signing.
 
-#![allow(dead_code, unused_variables)]
-
 use crate::blob_encryption;
 use crate::dice::Dice;
 use anyhow::{bail, Context, Result};
@@ -29,7 +27,6 @@
 };
 
 pub type DiceSigningKey = SigningKey<Dice>;
-pub type DiceSigner = Signer<Dice>;
 
 pub struct SigningKey<T: SecretStore> {
     secret_store: T,