Merge "Delete unused IProvisionerService interface"
diff --git a/identity/CredentialData.cpp b/identity/CredentialData.cpp
index 1bf1527..803e671 100644
--- a/identity/CredentialData.cpp
+++ b/identity/CredentialData.cpp
@@ -520,8 +520,12 @@
                                           bool allowUsingExpiredKeys) {
     AuthKeyData* candidate = nullptr;
 
-    int64_t nowMilliSeconds =
-        std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()) * 1000;
+    time_t now = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
+    int64_t nowMilliSeconds;
+    if (__builtin_mul_overflow(int64_t(now), int64_t(1000), &nowMilliSeconds)) {
+        LOG(ERROR) << "Overflow converting " << now << " to milliseconds";
+        return nullptr;
+    }
 
     int n = 0;
     for (AuthKeyData& data : authKeyDatas_) {
diff --git a/keystore2/Android.bp b/keystore2/Android.bp
index 4084ace..a47c2c2 100644
--- a/keystore2/Android.bp
+++ b/keystore2/Android.bp
@@ -31,6 +31,7 @@
     ],
 
     rustlibs: [
+        "android.hardware.security.rkp-V3-rust",
         "android.hardware.security.secureclock-V1-rust",
         "android.hardware.security.sharedsecret-V1-rust",
         "android.os.permissions_aidl-rust",
@@ -47,7 +48,7 @@
         "libkeystore2_crypto_rust",
         "libkeystore2_km_compat",
         "libkeystore2_selinux",
-        "libkeystore2_vintf_rust",
+        "libkeystore2_hal_names_rust",
         "liblazy_static",
         "liblibc",
         "liblog_event_list",
diff --git a/keystore2/src/fuzzers/Android.bp b/keystore2/src/fuzzers/Android.bp
index 4ac83e3..9f3e104 100644
--- a/keystore2/src/fuzzers/Android.bp
+++ b/keystore2/src/fuzzers/Android.bp
@@ -23,7 +23,7 @@
         "libbinder_rs",
         "libkeystore2",
         "libkeystore2_crypto_rust",
-        "libkeystore2_vintf_rust",
+        "libkeystore2_hal_names_rust",
         "libkeystore2_aaid-rust",
         "libkeystore2_apc_compat-rust",
         "libkeystore2_selinux",
@@ -46,7 +46,7 @@
     rustlibs: [
         "libkeystore2",
         "libkeystore2_crypto_rust",
-        "libkeystore2_vintf_rust",
+        "libkeystore2_hal_names_rust",
         "libkeystore2_aaid-rust",
         "libkeystore2_apc_compat-rust",
         "libkeystore2_selinux",
diff --git a/keystore2/src/fuzzers/keystore2_unsafe_fuzzer.rs b/keystore2/src/fuzzers/keystore2_unsafe_fuzzer.rs
index 0dca3a2..b8259cf 100644
--- a/keystore2/src/fuzzers/keystore2_unsafe_fuzzer.rs
+++ b/keystore2/src/fuzzers/keystore2_unsafe_fuzzer.rs
@@ -26,8 +26,8 @@
     ec_point_point_to_oct, ecdh_compute_key, generate_random_data, hkdf_expand, hkdf_extract,
     hmac_sha256, parse_subject_from_certificate, Password, ZVec,
 };
+use keystore2_hal_names::get_hidl_instances;
 use keystore2_selinux::{check_access, getpidcon, setcon, Backend, Context, KeystoreKeyBackend};
-use keystore2_vintf::get_hidl_instances;
 use libfuzzer_sys::{arbitrary::Arbitrary, fuzz_target};
 use std::{ffi::CString, sync::Arc};
 
diff --git a/keystore2/src/globals.rs b/keystore2/src/globals.rs
index 10d6f46..0f899ed 100644
--- a/keystore2/src/globals.rs
+++ b/keystore2/src/globals.rs
@@ -16,8 +16,9 @@
 //! database connections and connections to services that Keystore needs
 //! to talk to.
 
-use crate::ks_err;
 use crate::gc::Gc;
+use crate::km_compat::{BacklevelKeyMintWrapper, KeyMintV1};
+use crate::ks_err;
 use crate::legacy_blob::LegacyBlobLoader;
 use crate::legacy_importer::LegacyImporter;
 use crate::super_key::SuperKeyManager;
@@ -28,20 +29,23 @@
     database::Uuid,
     error::{map_binder_status, map_binder_status_code, Error, ErrorCode},
 };
-use crate::km_compat::{KeyMintV1, BacklevelKeyMintWrapper};
 use crate::{enforcements::Enforcements, error::map_km_error};
 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
     IKeyMintDevice::BpKeyMintDevice, IKeyMintDevice::IKeyMintDevice,
     KeyMintHardwareInfo::KeyMintHardwareInfo, SecurityLevel::SecurityLevel,
 };
-use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
-    ISecureClock::ISecureClock,
-};
 use android_hardware_security_keymint::binder::{StatusCode, Strong};
+use android_hardware_security_rkp::aidl::android::hardware::security::keymint::{
+    IRemotelyProvisionedComponent::BpRemotelyProvisionedComponent,
+    IRemotelyProvisionedComponent::IRemotelyProvisionedComponent,
+};
+use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
+    ISecureClock::BpSecureClock, ISecureClock::ISecureClock,
+};
 use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
 use anyhow::{Context, Result};
-use binder::FromIBinder;
 use binder::get_declared_instances;
+use binder::FromIBinder;
 use lazy_static::lazy_static;
 use std::sync::{Arc, Mutex, RwLock};
 use std::{cell::RefCell, sync::Once};
@@ -174,8 +178,8 @@
 }
 
 /// Determine the service name for a KeyMint device of the given security level
-/// which implements at least the specified version of the `IKeyMintDevice`
-/// interface.
+/// gotten by binder service from the device and determining what services
+/// are available.
 fn keymint_service_name(security_level: &SecurityLevel) -> Result<Option<String>> {
     let keymint_descriptor: &str = <BpKeyMintDevice as IKeyMintDevice>::get_descriptor();
     let keymint_instances = get_declared_instances(keymint_descriptor).unwrap();
@@ -212,10 +216,10 @@
 fn connect_keymint(
     security_level: &SecurityLevel,
 ) -> Result<(Strong<dyn IKeyMintDevice>, KeyMintHardwareInfo)> {
-    // Connects to binder to get the current keymint interface and
-    // based on the security level returns a service name to connect
-    // to.
-    let service_name = keymint_service_name(security_level).context(ks_err!("Get service name"))?;
+    // Show the keymint interface that is registered in the binder
+    // service and use the security level to get the service name.
+    let service_name = keymint_service_name(security_level)
+        .context(ks_err!("Get service name from binder service"))?;
 
     let (keymint, hal_version) = if let Some(service_name) = service_name {
         let km: Strong<dyn IKeyMintDevice> =
@@ -359,19 +363,17 @@
     KEY_MINT_DEVICES.lock().unwrap().devices()
 }
 
-static TIME_STAMP_SERVICE_NAME: &str = "android.hardware.security.secureclock.ISecureClock";
-
 /// Make a new connection to a secure clock service.
 /// If no native SecureClock device can be found brings up the compatibility service and attempts
 /// to connect to the legacy wrapper.
 fn connect_secureclock() -> Result<Strong<dyn ISecureClock>> {
-    let secureclock_instances =
-        get_declared_instances("android.hardware.security.secureclock.ISecureClock").unwrap();
+    let secure_clock_descriptor: &str = <BpSecureClock as ISecureClock>::get_descriptor();
+    let secureclock_instances = get_declared_instances(secure_clock_descriptor).unwrap();
 
     let secure_clock_available =
         secureclock_instances.iter().any(|instance| *instance == "default");
 
-    let default_time_stamp_service_name = format!("{}/default", TIME_STAMP_SERVICE_NAME);
+    let default_time_stamp_service_name = format!("{}/default", secure_clock_descriptor);
 
     let secureclock = if secure_clock_available {
         map_binder_status_code(binder::get_interface(&default_time_stamp_service_name))
@@ -411,25 +413,23 @@
     }
 }
 
-static REMOTE_PROVISIONING_HAL_SERVICE_NAME: &str =
-    "android.hardware.security.keymint.IRemotelyProvisionedComponent";
-
 /// Get the service name of a remotely provisioned component corresponding to given security level.
 pub fn get_remotely_provisioned_component_name(security_level: &SecurityLevel) -> Result<String> {
-    let remotely_prov_instances =
-        get_declared_instances(REMOTE_PROVISIONING_HAL_SERVICE_NAME).unwrap();
+    let remote_prov_descriptor: &str =
+        <BpRemotelyProvisionedComponent as IRemotelyProvisionedComponent>::get_descriptor();
+    let remotely_prov_instances = get_declared_instances(remote_prov_descriptor).unwrap();
 
     match *security_level {
         SecurityLevel::TRUSTED_ENVIRONMENT => {
             if remotely_prov_instances.iter().any(|instance| *instance == "default") {
-                Some(format!("{}/default", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
+                Some(format!("{}/default", remote_prov_descriptor))
             } else {
                 None
             }
         }
         SecurityLevel::STRONGBOX => {
             if remotely_prov_instances.iter().any(|instance| *instance == "strongbox") {
-                Some(format!("{}/strongbox", REMOTE_PROVISIONING_HAL_SERVICE_NAME))
+                Some(format!("{}/strongbox", remote_prov_descriptor))
             } else {
                 None
             }
diff --git a/keystore2/src/vintf/Android.bp b/keystore2/src/hal_instance_names/Android.bp
similarity index 74%
rename from keystore2/src/vintf/Android.bp
rename to keystore2/src/hal_instance_names/Android.bp
index 34719aa..2f1d5c3 100644
--- a/keystore2/src/vintf/Android.bp
+++ b/keystore2/src/hal_instance_names/Android.bp
@@ -22,41 +22,41 @@
 }
 
 rust_library {
-    name: "libkeystore2_vintf_rust",
-    crate_name: "keystore2_vintf",
+    name: "libkeystore2_hal_names_rust",
+    crate_name: "keystore2_hal_names",
     srcs: ["lib.rs"],
     rustlibs: [
         "libcxx",
     ],
     shared_libs: [
-        "libvintf",
+        "libhidlbase",
     ],
     static_libs: [
-        "libkeystore2_vintf_cpp",
+        "libkeystore2_hal_names_cpp",
     ],
 }
 
 cc_library_static {
-    name: "libkeystore2_vintf_cpp",
-    srcs: ["vintf.cpp"],
+    name: "libkeystore2_hal_names_cpp",
+    srcs: ["hal_names.cpp"],
     generated_headers: ["cxx-bridge-header"],
-    generated_sources: ["vintf_bridge_code"],
+    generated_sources: ["hal_names_bridge_code"],
     shared_libs: [
-        "libvintf",
+        "libhidlbase",
     ],
 }
 
 genrule {
-    name: "vintf_bridge_code",
+    name: "hal_names_bridge_code",
     tools: ["cxxbridge"],
     cmd: "$(location cxxbridge) $(in) >> $(out)",
     srcs: ["lib.rs"],
-    out: ["vintf_cxx_generated.cc"],
+    out: ["hal_names_cxx_generated.cc"],
 }
 
 rust_test {
-    name: "keystore2_vintf_test",
-    crate_name: "keystore2_vintf_test",
+    name: "keystore2_hal_names_test",
+    crate_name: "keystore2_hal_names_test",
     srcs: ["lib.rs"],
     test_suites: ["general-tests"],
     auto_gen_config: true,
@@ -64,10 +64,10 @@
         "libcxx",
     ],
     static_libs: [
-        "libkeystore2_vintf_cpp",
+        "libkeystore2_hal_names_cpp",
     ],
     shared_libs: [
         "libc++",
-        "libvintf",
+        "libhidlbase",
     ],
 }
diff --git a/keystore2/src/vintf/vintf.cpp b/keystore2/src/hal_instance_names/hal_names.cpp
similarity index 64%
rename from keystore2/src/vintf/vintf.cpp
rename to keystore2/src/hal_instance_names/hal_names.cpp
index bf77f5e..316c26c 100644
--- a/keystore2/src/vintf/vintf.cpp
+++ b/keystore2/src/hal_instance_names/hal_names.cpp
@@ -14,13 +14,11 @@
  * limitations under the License.
  */
 
-#include <algorithm>
-#include <vintf/HalManifest.h>
-#include <vintf/VintfObject.h>
+#include <hidl/ServiceManagement.h>
 
 #include "rust/cxx.h"
 
-rust::Vec<rust::String> convert(const std::set<std::string>& names) {
+rust::Vec<rust::String> convert(const std::vector<std::string>& names) {
     rust::Vec<rust::String> result;
     std::copy(names.begin(), names.end(), std::back_inserter(result));
     return result;
@@ -28,9 +26,10 @@
 
 rust::Vec<rust::String> get_hidl_instances(rust::Str package, size_t major_version,
                                            size_t minor_version, rust::Str interfaceName) {
-    android::vintf::Version version(major_version, minor_version);
-    const auto manifest = android::vintf::VintfObject::GetDeviceHalManifest();
-    const auto names = manifest->getHidlInstances(static_cast<std::string>(package), version,
-                                                  static_cast<std::string>(interfaceName));
-    return convert(names);
+    std::string version = std::to_string(major_version) + "." + std::to_string(minor_version);
+    std::string factoryName = static_cast<std::string>(package) + "@" + version +
+                              "::" + static_cast<std::string>(interfaceName);
+
+    const auto halNames = android::hardware::getAllHalInstanceNames(factoryName);
+    return convert(halNames);
 }
diff --git a/keystore2/src/vintf/vintf.hpp b/keystore2/src/hal_instance_names/hal_names.hpp
similarity index 100%
rename from keystore2/src/vintf/vintf.hpp
rename to keystore2/src/hal_instance_names/hal_names.hpp
diff --git a/keystore2/src/vintf/lib.rs b/keystore2/src/hal_instance_names/lib.rs
similarity index 96%
rename from keystore2/src/vintf/lib.rs
rename to keystore2/src/hal_instance_names/lib.rs
index 5bb015f..36a9c4f 100644
--- a/keystore2/src/vintf/lib.rs
+++ b/keystore2/src/hal_instance_names/lib.rs
@@ -17,7 +17,7 @@
 #[cxx::bridge]
 mod ffi {
     unsafe extern "C++" {
-        include!("vintf.hpp");
+        include!("hal_names.hpp");
 
         /// Gets the instances of the given package, version, and interface tuple.
         /// Note that this is not a zero-cost shim: it will make copies of the strings.
diff --git a/keystore2/src/shared_secret_negotiation.rs b/keystore2/src/shared_secret_negotiation.rs
index 739f4ba..ff0ddf8 100644
--- a/keystore2/src/shared_secret_negotiation.rs
+++ b/keystore2/src/shared_secret_negotiation.rs
@@ -19,20 +19,21 @@
 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::SecurityLevel::SecurityLevel;
 use android_hardware_security_keymint::binder::Strong;
 use android_hardware_security_sharedsecret::aidl::android::hardware::security::sharedsecret::{
-    ISharedSecret::ISharedSecret, SharedSecretParameters::SharedSecretParameters,
+    ISharedSecret::BpSharedSecret, ISharedSecret::ISharedSecret,
+    SharedSecretParameters::SharedSecretParameters,
 };
 use android_security_compat::aidl::android::security::compat::IKeystoreCompatService::IKeystoreCompatService;
 use anyhow::Result;
 use binder::get_declared_instances;
-use keystore2_vintf::get_hidl_instances;
+use keystore2_hal_names::get_hidl_instances;
 use std::fmt::{self, Display, Formatter};
 use std::time::Duration;
 
 /// This function initiates the shared secret negotiation. It starts a thread and then returns
-/// immediately. The thread consults the vintf manifest to enumerate expected negotiation
-/// participants. It then attempts to connect to all of these participants. If any connection
-/// fails the thread will retry once per second to connect to the failed instance(s) until all of
-/// the instances are connected. It then performs the negotiation.
+/// immediately. The thread gets hal names from the android ServiceManager. It then attempts
+/// to connect to all of these participants. If any connection fails the thread will retry once
+/// per second to connect to the failed instance(s) until all of the instances are connected.
+/// It then performs the negotiation.
 ///
 /// During the first phase of the negotiation it will again try every second until
 /// all instances have responded successfully to account for instances that register early but
@@ -63,11 +64,9 @@
 impl Display for SharedSecretParticipant {
     fn fmt(&self, f: &mut Formatter) -> fmt::Result {
         match self {
-            Self::Aidl(instance) => write!(
-                f,
-                "{}.{}/{}",
-                SHARED_SECRET_PACKAGE_NAME, SHARED_SECRET_INTERFACE_NAME, instance
-            ),
+            Self::Aidl(instance) => {
+                write!(f, "{}/{}", <BpSharedSecret as ISharedSecret>::get_descriptor(), instance)
+            }
             Self::Hidl { is_strongbox, version: (ma, mi) } => write!(
                 f,
                 "{}@V{}.{}::{}/{}",
@@ -110,10 +109,6 @@
 
 static KEYMASTER_PACKAGE_NAME: &str = "android.hardware.keymaster";
 static KEYMASTER_INTERFACE_NAME: &str = "IKeymasterDevice";
-static SHARED_SECRET_PACKAGE_NAME: &str = "android.hardware.security.sharedsecret";
-static SHARED_SECRET_INTERFACE_NAME: &str = "ISharedSecret";
-static SHARED_SECRET_PACKAGE_AND_INTERFACE_NAME: &str =
-    "android.hardware.security.sharedsecret.ISharedSecret";
 static COMPAT_PACKAGE_NAME: &str = "android.security.compat";
 
 /// Lists participants.
@@ -144,7 +139,7 @@
                 .collect::<Vec<SharedSecretParticipant>>()
         })
         .chain({
-            get_declared_instances(SHARED_SECRET_PACKAGE_AND_INTERFACE_NAME)
+            get_declared_instances(<BpSharedSecret as ISharedSecret>::get_descriptor())
                 .unwrap()
                 .into_iter()
                 .map(SharedSecretParticipant::Aidl)
@@ -166,8 +161,9 @@
                 match e {
                     SharedSecretParticipant::Aidl(instance_name) => {
                         let service_name = format!(
-                            "{}.{}/{}",
-                            SHARED_SECRET_PACKAGE_NAME, SHARED_SECRET_INTERFACE_NAME, instance_name
+                            "{}/{}",
+                            <BpSharedSecret as ISharedSecret>::get_descriptor(),
+                            instance_name
                         );
                         match map_binder_status_code(binder::get_interface(&service_name)) {
                             Err(e) => {