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/Android.bp b/compos/Android.bp
index d4fccbb..0af0ec4 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -19,7 +19,6 @@
         "libclap",
         "libcompos_common",
         "libcompos_native_rust",
-        "libenv_logger",
         "liblibc",
         "liblog_rust",
         "libminijail_rust",
diff --git a/compos/aidl/com/android/compos/ICompOsService.aidl b/compos/aidl/com/android/compos/ICompOsService.aidl
index 18e163e..5f1df6f 100644
--- a/compos/aidl/com/android/compos/ICompOsService.aidl
+++ b/compos/aidl/com/android/compos/ICompOsService.aidl
@@ -79,4 +79,10 @@
      * @return whether the inputs are valid and correspond to each other.
      */
     boolean verifySigningKey(in byte[] keyBlob, in byte[] publicKey);
+
+    /**
+     * Returns the current VM's signing key, as an Ed25519 public key
+     * (https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5).
+     */
+    byte[] getPublicKey();
 }
diff --git a/compos/apex/Android.bp b/compos/apex/Android.bp
index 6550b4f..4ff0635 100644
--- a/compos/apex/Android.bp
+++ b/compos/apex/Android.bp
@@ -42,7 +42,7 @@
 
     binaries: [
         // Used in Android
-        "compos_verify_key",
+        "compos_verify",
         "composd",
         "composd_cmd",
 
diff --git a/compos/common/compos_client.rs b/compos/common/compos_client.rs
index b754ba7..dcacb0f 100644
--- a/compos/common/compos_client.rs
+++ b/compos/common/compos_client.rs
@@ -114,6 +114,7 @@
             let log_fd = ParcelFileDescriptor::new(log_fd);
             // Full debug is not available in a protected VM
             let debug_level = if protected_vm { DebugLevel::APP_ONLY } else { DebugLevel::FULL };
+            info!("Debug mode is {:?}", debug_level);
             (Some(console_fd), Some(log_fd), debug_level)
         } else {
             (None, None, DebugLevel::NONE)
diff --git a/compos/common/odrefresh.rs b/compos/common/odrefresh.rs
index 7fe6ed5..390e50c 100644
--- a/compos/common/odrefresh.rs
+++ b/compos/common/odrefresh.rs
@@ -23,6 +23,18 @@
 /// The path to the odrefresh binary
 pub const ODREFRESH_PATH: &str = "/apex/com.android.art/bin/odrefresh";
 
+/// The path under which odrefresh writes compiled artifacts
+pub const ODREFRESH_OUTPUT_ROOT_DIR: &str = "/data/misc/apexdata/com.android.art";
+
+/// The directory under ODREFRESH_OUTPUT_ROOT_DIR where pending artifacts are written
+pub const PENDING_ARTIFACTS_SUBDIR: &str = "compos-pending";
+
+/// The directory under ODREFRESH_OUTPUT_ROOT_DIR where test artifacts are written
+pub const TEST_ARTIFACTS_SUBDIR: &str = "test-artifacts";
+
+/// The directory under ODREFRESH_OUTPUT_ROOT_DIR where the current (active) artifacts are stored
+pub const CURRENT_ARTIFACTS_SUBDIR: &str = "dalvik-cache";
+
 // The highest "standard" exit code defined in sysexits.h (as EX__MAX); odrefresh error codes
 // start above here to avoid clashing.
 // TODO: What if this changes?
diff --git a/compos/common/timeouts.rs b/compos/common/timeouts.rs
index e6cc430..b3ec1e5 100644
--- a/compos/common/timeouts.rs
+++ b/compos/common/timeouts.rs
@@ -56,7 +56,7 @@
     // Note: the source of truth for these odrefresh timeouts is art/odrefresh/odr_config.h.
     odrefresh_max_execution_time: Duration::from_secs(300),
     odrefresh_max_child_process_time: Duration::from_secs(90),
-    vm_max_time_to_ready: Duration::from_secs(15),
+    vm_max_time_to_ready: Duration::from_secs(20),
 };
 
 /// The timeouts that we use when need_extra_time() returns true.
diff --git a/compos/compos_key_helper/Android.bp b/compos/compos_key_helper/Android.bp
index c53d88d..a932b40 100644
--- a/compos/compos_key_helper/Android.bp
+++ b/compos/compos_key_helper/Android.bp
@@ -8,7 +8,6 @@
 
     shared_libs: [
         "libbase",
-        "libbinder_ndk",
         "libcrypto",
     ],
 }
@@ -17,11 +16,7 @@
     name: "libcompos_key",
     defaults: ["compos_key_defaults"],
     srcs: ["compos_key.cpp"],
-
-    shared_libs: [
-        "android.hardware.security.dice-V1-ndk",
-        "android.security.dice-ndk",
-    ],
+    export_include_dirs: ["."],
 }
 
 cc_binary {
@@ -31,7 +26,9 @@
 
     static_libs: ["libcompos_key"],
     shared_libs: [
+        "android.hardware.security.dice-V1-ndk",
         "android.security.dice-ndk",
+        "libbinder_ndk",
     ],
 }
 
diff --git a/compos/compos_key_helper/compos_key.cpp b/compos/compos_key_helper/compos_key.cpp
index 84a736d..2e3252c 100644
--- a/compos/compos_key_helper/compos_key.cpp
+++ b/compos/compos_key_helper/compos_key.cpp
@@ -16,24 +16,20 @@
 
 #include "compos_key.h"
 
-#include <aidl/android/security/dice/IDiceNode.h>
-#include <android/binder_auto_utils.h>
-#include <android/binder_manager.h>
 #include <openssl/digest.h>
 #include <openssl/hkdf.h>
 #include <openssl/mem.h>
-#include <unistd.h>
 
-using aidl::android::hardware::security::dice::BccHandover;
-using aidl::android::hardware::security::dice::InputValues;
-using aidl::android::security::dice::IDiceNode;
 using android::base::ErrnoError;
 using android::base::Error;
 using android::base::Result;
+using compos_key::Ed25519KeyPair;
+using compos_key::Signature;
 
 // Used to ensure the key we derive is distinct from any other.
 constexpr const char* kSigningKeyInfo = "CompOS signing key";
 
+namespace compos_key {
 Result<Ed25519KeyPair> deriveKeyFromSecret(const uint8_t* secret, size_t secret_size) {
     // Ed25519 private keys are derived from a 32 byte seed:
     // https://datatracker.ietf.org/doc/html/rfc8032#section-5.1.5
@@ -64,22 +60,4 @@
             size_t data_size) {
     return ED25519_verify(data, data_size, signature.data(), public_key.data()) == 1;
 }
-
-Result<Ed25519KeyPair> deriveKeyFromDice() {
-    ndk::SpAIBinder binder{AServiceManager_getService("android.security.dice.IDiceNode")};
-    auto dice_node = IDiceNode::fromBinder(binder);
-    if (!dice_node) {
-        return Error() << "Unable to connect to IDiceNode";
-    }
-
-    const std::vector<InputValues> empty_input_values;
-    BccHandover bcc;
-    auto status = dice_node->derive(empty_input_values, &bcc);
-    if (!status.isOk()) {
-        return Error() << "Derive failed: " << status.getDescription();
-    }
-
-    // We use the sealing CDI because we want stability - the key needs to be the same
-    // for any instance of the "same" VM.
-    return deriveKeyFromSecret(bcc.cdiSeal.data(), bcc.cdiSeal.size());
-}
+} // namespace compos_key
diff --git a/compos/compos_key_helper/compos_key.h b/compos/compos_key_helper/compos_key.h
index 520f846..e9c6061 100644
--- a/compos/compos_key_helper/compos_key.h
+++ b/compos/compos_key_helper/compos_key.h
@@ -21,6 +21,7 @@
 
 #include <array>
 
+namespace compos_key {
 using PrivateKey = std::array<uint8_t, ED25519_PRIVATE_KEY_LEN>;
 using PublicKey = std::array<uint8_t, ED25519_PUBLIC_KEY_LEN>;
 using Signature = std::array<uint8_t, ED25519_SIGNATURE_LEN>;
@@ -33,10 +34,9 @@
 android::base::Result<Ed25519KeyPair> deriveKeyFromSecret(const uint8_t* secret,
                                                           size_t secret_size);
 
-android::base::Result<Ed25519KeyPair> deriveKeyFromDice();
-
 android::base::Result<Signature> sign(const PrivateKey& private_key, const uint8_t* data,
                                       size_t data_size);
 
 bool verify(const PublicKey& public_key, const Signature& signature, const uint8_t* data,
             size_t data_size);
+} // namespace compos_key
diff --git a/compos/compos_key_helper/compos_key_main.cpp b/compos/compos_key_helper/compos_key_main.cpp
index 70f7539..a0d0b18 100644
--- a/compos/compos_key_helper/compos_key_main.cpp
+++ b/compos/compos_key_helper/compos_key_main.cpp
@@ -14,39 +14,102 @@
  * limitations under the License.
  */
 
+#include <aidl/android/security/dice/IDiceNode.h>
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android/binder_auto_utils.h>
+#include <android/binder_manager.h>
 #include <unistd.h>
 
-#include <iostream>
 #include <string_view>
 
 #include "compos_key.h"
 
-using android::base::ErrnoError;
+using aidl::android::hardware::security::dice::BccHandover;
+using aidl::android::hardware::security::dice::InputValues;
+using aidl::android::security::dice::IDiceNode;
+using android::base::Error;
+using android::base::ReadFdToString;
+using android::base::Result;
 using android::base::WriteFully;
 using namespace std::literals;
+using compos_key::Ed25519KeyPair;
+
+namespace {
+Result<Ed25519KeyPair> deriveKeyFromDice() {
+    ndk::SpAIBinder binder{AServiceManager_getService("android.security.dice.IDiceNode")};
+    auto dice_node = IDiceNode::fromBinder(binder);
+    if (!dice_node) {
+        return Error() << "Unable to connect to IDiceNode";
+    }
+
+    const std::vector<InputValues> empty_input_values;
+    BccHandover bcc;
+    auto status = dice_node->derive(empty_input_values, &bcc);
+    if (!status.isOk()) {
+        return Error() << "Derive failed: " << status.getDescription();
+    }
+
+    // We use the sealing CDI because we want stability - the key needs to be the same
+    // for any instance of the "same" VM.
+    return compos_key::deriveKeyFromSecret(bcc.cdiSeal.data(), bcc.cdiSeal.size());
+}
+
+int write_public_key() {
+    auto key_pair = deriveKeyFromDice();
+    if (!key_pair.ok()) {
+        LOG(ERROR) << key_pair.error();
+        return 1;
+    }
+    if (!WriteFully(STDOUT_FILENO, key_pair->public_key.data(), key_pair->public_key.size())) {
+        PLOG(ERROR) << "Write failed";
+        return 1;
+    }
+    return 0;
+}
+
+int sign_input() {
+    std::string to_sign;
+    if (!ReadFdToString(STDIN_FILENO, &to_sign)) {
+        PLOG(ERROR) << "Read failed";
+        return 1;
+    }
+
+    auto key_pair = deriveKeyFromDice();
+    if (!key_pair.ok()) {
+        LOG(ERROR) << key_pair.error();
+        return 1;
+    }
+
+    auto signature =
+            compos_key::sign(key_pair->private_key,
+                             reinterpret_cast<const uint8_t*>(to_sign.data()), to_sign.size());
+    if (!signature.ok()) {
+        LOG(ERROR) << signature.error();
+        return 1;
+    }
+
+    if (!WriteFully(STDOUT_FILENO, signature->data(), signature->size())) {
+        PLOG(ERROR) << "Write failed";
+        return 1;
+    }
+    return 0;
+}
+} // namespace
 
 int main(int argc, char** argv) {
     android::base::InitLogging(argv, android::base::LogdLogger(android::base::SYSTEM));
 
     if (argc == 2) {
         if (argv[1] == "public_key"sv) {
-            auto key_pair = deriveKeyFromDice();
-            if (!key_pair.ok()) {
-                LOG(ERROR) << key_pair.error();
-                return 1;
-            }
-            if (!WriteFully(STDOUT_FILENO, key_pair->public_key.data(),
-                            key_pair->public_key.size())) {
-                PLOG(ERROR) << "Write failed";
-                return 1;
-            }
-            return 0;
+            return write_public_key();
+        } else if (argv[1] == "sign"sv) {
+            return sign_input();
         }
     }
 
-    std::cerr << "Usage:\n"
-                 "compos_key_helper public_key   Write current public key to stdout\n";
+    LOG(INFO) << "Usage: compos_key_helper <command>. Available commands are:\n"
+                 "public_key   Write current public key to stdout\n"
+                 "sign         Consume stdin, sign it and write signature to stdout\n";
     return 1;
 }
diff --git a/compos/compos_key_helper/compos_key_test.cpp b/compos/compos_key_helper/compos_key_test.cpp
index e5c4768..e4c3e8a 100644
--- a/compos/compos_key_helper/compos_key_test.cpp
+++ b/compos/compos_key_helper/compos_key_test.cpp
@@ -20,6 +20,8 @@
 
 #include "gtest/gtest.h"
 
+using namespace compos_key;
+
 const std::vector<uint8_t> secret = {1, 2, 3};
 const std::vector<uint8_t> other_secret = {3, 2, 3};
 const std::vector<uint8_t> data = {42, 180, 65, 0};
diff --git a/compos/composd/src/odrefresh_task.rs b/compos/composd/src/odrefresh_task.rs
index d1d0e28..9dec1c1 100644
--- a/compos/composd/src/odrefresh_task.rs
+++ b/compos/composd/src/odrefresh_task.rs
@@ -26,7 +26,7 @@
 use compos_aidl_interface::aidl::com::android::compos::ICompOsService::{
     CompilationMode::CompilationMode, ICompOsService,
 };
-use compos_common::odrefresh::ExitCode;
+use compos_common::odrefresh::{ExitCode, ODREFRESH_OUTPUT_ROOT_DIR};
 use log::{error, info, warn};
 use rustutils::system_properties;
 use std::fs::{remove_dir_all, File, OpenOptions};
@@ -36,8 +36,6 @@
 use std::sync::{Arc, Mutex};
 use std::thread;
 
-const ART_APEX_DATA: &str = "/data/misc/apexdata/com.android.art";
-
 #[derive(Clone)]
 pub struct OdrefreshTask {
     running_task: Arc<Mutex<Option<RunningTask>>>,
@@ -122,7 +120,7 @@
     compilation_mode: CompilationMode,
     target_dir_name: &str,
 ) -> Result<ExitCode> {
-    let output_root = Path::new(ART_APEX_DATA);
+    let output_root = Path::new(ODREFRESH_OUTPUT_ROOT_DIR);
 
     // We need to remove the target directory because odrefresh running in compos will create it
     // (and can't see the existing one, since authfs doesn't show it existing files in an output
diff --git a/compos/composd/src/service.rs b/compos/composd/src/service.rs
index f4121e7..8e5586e 100644
--- a/compos/composd/src/service.rs
+++ b/compos/composd/src/service.rs
@@ -30,6 +30,7 @@
 use anyhow::{Context, Result};
 use compos_aidl_interface::aidl::com::android::compos::ICompOsService::CompilationMode::CompilationMode;
 use compos_common::binder::to_binder_result;
+use compos_common::odrefresh::{PENDING_ARTIFACTS_SUBDIR, TEST_ARTIFACTS_SUBDIR};
 use rustutils::{users::AID_ROOT, users::AID_SYSTEM};
 use std::sync::Arc;
 
@@ -72,7 +73,7 @@
         // TODO: Try to start the current instance with staged APEXes to see if it works?
         let comp_os = self.instance_manager.start_pending_instance().context("Starting CompOS")?;
 
-        let target_dir_name = "compos-pending".to_owned();
+        let target_dir_name = PENDING_ARTIFACTS_SUBDIR.to_owned();
         let task = OdrefreshTask::start(
             comp_os,
             CompilationMode::NORMAL_COMPILE,
@@ -89,7 +90,7 @@
     ) -> Result<Strong<dyn ICompilationTask>> {
         let comp_os = self.instance_manager.start_test_instance().context("Starting CompOS")?;
 
-        let target_dir_name = "test-artifacts".to_owned();
+        let target_dir_name = TEST_ARTIFACTS_SUBDIR.to_owned();
         let task = OdrefreshTask::start(
             comp_os,
             CompilationMode::TEST_COMPILE,
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,
diff --git a/compos/tests/java/android/compos/test/ComposTestCase.java b/compos/tests/java/android/compos/test/ComposTestCase.java
index 1213ada..cfe72cb 100644
--- a/compos/tests/java/android/compos/test/ComposTestCase.java
+++ b/compos/tests/java/android/compos/test/ComposTestCase.java
@@ -38,8 +38,8 @@
     // Binaries used in test. (These paths are valid both in host and Microdroid.)
     private static final String ODREFRESH_BIN = "/apex/com.android.art/bin/odrefresh";
     private static final String COMPOSD_CMD_BIN = "/apex/com.android.compos/bin/composd_cmd";
-    private static final String COMPOS_VERIFY_KEY_BIN =
-            "/apex/com.android.compos/bin/compos_verify_key";
+    private static final String COMPOS_VERIFY_BIN =
+            "/apex/com.android.compos/bin/compos_verify";
 
     /** Output directory of odrefresh */
     private static final String TEST_ARTIFACTS_DIR = "test-artifacts";
@@ -153,8 +153,8 @@
         android.run("test -f " + ODREFRESH_OUTPUT_DIR + "/compos.info");
         android.run("test -f " + ODREFRESH_OUTPUT_DIR + "/compos.info.signature");
 
-        // Expect the CompOS public key & key blob to be valid
-        android.run(COMPOS_VERIFY_KEY_BIN + " --debug --instance test");
+        // Expect the CompOS signature to be valid
+        android.run(COMPOS_VERIFY_BIN + " --debug --instance test");
     }
 
     private CommandResult runOdrefresh(CommandRunner android, String command) throws Exception {
diff --git a/compos/verify_key/Android.bp b/compos/verify/Android.bp
similarity index 80%
rename from compos/verify_key/Android.bp
rename to compos/verify/Android.bp
index a5892b8..d6875d1 100644
--- a/compos/verify_key/Android.bp
+++ b/compos/verify/Android.bp
@@ -3,8 +3,8 @@
 }
 
 rust_binary {
-    name: "compos_verify_key",
-    srcs: ["verify_key.rs"],
+    name: "compos_verify",
+    srcs: ["verify.rs"],
     edition: "2018",
     rustlibs: [
         "compos_aidl_interface-rust",
@@ -13,6 +13,7 @@
         "libbinder_rs",
         "libclap",
         "libcompos_common",
+        "libcompos_verify_native_rust",
         "liblog_rust",
     ],
     prefer_rlib: true,
diff --git a/compos/verify/native/Android.bp b/compos/verify/native/Android.bp
new file mode 100644
index 0000000..969c9f4
--- /dev/null
+++ b/compos/verify/native/Android.bp
@@ -0,0 +1,51 @@
+package {
+    default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_library {
+    name: "libcompos_verify_native_rust",
+    crate_name: "compos_verify_native",
+    srcs: ["lib.rs"],
+    rustlibs: [
+        "libanyhow",
+        "libcxx",
+        "liblibc",
+    ],
+    static_libs: [
+        "libcompos_verify_native_cpp",
+        "libcompos_key",
+    ],
+    shared_libs: [
+        "libcrypto",
+    ],
+    apex_available: ["com.android.compos"],
+}
+
+cc_library_static {
+    name: "libcompos_verify_native_cpp",
+    srcs: ["verify_native.cpp"],
+    static_libs: ["libcompos_key"],
+    shared_libs: [
+        "libbase",
+        "libcrypto",
+    ],
+    generated_headers: ["compos_verify_native_header"],
+    generated_sources: ["compos_verify_native_code"],
+    apex_available: ["com.android.compos"],
+}
+
+genrule {
+    name: "compos_verify_native_code",
+    tools: ["cxxbridge"],
+    cmd: "$(location cxxbridge) $(in) >> $(out)",
+    srcs: ["lib.rs"],
+    out: ["verify_native_cxx_generated.cc"],
+}
+
+genrule {
+    name: "compos_verify_native_header",
+    tools: ["cxxbridge"],
+    cmd: "$(location cxxbridge) $(in) --header >> $(out)",
+    srcs: ["lib.rs"],
+    out: ["lib.rs.h"],
+}
diff --git a/compos/verify/native/lib.rs b/compos/verify/native/lib.rs
new file mode 100644
index 0000000..51050da
--- /dev/null
+++ b/compos/verify/native/lib.rs
@@ -0,0 +1,31 @@
+// 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.
+
+//! Native helper for compos_verify to call boringssl.
+
+pub use native::*;
+
+#[cxx::bridge]
+mod native {
+    unsafe extern "C++" {
+        include!("verify_native.h");
+
+        // SAFETY: The C++ implementation manages its own memory, and does not retain or abuse
+        // the references passed to it.
+
+        /// Verify a PureEd25519 signature with the specified public key on the given data,
+        /// returning whether the signature is valid or not.
+        fn verify(public_key: &[u8], signature: &[u8], data: &[u8]) -> bool;
+    }
+}
diff --git a/compos/verify/native/verify_native.cpp b/compos/verify/native/verify_native.cpp
new file mode 100644
index 0000000..2c43d95
--- /dev/null
+++ b/compos/verify/native/verify_native.cpp
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+#include "verify_native.h"
+
+#include <compos_key.h>
+
+using rust::Slice;
+
+bool verify(Slice<const uint8_t> public_key, Slice<const uint8_t> signature,
+            Slice<const uint8_t> data) {
+    compos_key::PublicKey public_key_array;
+    compos_key::Signature signature_array;
+
+    if (public_key.size() != public_key_array.size() ||
+        signature.size() != signature_array.size()) {
+        return false;
+    }
+
+    std::copy(public_key.begin(), public_key.end(), public_key_array.begin());
+    std::copy(signature.begin(), signature.end(), signature_array.begin());
+
+    return compos_key::verify(public_key_array, signature_array, data.data(), data.size());
+}
diff --git a/compos/verify/native/verify_native.h b/compos/verify/native/verify_native.h
new file mode 100644
index 0000000..5f000b6
--- /dev/null
+++ b/compos/verify/native/verify_native.h
@@ -0,0 +1,22 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#include "lib.rs.h"
+
+bool verify(rust::Slice<const uint8_t> public_key, rust::Slice<const uint8_t> signature,
+            rust::Slice<const uint8_t> data);
diff --git a/compos/verify/verify.rs b/compos/verify/verify.rs
new file mode 100644
index 0000000..228225d
--- /dev/null
+++ b/compos/verify/verify.rs
@@ -0,0 +1,126 @@
+/*
+ * 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 verify a CompOS signature. It starts a CompOS VM as part of this to retrieve the
+//!  public key. The tool is intended to be run by odsign during boot.
+
+use anyhow::{bail, Context, Result};
+use compos_aidl_interface::binder::ProcessState;
+use compos_common::compos_client::{VmInstance, VmParameters};
+use compos_common::odrefresh::{
+    CURRENT_ARTIFACTS_SUBDIR, ODREFRESH_OUTPUT_ROOT_DIR, PENDING_ARTIFACTS_SUBDIR,
+    TEST_ARTIFACTS_SUBDIR,
+};
+use compos_common::{
+    COMPOS_DATA_ROOT, IDSIG_FILE, IDSIG_MANIFEST_APK_FILE, INSTANCE_IMAGE_FILE,
+    PENDING_INSTANCE_DIR, TEST_INSTANCE_DIR,
+};
+use log::error;
+use std::fs::File;
+use std::io::Read;
+use std::panic;
+use std::path::Path;
+
+const MAX_FILE_SIZE_BYTES: u64 = 100 * 1024;
+
+fn main() {
+    android_logger::init_once(
+        android_logger::Config::default()
+            .with_tag("compos_verify")
+            .with_min_level(log::Level::Info),
+    );
+
+    // Redirect panic messages to logcat.
+    panic::set_hook(Box::new(|panic_info| {
+        error!("{}", panic_info);
+    }));
+
+    if let Err(e) = try_main() {
+        error!("{:?}", e);
+        std::process::exit(1)
+    }
+}
+
+fn try_main() -> Result<()> {
+    let matches = clap::App::new("compos_verify")
+        .arg(
+            clap::Arg::with_name("instance")
+                .long("instance")
+                .takes_value(true)
+                .required(true)
+                .possible_values(&["pending", "current", "test"]),
+        )
+        .arg(clap::Arg::with_name("debug").long("debug"))
+        .get_matches();
+
+    let debug_mode = matches.is_present("debug");
+    let (instance_dir, artifacts_dir) = match matches.value_of("instance").unwrap() {
+        "pending" => (PENDING_INSTANCE_DIR, PENDING_ARTIFACTS_SUBDIR),
+        "current" => (PENDING_INSTANCE_DIR, CURRENT_ARTIFACTS_SUBDIR),
+        "test" => (TEST_INSTANCE_DIR, TEST_ARTIFACTS_SUBDIR),
+        _ => unreachable!("Unexpected instance name"),
+    };
+
+    let instance_dir = Path::new(COMPOS_DATA_ROOT).join(instance_dir);
+    let artifacts_dir = Path::new(ODREFRESH_OUTPUT_ROOT_DIR).join(artifacts_dir);
+
+    if !instance_dir.is_dir() {
+        bail!("{:?} is not a directory", instance_dir);
+    }
+
+    let instance_image = instance_dir.join(INSTANCE_IMAGE_FILE);
+    let idsig = instance_dir.join(IDSIG_FILE);
+    let idsig_manifest_apk = instance_dir.join(IDSIG_MANIFEST_APK_FILE);
+
+    let instance_image = File::open(instance_image).context("Failed to open instance image")?;
+
+    let info = artifacts_dir.join("compos.info");
+    let signature = artifacts_dir.join("compos.info.signature");
+
+    let info = read_small_file(&info)?;
+    let signature = read_small_file(&signature)?;
+
+    // We need to start the thread pool to be able to receive Binder callbacks
+    ProcessState::start_thread_pool();
+
+    let virtualization_service = VmInstance::connect_to_virtualization_service()?;
+    let vm_instance = VmInstance::start(
+        &*virtualization_service,
+        instance_image,
+        &idsig,
+        &idsig_manifest_apk,
+        &VmParameters { debug_mode, ..Default::default() },
+    )?;
+    let service = vm_instance.get_service()?;
+
+    let public_key = service.getPublicKey().context("Getting public key")?;
+
+    if !compos_verify_native::verify(&public_key, &signature, &info) {
+        bail!("Signature verification failed");
+    }
+
+    Ok(())
+}
+
+fn read_small_file(file: &Path) -> Result<Vec<u8>> {
+    let mut file = File::open(file)?;
+    if file.metadata()?.len() > MAX_FILE_SIZE_BYTES {
+        bail!("File is too big");
+    }
+    let mut data = Vec::new();
+    file.read_to_end(&mut data)?;
+    Ok(data)
+}
diff --git a/compos/verify_key/verify_key.rs b/compos/verify_key/verify_key.rs
deleted file mode 100644
index 9454442..0000000
--- a/compos/verify_key/verify_key.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * 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 verify whether a CompOS instance image and key pair are valid. It starts a CompOS VM
-//! as part of this. The tool is intended to be run by odsign during boot.
-
-use anyhow::{bail, Context, Result};
-use compos_aidl_interface::binder::ProcessState;
-use compos_common::compos_client::{VmInstance, VmParameters};
-use compos_common::{
-    COMPOS_DATA_ROOT, CURRENT_INSTANCE_DIR, IDSIG_FILE, IDSIG_MANIFEST_APK_FILE,
-    INSTANCE_IMAGE_FILE, PENDING_INSTANCE_DIR, PRIVATE_KEY_BLOB_FILE, PUBLIC_KEY_FILE,
-    TEST_INSTANCE_DIR,
-};
-use std::fs::{self, File};
-use std::io::Read;
-use std::panic;
-use std::path::{Path, PathBuf};
-
-const MAX_FILE_SIZE_BYTES: u64 = 8 * 1024;
-
-fn main() {
-    android_logger::init_once(
-        android_logger::Config::default()
-            .with_tag("compos_verify_key")
-            .with_min_level(log::Level::Info),
-    );
-
-    // Redirect panic messages to logcat.
-    panic::set_hook(Box::new(|panic_info| {
-        log::error!("{}", panic_info);
-    }));
-
-    if let Err(e) = try_main() {
-        log::error!("{:?}", e);
-        std::process::exit(-1)
-    }
-}
-
-fn try_main() -> Result<()> {
-    let matches = clap::App::new("compos_verify_key")
-        .arg(
-            clap::Arg::with_name("instance")
-                .long("instance")
-                .takes_value(true)
-                .required(true)
-                .possible_values(&["pending", "current", "test"]),
-        )
-        .arg(clap::Arg::with_name("debug").long("debug"))
-        .get_matches();
-
-    let debug_mode = matches.is_present("debug");
-    let (promote_if_valid, instance_dir) = match matches.value_of("instance").unwrap() {
-        "pending" => (true, PENDING_INSTANCE_DIR),
-        "current" => (false, CURRENT_INSTANCE_DIR),
-        "test" => (false, TEST_INSTANCE_DIR),
-        _ => unreachable!("Unexpected instance name"),
-    };
-
-    let instance_dir: PathBuf = [COMPOS_DATA_ROOT, instance_dir].iter().collect();
-
-    if !instance_dir.is_dir() {
-        bail!("{:?} is not a directory", instance_dir);
-    }
-
-    // We need to start the thread pool to be able to receive Binder callbacks
-    ProcessState::start_thread_pool();
-
-    let result = verify(debug_mode, &instance_dir).and_then(|_| {
-        log::info!("Verified {:?}", instance_dir);
-        if promote_if_valid {
-            // If the instance is ok, then it must actually match the current system state,
-            // so we promote it to current.
-            log::info!("Promoting to current");
-            promote_to_current(&instance_dir)
-        } else {
-            Ok(())
-        }
-    });
-
-    if result.is_err() {
-        // This is best efforts, and we still want to report the original error as our result
-        log::info!("Removing {:?}", instance_dir);
-        if let Err(e) = fs::remove_dir_all(&instance_dir) {
-            log::warn!("Failed to remove directory: {}", e);
-        }
-    }
-
-    result
-}
-
-fn verify(debug_mode: bool, instance_dir: &Path) -> Result<()> {
-    let blob = instance_dir.join(PRIVATE_KEY_BLOB_FILE);
-    let public_key = instance_dir.join(PUBLIC_KEY_FILE);
-    let instance_image = instance_dir.join(INSTANCE_IMAGE_FILE);
-    let idsig = instance_dir.join(IDSIG_FILE);
-    let idsig_manifest_apk = instance_dir.join(IDSIG_MANIFEST_APK_FILE);
-
-    let blob = read_small_file(blob).context("Failed to read key blob")?;
-    let public_key = read_small_file(public_key).context("Failed to read public key")?;
-    let instance_image = File::open(instance_image).context("Failed to open instance image")?;
-
-    let virtualization_service = VmInstance::connect_to_virtualization_service()?;
-    let vm_instance = VmInstance::start(
-        &*virtualization_service,
-        instance_image,
-        &idsig,
-        &idsig_manifest_apk,
-        &VmParameters { debug_mode, ..Default::default() },
-    )?;
-    let service = vm_instance.get_service()?;
-
-    let result = service.verifySigningKey(&blob, &public_key).context("Verifying signing key")?;
-
-    if !result {
-        bail!("Key files are not valid");
-    }
-
-    Ok(())
-}
-
-fn promote_to_current(instance_dir: &Path) -> Result<()> {
-    let current_dir: PathBuf = [COMPOS_DATA_ROOT, CURRENT_INSTANCE_DIR].iter().collect();
-
-    // This may fail if the directory doesn't exist - which is fine, we only care about the rename
-    // succeeding.
-    let _ = fs::remove_dir_all(&current_dir);
-
-    fs::rename(&instance_dir, &current_dir).context("Unable to promote instance to current")?;
-    Ok(())
-}
-
-fn read_small_file(file: PathBuf) -> Result<Vec<u8>> {
-    let mut file = File::open(file)?;
-    if file.metadata()?.len() > MAX_FILE_SIZE_BYTES {
-        bail!("File is too big");
-    }
-    let mut data = vec![];
-    file.read_to_end(&mut data)?;
-    Ok(data)
-}