Revert "Revert "[rkp] Expose RKP Hal implementation in virtualiz..."

Revert submission 2812435-revert-2778549-expose-avf-rkp-hal-GTFGLMUUKQ

Reason for revert: This change relands the topic
https://r.android.com/q/topic:%22expose-avf-rkp-hal%22
This SELinux denial has been fixed in system/sepolicy

Reverted changes: /q/submissionid:2812435-revert-2778549-expose-avf-rkp-hal-GTFGLMUUKQ

Change-Id: I87b2df911bd6e39b717497e730a1b56156b692f1
diff --git a/apex/Android.bp b/apex/Android.bp
index a05f7b0..7983181 100644
--- a/apex/Android.bp
+++ b/apex/Android.bp
@@ -60,7 +60,20 @@
     ],
 }
 
-apex_defaults {
+soong_config_module_type {
+    name: "flag_aware_apex_defaults",
+    module_type: "apex_defaults",
+    config_namespace: "ANDROID",
+    bool_variables: [
+        "release_avf_enable_remote_attestation",
+    ],
+    properties: [
+        "prebuilts",
+        "vintf_fragments",
+    ],
+}
+
+flag_aware_apex_defaults {
     name: "com.android.virt_avf_enabled",
 
     defaults: ["com.android.virt_common"],
@@ -92,8 +105,19 @@
         "fd_server",
         "vm",
     ],
+    soong_config_variables: {
+        release_avf_enable_remote_attestation: {
+            prebuilts: ["com.android.virt.init_attestation_enabled.rc"],
+            vintf_fragments: [
+                "virtualizationservice.xml",
+            ],
+            conditions_default: {
+                prebuilts: ["com.android.virt.init.rc"],
+            },
+        },
+    },
     prebuilts: [
-        "com.android.virt.init.rc",
+        "com.android.virt.vfio_handler.rc",
         "features_com.android.virt.xml",
         "microdroid_initrd_debuggable",
         "microdroid_initrd_normal",
@@ -128,9 +152,23 @@
 }
 
 prebuilt_etc {
+    name: "com.android.virt.vfio_handler.rc",
+    src: "vfio_handler.rc",
+    filename: "vfio_handler.rc",
+    installable: false,
+}
+
+prebuilt_etc {
     name: "com.android.virt.init.rc",
     src: "virtualizationservice.rc",
-    filename: "init.rc",
+    filename: "virtualizationservice.rc",
+    installable: false,
+}
+
+prebuilt_etc {
+    name: "com.android.virt.init_attestation_enabled.rc",
+    src: "virtualizationservice_attestation_enabled.rc",
+    filename: "virtualizationservice.rc",
     installable: false,
 }
 
diff --git a/apex/vfio_handler.rc b/apex/vfio_handler.rc
new file mode 100644
index 0000000..419acef
--- /dev/null
+++ b/apex/vfio_handler.rc
@@ -0,0 +1,20 @@
+# Copyright (C) 2023 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.
+
+service vfio_handler /apex/com.android.virt/bin/vfio_handler
+    user root
+    group system
+    interface aidl android.system.virtualizationservice_internal.IVfioHandler
+    disabled
+    oneshot
diff --git a/apex/virtualizationservice.rc b/apex/virtualizationservice.rc
index 8283594..02b2081 100644
--- a/apex/virtualizationservice.rc
+++ b/apex/virtualizationservice.rc
@@ -19,10 +19,3 @@
     interface aidl android.system.virtualizationservice
     disabled
     oneshot
-
-service vfio_handler /apex/com.android.virt/bin/vfio_handler
-    user root
-    group system
-    interface aidl android.system.virtualizationservice_internal.IVfioHandler
-    disabled
-    oneshot
diff --git a/apex/virtualizationservice.xml b/apex/virtualizationservice.xml
index 0ce1e10..60f466f 100644
--- a/apex/virtualizationservice.xml
+++ b/apex/virtualizationservice.xml
@@ -1,6 +1,6 @@
 <manifest version="1.0" type="framework">
     <hal format="aidl">
-        <name>android.system.virtualization</name>
+        <name>android.hardware.security.keymint</name>
         <version>3</version>
         <fqname>IRemotelyProvisionedComponent/avf</fqname>
     </hal>
diff --git a/apex/virtualizationservice_attestation_enabled.rc b/apex/virtualizationservice_attestation_enabled.rc
new file mode 100644
index 0000000..8eaccae
--- /dev/null
+++ b/apex/virtualizationservice_attestation_enabled.rc
@@ -0,0 +1,22 @@
+# 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.
+
+service virtualizationservice /apex/com.android.virt/bin/virtualizationservice
+    class main
+    user system
+    group system
+    interface aidl android.system.virtualizationservice
+    interface aidl android.hardware.security.keymint.IRemotelyProvisionedComponent/avf
+    disabled
+    oneshot
diff --git a/service_vm/requests/src/rkp.rs b/service_vm/requests/src/rkp.rs
index 8d7d771..f5b9203 100644
--- a/service_vm/requests/src/rkp.rs
+++ b/service_vm/requests/src/rkp.rs
@@ -75,10 +75,13 @@
         public_keys.push(public_key.to_cbor_value()?);
     }
     // Builds `CsrPayload`.
+    // TODO(b/299256925): The device information is currently empty as we do not
+    // have sufficient details to include.
+    let device_info = Value::Map(Vec::new());
     let csr_payload = cbor!([
         Value::Integer(CSR_PAYLOAD_SCHEMA_V3.into()),
         Value::Text(String::from(CERTIFICATE_TYPE)),
-        // TODO(b/299256925): Add device info in CBOR format here.
+        device_info,
         Value::Array(public_keys),
     ])?;
     let csr_payload = cbor_util::serialize(&csr_payload)?;
diff --git a/virtualizationservice/Android.bp b/virtualizationservice/Android.bp
index c00445d..7bdab0a 100644
--- a/virtualizationservice/Android.bp
+++ b/virtualizationservice/Android.bp
@@ -31,6 +31,7 @@
         "libanyhow",
         "libavflog",
         "libbinder_rs",
+        "libhypervisor_props",
         "liblibc",
         "liblog_rust",
         "libnix",
diff --git a/virtualizationservice/src/main.rs b/virtualizationservice/src/main.rs
index fd668bc..c2e55eb 100644
--- a/virtualizationservice/src/main.rs
+++ b/virtualizationservice/src/main.rs
@@ -33,8 +33,8 @@
 use std::path::Path;
 
 const LOG_TAG: &str = "VirtualizationService";
-const _REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME: &str =
-    "android.system.virtualization.IRemotelyProvisionedComponent/avf";
+const REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME: &str =
+    "android.hardware.security.keymint.IRemotelyProvisionedComponent/avf";
 
 fn get_calling_pid() -> pid_t {
     ThreadState::get_calling_pid()
@@ -69,10 +69,17 @@
     register_lazy_service(BINDER_SERVICE_IDENTIFIER, service.as_binder()).unwrap();
     info!("Registered Binder service {}.", BINDER_SERVICE_IDENTIFIER);
 
-    // The IRemotelyProvisionedComponent service is only supposed to be triggered by rkpd for
-    // RKP VM attestation.
-    let _remote_provisioning_service = remote_provisioning::new_binder();
-    // TODO(b/274881098): Register the RKP service when the implementation is ready.
+    if cfg!(remote_attestation) {
+        // The IRemotelyProvisionedComponent service is only supposed to be triggered by rkpd for
+        // RKP VM attestation.
+        let remote_provisioning_service = remote_provisioning::new_binder();
+        register_lazy_service(
+            REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME,
+            remote_provisioning_service.as_binder(),
+        )
+        .unwrap();
+        info!("Registered Binder service {}.", REMOTELY_PROVISIONED_COMPONENT_SERVICE_NAME);
+    }
 
     ProcessState::join_thread_pool();
 }
diff --git a/virtualizationservice/src/remote_provisioning.rs b/virtualizationservice/src/remote_provisioning.rs
index a9a07a5..40f54db 100644
--- a/virtualizationservice/src/remote_provisioning.rs
+++ b/virtualizationservice/src/remote_provisioning.rs
@@ -27,7 +27,11 @@
 };
 use anyhow::Context;
 use avflog::LogResult;
-use binder::{BinderFeatures, Interface, IntoBinderResult, Result as BinderResult, Status, Strong};
+use binder::{
+    BinderFeatures, ExceptionCode, Interface, IntoBinderResult, Result as BinderResult, Status,
+    Strong,
+};
+use hypervisor_props::is_protected_vm_supported;
 use service_vm_comm::{RequestProcessingError, Response};
 
 /// Constructs a binder object that implements `IRemotelyProvisionedComponent`.
@@ -45,11 +49,13 @@
 #[allow(non_snake_case)]
 impl IRemotelyProvisionedComponent for AvfRemotelyProvisionedComponent {
     fn getHardwareInfo(&self) -> BinderResult<RpcHardwareInfo> {
+        check_protected_vm_is_supported()?;
+
         Ok(RpcHardwareInfo {
             versionNumber: 3,
             rpcAuthorName: String::from("Android Virtualization Framework"),
             supportedEekCurve: CURVE_NONE,
-            uniqueId: Some(String::from("Android Virtualization Framework 1")),
+            uniqueId: Some(String::from("AVF Remote Provisioning 1")),
             supportedNumKeysInCsr: MIN_SUPPORTED_NUM_KEYS_IN_CSR,
         })
     }
@@ -59,6 +65,8 @@
         testMode: bool,
         macedPublicKey: &mut MacedPublicKey,
     ) -> BinderResult<Vec<u8>> {
+        check_protected_vm_is_supported()?;
+
         if testMode {
             return Err(Status::new_service_specific_error_str(
                 STATUS_REMOVED,
@@ -101,6 +109,8 @@
         keysToSign: &[MacedPublicKey],
         challenge: &[u8],
     ) -> BinderResult<Vec<u8>> {
+        check_protected_vm_is_supported()?;
+
         const MAX_CHALLENGE_SIZE: usize = 64;
         if challenge.len() > MAX_CHALLENGE_SIZE {
             let message = format!(
@@ -123,6 +133,18 @@
     }
 }
 
+fn check_protected_vm_is_supported() -> BinderResult<()> {
+    if is_protected_vm_supported().unwrap_or(false) {
+        Ok(())
+    } else {
+        Err(Status::new_exception_str(
+            ExceptionCode::UNSUPPORTED_OPERATION,
+            Some("Protected VM support is missing for this operation"),
+        ))
+        .with_log()
+    }
+}
+
 fn to_service_specific_error(response: Response) -> Status {
     match response {
         Response::Err(e) => match e {