Merge "Rename the fix_unlocked_device_required_keys flag" into main
diff --git a/keystore2/aconfig/flags.aconfig b/keystore2/aconfig/flags.aconfig
index 41e1a92..7bdb007 100644
--- a/keystore2/aconfig/flags.aconfig
+++ b/keystore2/aconfig/flags.aconfig
@@ -1,7 +1,7 @@
 package: "android.security.keystore2"
 
 flag {
-  name: "wal_db_journalmode"
+  name: "wal_db_journalmode_v2"
   namespace: "hardware_backed_security"
   description: "This flag controls changing journalmode to wal"
   bug: "191777960"
@@ -9,7 +9,7 @@
 }
 
 flag {
-  name: "disable_legacy_keystore_put"
+  name: "disable_legacy_keystore_put_v2"
   namespace: "hardware_backed_security"
   description: "This flag disables legacy keystore put and makes it so that command returns an error"
   bug: "307460850"
diff --git a/keystore2/legacykeystore/Android.bp b/keystore2/legacykeystore/Android.bp
index 505b165..8cb7289 100644
--- a/keystore2/legacykeystore/Android.bp
+++ b/keystore2/legacykeystore/Android.bp
@@ -31,7 +31,9 @@
         "android.security.legacykeystore-rust",
         "libanyhow",
         "libbinder_rs",
+        "libkeystore2_flags_rust",
         "liblog_rust",
+        "libkeystore2_flags_rust",
         "librusqlite",
         "librustutils",
         "libthiserror",
@@ -43,6 +45,7 @@
     defaults: ["liblegacykeystore-rust_defaults"],
     rustlibs: [
         "libkeystore2",
+        "libkeystore2_flags_rust",
         "librusqlite",
     ],
 }
@@ -58,7 +61,9 @@
         "libanyhow",
         "libbinder_rs",
         "libkeystore2",
+        "libkeystore2_flags_rust",
         "libkeystore2_test_utils",
+        "libkeystore2_flags_rust",
         "liblog_rust",
         "librusqlite",
         "librustutils",
diff --git a/keystore2/legacykeystore/lib.rs b/keystore2/legacykeystore/lib.rs
index 55224f7..cf61482 100644
--- a/keystore2/legacykeystore/lib.rs
+++ b/keystore2/legacykeystore/lib.rs
@@ -46,6 +46,12 @@
             conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?,
         };
 
+        if keystore2_flags::wal_db_journalmode_v2() {
+            // Update journal mode to WAL
+            db.conn
+                .pragma_update(None, "journal_mode", "WAL")
+                .context("Failed to connect in WAL mode for persistent db")?;
+        }
         db.init_tables().context("Trying to initialize legacy keystore db.")?;
         Ok(db)
     }
@@ -121,6 +127,12 @@
     }
 
     fn put(&mut self, caller_uid: u32, alias: &str, entry: &[u8]) -> Result<()> {
+        if keystore2_flags::disable_legacy_keystore_put_v2() {
+            return Err(Error::deprecated()).context(concat!(
+                "Storing into Keystore's legacy database is ",
+                "no longer supported, store in an app-specific database instead"
+            ));
+        }
         self.with_transaction(TransactionBehavior::Immediate, |tx| {
             tx.execute(
                 "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)",
@@ -201,6 +213,11 @@
     pub fn perm() -> Self {
         Error::Error(ERROR_PERMISSION_DENIED)
     }
+
+    /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)`
+    pub fn deprecated() -> Self {
+        Error::Error(ERROR_SYSTEM_ERROR)
+    }
 }
 
 /// This function should be used by legacykeystore service calls to translate error conditions
@@ -332,6 +349,12 @@
     }
 
     fn put(&self, alias: &str, uid: i32, entry: &[u8]) -> Result<()> {
+        if keystore2_flags::disable_legacy_keystore_put_v2() {
+            return Err(Error::deprecated()).context(concat!(
+                "Storing into Keystore's legacy database is ",
+                "no longer supported, store in an app-specific database instead"
+            ));
+        }
         let uid = Self::get_effective_uid(uid).context("In put.")?;
         let mut db = self.open_db().context("In put.")?;
         db.put(uid, alias, entry).context("In put: Trying to insert entry into DB.")?;
diff --git a/keystore2/src/database.rs b/keystore2/src/database.rs
index 63dbf7f..93de484 100644
--- a/keystore2/src/database.rs
+++ b/keystore2/src/database.rs
@@ -1036,7 +1036,7 @@
             break;
         }
 
-        if keystore2_flags::wal_db_journalmode() {
+        if keystore2_flags::wal_db_journalmode_v2() {
             // Update journal mode to WAL
             conn.pragma_update(None, "journal_mode", "WAL")
                 .context("Failed to connect in WAL mode for persistent db")?;
diff --git a/keystore2/src/remote_provisioning.rs b/keystore2/src/remote_provisioning.rs
index a386d96..0ef8c95 100644
--- a/keystore2/src/remote_provisioning.rs
+++ b/keystore2/src/remote_provisioning.rs
@@ -24,6 +24,7 @@
     KeyParameter::KeyParameter, KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel,
     Tag::Tag,
 };
+use android_security_rkp_aidl::aidl::android::security::rkp::RemotelyProvisionedKey::RemotelyProvisionedKey;
 use android_system_keystore2::aidl::android::system::keystore2::{
     Domain::Domain, KeyDescriptor::KeyDescriptor,
 };
@@ -37,7 +38,6 @@
 use crate::metrics_store::log_rkp_error_stats;
 use crate::watchdog_helper::watchdog as wd;
 use android_security_metrics::aidl::android::security::metrics::RkpError::RkpError as MetricsRkpError;
-use rkpd_client::get_rkpd_attestation_key;
 
 /// Contains helper functions to check if remote provisioning is enabled on the system and, if so,
 /// to assign and retrieve attestation keys and certificate chains.
@@ -96,10 +96,7 @@
         if !self.is_asymmetric_key(params) || key.domain != Domain::APP {
             Ok(None)
         } else {
-            let rpc_name = get_remotely_provisioned_component_name(&self.security_level)
-                .context(ks_err!("Trying to get IRPC name."))?;
-            let _wd = wd::watch_millis("Calling get_rkpd_attestation_key()", 500);
-            match get_rkpd_attestation_key(&rpc_name, caller_uid) {
+            match get_rkpd_attestation_key(&self.security_level, caller_uid) {
                 Err(e) => {
                     if self.is_rkp_only() {
                         log::error!("Error occurred: {:?}", e);
@@ -128,3 +125,17 @@
         }
     }
 }
+
+fn get_rkpd_attestation_key(
+    security_level: &SecurityLevel,
+    caller_uid: u32,
+) -> Result<RemotelyProvisionedKey> {
+    // Depending on the Android release, RKP may not have been mandatory for the
+    // TEE or StrongBox KM instances. In such cases, lookup failure for the IRPC
+    // HAL service is WAI and should not cause a failure. The error should be caught
+    // by the calling function and allow for natural fallback to the factory key.
+    let rpc_name = get_remotely_provisioned_component_name(security_level)
+        .context(ks_err!("Trying to get IRPC name."))?;
+    let _wd = wd::watch_millis("Calling get_rkpd_attestation_key()", 500);
+    rkpd_client::get_rkpd_attestation_key(&rpc_name, caller_uid)
+}