Get CompOS talking to diced

Create a module in compsvc to handle using DICE for signing. Initially
we just expose a method for returning our key's attestation
chain.

Add a method to composd, accessed via compos_cmd, to exercise this
functionality for testing purposes.

Bug: 214233409
Test: composd_cmd dice
Change-Id: I65ef19d0126862b800b6539ae1798b1a433085b8
diff --git a/compos/Android.bp b/compos/Android.bp
index ab55efb..18fd28f 100644
--- a/compos/Android.bp
+++ b/compos/Android.bp
@@ -6,7 +6,9 @@
     name: "compsvc",
     srcs: ["src/compsvc_main.rs"],
     rustlibs: [
+        "android.hardware.security.dice-V1-rust",
         "android.hardware.security.keymint-V1-rust",
+        "android.security.dice-rust",
         "android.system.keystore2-V1-rust",
         "android.system.virtualmachineservice-rust",
         "authfs_aidl_interface-rust",
diff --git a/compos/aidl/com/android/compos/ICompOsService.aidl b/compos/aidl/com/android/compos/ICompOsService.aidl
index e3e0317..b68cdee 100644
--- a/compos/aidl/com/android/compos/ICompOsService.aidl
+++ b/compos/aidl/com/android/compos/ICompOsService.aidl
@@ -96,4 +96,9 @@
      * @return whether the inputs are valid and correspond to each other.
      */
     boolean verifySigningKey(in byte[] keyBlob, in byte[] publicKey);
+
+    /**
+     * Returns the DICE BCC for this instance of CompOS, allowing signatures to be verified.
+     */
+    byte[] getBootCertificateChain();
 }
diff --git a/compos/composd/aidl/android/system/composd/IIsolatedCompilationService.aidl b/compos/composd/aidl/android/system/composd/IIsolatedCompilationService.aidl
index 8156265..0b5eec1 100644
--- a/compos/composd/aidl/android/system/composd/IIsolatedCompilationService.aidl
+++ b/compos/composd/aidl/android/system/composd/IIsolatedCompilationService.aidl
@@ -42,4 +42,10 @@
      * a reference to the ICompilationTask until compilation completes or is cancelled.
      */
     ICompilationTask startTestCompile(ICompilationTaskCallback callback);
+
+    /**
+     * For testing.
+     * TODO(b/214233409): Remove
+     */
+    byte[] getBcc();
 }
diff --git a/compos/composd/src/service.rs b/compos/composd/src/service.rs
index 6cdcd85..cb52037 100644
--- a/compos/composd/src/service.rs
+++ b/compos/composd/src/service.rs
@@ -61,6 +61,12 @@
         check_permissions()?;
         to_binder_result(self.do_start_test_compile(callback))
     }
+
+    // TODO(b/214233409): Remove
+    fn getBcc(&self) -> binder::Result<Vec<u8>> {
+        check_permissions()?;
+        to_binder_result(self.do_get_bcc())
+    }
 }
 
 impl IsolatedCompilationService {
@@ -88,6 +94,11 @@
 
         Ok(BnCompilationTask::new_binder(task, BinderFeatures::default()))
     }
+
+    fn do_get_bcc(&self) -> Result<Vec<u8>> {
+        let comp_os = self.instance_manager.start_test_instance().context("Starting CompOS")?;
+        comp_os.get_service().getBootCertificateChain().context("getBcc")
+    }
 }
 
 fn check_permissions() -> binder::Result<()> {
diff --git a/compos/composd_cmd/composd_cmd.rs b/compos/composd_cmd/composd_cmd.rs
index 546c4af..9b41104 100644
--- a/compos/composd_cmd/composd_cmd.rs
+++ b/compos/composd_cmd/composd_cmd.rs
@@ -29,6 +29,8 @@
 };
 use anyhow::{bail, Context, Result};
 use compos_common::timeouts::timeouts;
+use std::fs::File;
+use std::io::Write;
 use std::sync::{Arc, Condvar, Mutex};
 use std::time::Duration;
 
@@ -38,7 +40,7 @@
             .index(1)
             .takes_value(true)
             .required(true)
-            .possible_values(&["staged-apex-compile", "test-compile"]),
+            .possible_values(&["staged-apex-compile", "test-compile", "dice"]),
     );
     let args = app.get_matches();
     let command = args.value_of("command").unwrap();
@@ -48,6 +50,7 @@
     match command {
         "staged-apex-compile" => run_staged_apex_compile()?,
         "test-compile" => run_test_compile()?,
+        "dice" => write_dice()?,
         _ => panic!("Unexpected command {}", command),
     }
 
@@ -112,6 +115,16 @@
     run_async_compilation(|service, callback| service.startTestCompile(callback))
 }
 
+fn write_dice() -> Result<()> {
+    let service = wait_for_interface::<dyn IIsolatedCompilationService>("android.system.composd")
+        .context("Failed to connect to composd service")?;
+
+    let bcc = service.getBcc()?;
+    let mut file =
+        File::create("/data/misc/apexdata/com.android.compos/bcc").context("Creating bcc file")?;
+    file.write_all(&bcc).context("Writing bcc")
+}
+
 fn run_async_compilation<F>(start_compile_fn: F) -> Result<()>
 where
     F: FnOnce(
diff --git a/compos/src/compsvc.rs b/compos/src/compsvc.rs
index 5a2c3ca..28bf5d9 100644
--- a/compos/src/compsvc.rs
+++ b/compos/src/compsvc.rs
@@ -28,6 +28,7 @@
 
 use crate::compilation::{compile_cmd, odrefresh, CompilerOutput, OdrefreshContext};
 use crate::compos_key_service::{CompOsKeyService, Signer};
+use crate::dice::Dice;
 use crate::fsverity;
 use authfs_aidl_interface::aidl::com::android::virt::fs::IAuthFsService::IAuthFsService;
 use compos_aidl_interface::aidl::com::android::compos::{
@@ -79,6 +80,11 @@
             Ok(self.key_service.new_signer(key))
         }
     }
+
+    fn get_boot_certificate_chain(&self) -> Result<Vec<u8>> {
+        let dice = Dice::new()?;
+        dice.get_boot_certificate_chain()
+    }
 }
 
 impl Interface for CompOsService {}
@@ -164,6 +170,10 @@
             true
         })
     }
+
+    fn getBootCertificateChain(&self) -> BinderResult<Vec<u8>> {
+        to_binder_result(self.get_boot_certificate_chain())
+    }
 }
 
 fn get_authfs_service() -> BinderResult<Strong<dyn IAuthFsService>> {
diff --git a/compos/src/compsvc_main.rs b/compos/src/compsvc_main.rs
index 9347905..b4e3128 100644
--- a/compos/src/compsvc_main.rs
+++ b/compos/src/compsvc_main.rs
@@ -20,6 +20,7 @@
 mod compilation;
 mod compos_key_service;
 mod compsvc;
+mod dice;
 mod fsverity;
 
 use android_system_virtualmachineservice::{
diff --git a/compos/src/dice.rs b/compos/src/dice.rs
new file mode 100644
index 0000000..22a7ee2
--- /dev/null
+++ b/compos/src/dice.rs
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+//! Handles the use of DICE as the source of our unique signing key via diced / IDiceNode.
+
+use android_security_dice::aidl::android::security::dice::IDiceNode::IDiceNode;
+use android_security_dice::binder::{wait_for_interface, Strong};
+use anyhow::{Context, Result};
+
+pub struct Dice {
+    node: Strong<dyn IDiceNode>,
+}
+
+impl Dice {
+    pub fn new() -> Result<Self> {
+        let dice_service = wait_for_interface::<dyn IDiceNode>("android.security.dice.IDiceNode")
+            .context("No IDiceNode service")?;
+        Ok(Self { node: dice_service })
+    }
+
+    pub fn get_boot_certificate_chain(&self) -> Result<Vec<u8>> {
+        let input_values = []; // Get our BCC, not a child's
+        let bcc = self
+            .node
+            .getAttestationChain(&input_values)
+            .context("Getting attestation chain failed")?;
+        Ok(bcc.data)
+    }
+}