Empty merge of Android 24Q2 Release (ab/11526283) to aosp-main-future

Bug: 337098550
Merged-In: I619784b71c0a87574dc633d641aec91da1fc3475
Change-Id: Ic602b2b32c98e650a405c15ce0454affe89adcf3
diff --git a/fsverity/fsverity_manifest_generator.py b/fsverity/fsverity_manifest_generator.py
index 181758a..ca7ac5c 100644
--- a/fsverity/fsverity_manifest_generator.py
+++ b/fsverity/fsverity_manifest_generator.py
@@ -35,7 +35,7 @@
   return bytes(bytearray.fromhex(out))
 
 if __name__ == '__main__':
-  p = argparse.ArgumentParser()
+  p = argparse.ArgumentParser(fromfile_prefix_chars='@')
   p.add_argument(
       '--output',
       help='Path to the output manifest',
@@ -52,7 +52,7 @@
       'inputs',
       nargs='*',
       help='input file for the build manifest')
-  args = p.parse_args(sys.argv[1:])
+  args = p.parse_args()
 
   digests = FSVerityDigests()
   for f in sorted(args.inputs):
diff --git a/identity/Android.bp b/identity/Android.bp
index 6227bfe..a563532 100644
--- a/identity/Android.bp
+++ b/identity/Android.bp
@@ -59,7 +59,7 @@
         "android.hardware.identity-support-lib",
         "android.hardware.security.rkp-V3-cpp",
         "android.security.rkp_aidl-cpp",
-        "libcppbor_external",
+        "libcppbor",
         "libcredstore_aidl",
         "libkeymaster4support",
         "librkp_support",
diff --git a/keystore2/Android.bp b/keystore2/Android.bp
index 7cb7c37..ed9cd88 100644
--- a/keystore2/Android.bp
+++ b/keystore2/Android.bp
@@ -28,6 +28,7 @@
     defaults: [
         "keymint_use_latest_hal_aidl_rust",
         "keystore2_use_latest_aidl_rust",
+        "structured_log_rust_defaults",
     ],
 
     rustlibs: [
@@ -54,7 +55,6 @@
         "libkeystore2_selinux",
         "liblazy_static",
         "liblibc",
-        "liblog_event_list",
         "liblog_rust",
         "libmessage_macro",
         "librand",
diff --git a/keystore2/aidl/android/security/authorization/IKeystoreAuthorization.aidl b/keystore2/aidl/android/security/authorization/IKeystoreAuthorization.aidl
index a9de026..fd532f6 100644
--- a/keystore2/aidl/android/security/authorization/IKeystoreAuthorization.aidl
+++ b/keystore2/aidl/android/security/authorization/IKeystoreAuthorization.aidl
@@ -18,8 +18,6 @@
 import android.hardware.security.keymint.HardwareAuthenticatorType;
 import android.security.authorization.AuthorizationTokens;
 
-// TODO: mark the interface with @SensitiveData when the annotation is ready (b/176110256).
-
 /**
  * IKeystoreAuthorization interface exposes the methods for other system components to
  * provide keystore with the information required to enforce authorizations on key usage.
diff --git a/keystore2/aidl/android/security/maintenance/IKeystoreMaintenance.aidl b/keystore2/aidl/android/security/maintenance/IKeystoreMaintenance.aidl
index abea958..50e9828 100644
--- a/keystore2/aidl/android/security/maintenance/IKeystoreMaintenance.aidl
+++ b/keystore2/aidl/android/security/maintenance/IKeystoreMaintenance.aidl
@@ -112,16 +112,6 @@
      void earlyBootEnded();
 
     /**
-     * Informs Keystore 2.0 that the an off body event was detected.
-     *
-     * ## Error conditions:
-     * `ResponseCode::PERMISSION_DENIED` - if the caller does not have the `ReportOffBody`
-     *                                     permission.
-     * `ResponseCode::SYSTEM_ERROR` - if an unexpected error occurred.
-     */
-    void onDeviceOffBody();
-
-    /**
      * Migrate a key from one namespace to another. The caller must have use, grant, and delete
      * permissions on the source namespace and rebind permissions on the destination namespace.
      * The source may be specified by Domain::APP, Domain::SELINUX, or Domain::KEY_ID. The target
diff --git a/keystore2/src/audit_log.rs b/keystore2/src/audit_log.rs
index 0e5dfeb..8d9735e 100644
--- a/keystore2/src/audit_log.rs
+++ b/keystore2/src/audit_log.rs
@@ -20,7 +20,7 @@
     Domain::Domain, KeyDescriptor::KeyDescriptor,
 };
 use libc::uid_t;
-use log_event_list::{LogContext, LogContextError, LogIdSecurity};
+use structured_log::{structured_log, LOG_ID_SECURITY};
 
 const TAG_KEY_GENERATED: u32 = 210024;
 const TAG_KEY_IMPORTED: u32 = 210025;
@@ -58,30 +58,19 @@
 
 /// Logs key integrity violation to NIAP audit log.
 pub fn log_key_integrity_violation(key: &KeyDescriptor) {
-    with_log_context(TAG_KEY_INTEGRITY_VIOLATION, |ctx| {
-        let owner = key_owner(key.domain, key.nspace, key.nspace as i32);
-        ctx.append_str(key.alias.as_ref().map_or("none", String::as_str))?.append_i32(owner)
-    })
+    let owner = key_owner(key.domain, key.nspace, key.nspace as i32);
+    let alias = String::from(key.alias.as_ref().map_or("none", String::as_str));
+    LOGS_HANDLER.queue_lo(move |_| {
+        let _result =
+            structured_log!(log_id: LOG_ID_SECURITY, TAG_KEY_INTEGRITY_VIOLATION, alias, owner);
+    });
 }
 
 fn log_key_event(tag: u32, key: &KeyDescriptor, calling_app: uid_t, success: bool) {
-    with_log_context(tag, |ctx| {
-        let owner = key_owner(key.domain, key.nspace, calling_app as i32);
-        ctx.append_i32(i32::from(success))?
-            .append_str(key.alias.as_ref().map_or("none", String::as_str))?
-            .append_i32(owner)
-    })
-}
-
-fn with_log_context<F>(tag: u32, f: F)
-where
-    F: Fn(LogContext) -> Result<LogContext, LogContextError>,
-{
-    if let Some(ctx) = LogContext::new(LogIdSecurity, tag) {
-        if let Ok(event) = f(ctx) {
-            LOGS_HANDLER.queue_lo(move |_| {
-                let _result = event.write();
-            });
-        }
-    }
+    let owner = key_owner(key.domain, key.nspace, calling_app as i32);
+    let alias = String::from(key.alias.as_ref().map_or("none", String::as_str));
+    LOGS_HANDLER.queue_lo(move |_| {
+        let _result =
+            structured_log!(log_id: LOG_ID_SECURITY, tag, i32::from(success), alias, owner);
+    });
 }
diff --git a/keystore2/src/authorization.rs b/keystore2/src/authorization.rs
index f956787..243abf1 100644
--- a/keystore2/src/authorization.rs
+++ b/keystore2/src/authorization.rs
@@ -128,7 +128,8 @@
 
     fn add_auth_token(&self, auth_token: &HardwareAuthToken) -> Result<()> {
         // Check keystore permission.
-        check_keystore_permission(KeystorePerm::AddAuth).context(ks_err!())?;
+        check_keystore_permission(KeystorePerm::AddAuth)
+            .context(ks_err!("caller missing AddAuth permissions"))?;
 
         log::info!(
             "add_auth_token(challenge={}, userId={}, authId={}, authType={:#x}, timestamp={}ms)",
@@ -149,7 +150,8 @@
             user_id,
             password.is_some(),
         );
-        check_keystore_permission(KeystorePerm::Unlock).context(ks_err!("Unlock."))?;
+        check_keystore_permission(KeystorePerm::Unlock)
+            .context(ks_err!("caller missing Unlock permissions"))?;
         ENFORCEMENTS.set_device_locked(user_id, false);
 
         let mut skm = SUPER_KEY.write().unwrap();
@@ -160,7 +162,7 @@
             .context(ks_err!("Unlock with password."))
         } else {
             DB.with(|db| skm.try_unlock_user_with_biometric(&mut db.borrow_mut(), user_id as u32))
-                .context(ks_err!("try_unlock_user_with_biometric failed"))
+                .context(ks_err!("try_unlock_user_with_biometric failed user_id={user_id}"))
         }
     }
 
@@ -179,7 +181,8 @@
         if !android_security_flags::fix_unlocked_device_required_keys_v2() {
             weak_unlock_enabled = false;
         }
-        check_keystore_permission(KeystorePerm::Lock).context(ks_err!("Lock"))?;
+        check_keystore_permission(KeystorePerm::Lock)
+            .context(ks_err!("caller missing Lock permission"))?;
         ENFORCEMENTS.set_device_locked(user_id, true);
         let mut skm = SUPER_KEY.write().unwrap();
         DB.with(|db| {
@@ -198,7 +201,8 @@
         if !android_security_flags::fix_unlocked_device_required_keys_v2() {
             return Ok(());
         }
-        check_keystore_permission(KeystorePerm::Lock).context(ks_err!("Lock"))?;
+        check_keystore_permission(KeystorePerm::Lock)
+            .context(ks_err!("caller missing Lock permission"))?;
         SUPER_KEY.write().unwrap().wipe_plaintext_unlocked_device_required_keys(user_id as u32);
         Ok(())
     }
@@ -208,7 +212,8 @@
         if !android_security_flags::fix_unlocked_device_required_keys_v2() {
             return Ok(());
         }
-        check_keystore_permission(KeystorePerm::Lock).context(ks_err!("Lock"))?;
+        check_keystore_permission(KeystorePerm::Lock)
+            .context(ks_err!("caller missing Lock permission"))?;
         SUPER_KEY.write().unwrap().wipe_all_unlocked_device_required_keys(user_id as u32);
         Ok(())
     }
@@ -221,7 +226,8 @@
     ) -> Result<AuthorizationTokens> {
         // Check permission. Function should return if this failed. Therefore having '?' at the end
         // is very important.
-        check_keystore_permission(KeystorePerm::GetAuthToken).context(ks_err!("GetAuthToken"))?;
+        check_keystore_permission(KeystorePerm::GetAuthToken)
+            .context(ks_err!("caller missing GetAuthToken permission"))?;
 
         // If the challenge is zero, return error
         if challenge == 0 {
@@ -240,7 +246,8 @@
         auth_types: &[HardwareAuthenticatorType],
     ) -> Result<i64> {
         // Check keystore permission.
-        check_keystore_permission(KeystorePerm::GetLastAuthTime).context(ks_err!())?;
+        check_keystore_permission(KeystorePerm::GetLastAuthTime)
+            .context(ks_err!("caller missing GetLastAuthTime permission"))?;
 
         let mut max_time: i64 = -1;
         for auth_type in auth_types.iter() {
diff --git a/keystore2/src/crypto/zvec.rs b/keystore2/src/crypto/zvec.rs
index c917a89..00cbb1c 100644
--- a/keystore2/src/crypto/zvec.rs
+++ b/keystore2/src/crypto/zvec.rs
@@ -20,6 +20,7 @@
 use std::fmt;
 use std::ops::{Deref, DerefMut};
 use std::ptr::write_volatile;
+use std::ptr::NonNull;
 
 /// A semi fixed size u8 vector that is zeroed when dropped.  It can shrink in
 /// size but cannot grow larger than the original size (and if it shrinks it
@@ -46,7 +47,7 @@
         let b = v.into_boxed_slice();
         if size > 0 {
             // SAFETY: The address range is part of our address space.
-            unsafe { mlock(b.as_ptr() as *const std::ffi::c_void, b.len()) }?;
+            unsafe { mlock(NonNull::from(&b).cast(), b.len()) }?;
         }
         Ok(Self { elems: b, len: size })
     }
@@ -79,9 +80,7 @@
             if let Err(e) =
                 // SAFETY: The address range is part of our address space, and was previously locked
                 // by `mlock` in `ZVec::new` or the `TryFrom<Vec<u8>>` implementation.
-                unsafe {
-                    munlock(self.elems.as_ptr() as *const std::ffi::c_void, self.elems.len())
-                }
+                unsafe { munlock(NonNull::from(&self.elems).cast(), self.elems.len()) }
             {
                 log::error!("In ZVec::drop: `munlock` failed: {:?}.", e);
             }
@@ -137,7 +136,7 @@
         let b = v.into_boxed_slice();
         if !b.is_empty() {
             // SAFETY: The address range is part of our address space.
-            unsafe { mlock(b.as_ptr() as *const std::ffi::c_void, b.len()) }?;
+            unsafe { mlock(NonNull::from(&b).cast(), b.len()) }?;
         }
         Ok(Self { elems: b, len })
     }
diff --git a/keystore2/src/database.rs b/keystore2/src/database.rs
index 2757313..0cc982a 100644
--- a/keystore2/src/database.rs
+++ b/keystore2/src/database.rs
@@ -842,11 +842,6 @@
     }
 }
 
-/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
-/// This object does not allow access to the database connection. But it keeps a database
-/// connection alive in order to keep the in memory per boot database alive.
-pub struct PerBootDbKeepAlive(Connection);
-
 impl KeystoreDB {
     const UNASSIGNED_KEY_ID: i64 = -1i64;
     const CURRENT_DB_VERSION: u32 = 1;
@@ -2864,26 +2859,11 @@
     }
 
     /// Find the newest auth token matching the given predicate.
-    pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, BootTime)>
+    pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
     where
         F: Fn(&AuthTokenEntry) -> bool,
     {
-        self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
-    }
-
-    /// Insert last_off_body into the metadata table at the initialization of auth token table
-    pub fn insert_last_off_body(&self, last_off_body: BootTime) {
-        self.perboot.set_last_off_body(last_off_body)
-    }
-
-    /// Update last_off_body when on_device_off_body is called
-    pub fn update_last_off_body(&self, last_off_body: BootTime) {
-        self.perboot.set_last_off_body(last_off_body)
-    }
-
-    /// Get last_off_body time when finding auth tokens
-    fn get_last_off_body(&self) -> BootTime {
-        self.perboot.get_last_off_body()
+        self.perboot.find_auth_token_entry(p)
     }
 
     /// Load descriptor of a key by key id
@@ -5033,7 +5013,7 @@
     // This allows us to test repeated elements.
 
     thread_local! {
-        static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
+        static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
     }
 
     fn reset_random() {
@@ -5051,23 +5031,6 @@
     }
 
     #[test]
-    fn test_last_off_body() -> Result<()> {
-        let mut db = new_test_db()?;
-        db.insert_last_off_body(BootTime::now());
-        let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
-        tx.commit()?;
-        let last_off_body_1 = db.get_last_off_body();
-        let one_second = Duration::from_secs(1);
-        thread::sleep(one_second);
-        db.update_last_off_body(BootTime::now());
-        let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
-        tx2.commit()?;
-        let last_off_body_2 = db.get_last_off_body();
-        assert!(last_off_body_1 < last_off_body_2);
-        Ok(())
-    }
-
-    #[test]
     fn test_unbind_keys_for_user() -> Result<()> {
         let mut db = new_test_db()?;
         db.unbind_keys_for_user(1, false)?;
@@ -5491,7 +5454,7 @@
         // All three entries are in the database
         assert_eq!(db.perboot.auth_tokens_len(), 3);
         // It selected the most recent timestamp
-        assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
+        assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
         Ok(())
     }
 
diff --git a/keystore2/src/database/perboot.rs b/keystore2/src/database/perboot.rs
index 1b7c80d..4727015 100644
--- a/keystore2/src/database/perboot.rs
+++ b/keystore2/src/database/perboot.rs
@@ -13,15 +13,14 @@
 // limitations under the License.
 
 //! This module implements a per-boot, shared, in-memory storage of auth tokens
-//! and last-time-on-body for the main Keystore 2.0 database module.
+//! for the main Keystore 2.0 database module.
 
-use super::{AuthTokenEntry, BootTime};
+use super::AuthTokenEntry;
 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
     HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
 };
 use lazy_static::lazy_static;
 use std::collections::HashSet;
-use std::sync::atomic::{AtomicI64, Ordering};
 use std::sync::Arc;
 use std::sync::RwLock;
 
@@ -62,17 +61,13 @@
 
 impl Eq for AuthTokenEntryWrap {}
 
-/// Per-boot state structure. Currently only used to track auth tokens and
-/// last-off-body.
+/// Per-boot state structure. Currently only used to track auth tokens.
 #[derive(Default)]
 pub struct PerbootDB {
     // We can use a .unwrap() discipline on this lock, because only panicking
     // while holding a .write() lock will poison it. The only write usage is
     // an insert call which inserts a pre-constructed pair.
     auth_tokens: RwLock<HashSet<AuthTokenEntryWrap>>,
-    // Ordering::Relaxed is appropriate for accessing this atomic, since it
-    // does not currently need to be synchronized with anything else.
-    last_off_body: AtomicI64,
 }
 
 lazy_static! {
@@ -102,14 +97,6 @@
         matches.sort_by_key(|x| x.0.time_received);
         matches.last().map(|x| x.0.clone())
     }
-    /// Get the last time the device was off the user's body
-    pub fn get_last_off_body(&self) -> BootTime {
-        BootTime(self.last_off_body.load(Ordering::Relaxed))
-    }
-    /// Set the last time the device was off the user's body
-    pub fn set_last_off_body(&self, last_off_body: BootTime) {
-        self.last_off_body.store(last_off_body.0, Ordering::Relaxed)
-    }
     /// Return how many auth tokens are currently tracked.
     pub fn auth_tokens_len(&self) -> usize {
         self.auth_tokens.read().unwrap().len()
diff --git a/keystore2/src/enforcements.rs b/keystore2/src/enforcements.rs
index 55c9591..95dd026 100644
--- a/keystore2/src/enforcements.rs
+++ b/keystore2/src/enforcements.rs
@@ -476,7 +476,6 @@
         let mut user_id: i32 = -1;
         let mut user_secure_ids = Vec::<i64>::new();
         let mut key_time_out: Option<i64> = None;
-        let mut allow_while_on_body = false;
         let mut unlocked_device_required = false;
         let mut key_usage_limited: Option<i64> = None;
         let mut confirmation_token_receiver: Option<Arc<Mutex<Option<Receiver<Vec<u8>>>>>> = None;
@@ -533,9 +532,6 @@
                 KeyParameterValue::UnlockedDeviceRequired => {
                     unlocked_device_required = true;
                 }
-                KeyParameterValue::AllowWhileOnBody => {
-                    allow_while_on_body = true;
-                }
                 KeyParameterValue::UsageCountLimit(_) => {
                     // We don't examine the limit here because this is enforced on finish.
                     // Instead, we store the key_id so that finish can look up the key
@@ -607,13 +603,12 @@
             let (hat, state) = if user_secure_ids.is_empty() {
                 (None, DeferredAuthState::NoAuthRequired)
             } else if let Some(key_time_out) = key_time_out {
-                let (hat, last_off_body) =
-                    Self::find_auth_token(|hat: &AuthTokenEntry| match user_auth_type {
-                        Some(auth_type) => hat.satisfies(&user_secure_ids, auth_type),
-                        None => false, // not reachable due to earlier check
-                    })
-                    .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
-                    .context(ks_err!("No suitable auth token found."))?;
+                let hat = Self::find_auth_token(|hat: &AuthTokenEntry| match user_auth_type {
+                    Some(auth_type) => hat.satisfies(&user_secure_ids, auth_type),
+                    None => false, // not reachable due to earlier check
+                })
+                .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
+                .context(ks_err!("No suitable auth token found."))?;
                 let now = BootTime::now();
                 let token_age = now
                     .checked_sub(&hat.time_received())
@@ -623,9 +618,7 @@
                     Validity cannot be established."
                     ))?;
 
-                let on_body_extended = allow_while_on_body && last_off_body < hat.time_received();
-
-                if token_age.seconds() > key_time_out && !on_body_extended {
+                if token_age.seconds() > key_time_out {
                     return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
                         .context(ks_err!("matching auth token is expired."));
                 }
@@ -660,8 +653,8 @@
 
         let need_auth_token = timeout_bound || unlocked_device_required;
 
-        let hat_and_last_off_body = if need_auth_token {
-            let hat_and_last_off_body = Self::find_auth_token(|hat: &AuthTokenEntry| {
+        let hat = if need_auth_token {
+            let hat = Self::find_auth_token(|hat: &AuthTokenEntry| {
                 if let (Some(auth_type), true) = (user_auth_type, timeout_bound) {
                     hat.satisfies(&user_secure_ids, auth_type)
                 } else {
@@ -669,8 +662,7 @@
                 }
             });
             Some(
-                hat_and_last_off_body
-                    .ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
+                hat.ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
                     .context(ks_err!("No suitable auth token found."))?,
             )
         } else {
@@ -678,8 +670,8 @@
         };
 
         // Now check the validity of the auth token if the key is timeout bound.
-        let hat = match (hat_and_last_off_body, key_time_out) {
-            (Some((hat, last_off_body)), Some(key_time_out)) => {
+        let hat = match (hat, key_time_out) {
+            (Some(hat), Some(key_time_out)) => {
                 let now = BootTime::now();
                 let token_age = now
                     .checked_sub(&hat.time_received())
@@ -689,15 +681,13 @@
                     Validity cannot be established."
                     ))?;
 
-                let on_body_extended = allow_while_on_body && last_off_body < hat.time_received();
-
-                if token_age.seconds() > key_time_out && !on_body_extended {
+                if token_age.seconds() > key_time_out {
                     return Err(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
                         .context(ks_err!("matching auth token is expired."));
                 }
                 Some(hat)
             }
-            (Some((hat, _)), None) => Some(hat),
+            (Some(hat), None) => Some(hat),
             // If timeout_bound is true, above code must have retrieved a HAT or returned with
             // KEY_USER_NOT_AUTHENTICATED. This arm should not be reachable.
             (None, Some(_)) => panic!("Logical error."),
@@ -728,7 +718,7 @@
         })
     }
 
-    fn find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, BootTime)>
+    fn find_auth_token<F>(p: F) -> Option<AuthTokenEntry>
     where
         F: Fn(&AuthTokenEntry) -> bool,
     {
@@ -848,7 +838,7 @@
             (challenge == hat.challenge()) && hat.satisfies(&sids, auth_type)
         });
 
-        let auth_token = if let Some((auth_token_entry, _)) = result {
+        let auth_token = if let Some(auth_token_entry) = result {
             auth_token_entry.take_auth_token()
         } else {
             // Filter the matching auth tokens by age.
@@ -863,7 +853,7 @@
                     token_valid && auth_token_entry.satisfies(&sids, auth_type)
                 });
 
-                if let Some((auth_token_entry, _)) = result {
+                if let Some(auth_token_entry) = result {
                     auth_token_entry.take_auth_token()
                 } else {
                     return Err(AuthzError::Rc(AuthzResponseCode::NO_AUTH_TOKEN_FOUND))
@@ -895,11 +885,7 @@
         let result =
             Self::find_auth_token(|entry: &AuthTokenEntry| entry.satisfies(&sids, auth_type));
 
-        if let Some((auth_token_entry, _)) = result {
-            Some(auth_token_entry.time_received())
-        } else {
-            None
-        }
+        result.map(|auth_token_entry| auth_token_entry.time_received())
     }
 }
 
diff --git a/keystore2/src/globals.rs b/keystore2/src/globals.rs
index eb755a6..7ac1038 100644
--- a/keystore2/src/globals.rs
+++ b/keystore2/src/globals.rs
@@ -16,6 +16,7 @@
 //! database connections and connections to services that Keystore needs
 //! to talk to.
 
+use crate::async_task::AsyncTask;
 use crate::gc::Gc;
 use crate::km_compat::{BacklevelKeyMintWrapper, KeyMintV1};
 use crate::ks_err;
@@ -23,7 +24,6 @@
 use crate::legacy_importer::LegacyImporter;
 use crate::super_key::SuperKeyManager;
 use crate::utils::watchdog as wd;
-use crate::{async_task::AsyncTask, database::BootTime};
 use crate::{
     database::KeystoreDB,
     database::Uuid,
@@ -68,7 +68,6 @@
 
     DB_INIT.call_once(|| {
         log::info!("Touching Keystore 2.0 database for this first time since boot.");
-        db.insert_last_off_body(BootTime::now());
         log::info!("Calling cleanup leftovers.");
         let n = db.cleanup_leftovers().expect("Failed to cleanup database on startup.");
         if n != 0 {
@@ -247,7 +246,11 @@
                     }
                     e => e,
                 })
-                .context(ks_err!("Trying to get Legacy wrapper."))?,
+                .context(ks_err!(
+                    "Trying to get Legacy wrapper. Attempt to get keystore \
+                    compat service for security level {:?}",
+                    *security_level
+                ))?,
             None,
         )
     };
@@ -394,7 +397,7 @@
                 }
                 e => e,
             })
-            .context(ks_err!("Trying to get Legacy wrapper."))
+            .context(ks_err!("Failed attempt to get legacy secure clock."))
     }?;
 
     Ok(secureclock)
@@ -437,5 +440,5 @@
         _ => None,
     }
     .ok_or(Error::Km(ErrorCode::HARDWARE_TYPE_UNAVAILABLE))
-    .context(ks_err!())
+    .context(ks_err!("Failed to get rpc for sec level {:?}", *security_level))
 }
diff --git a/keystore2/src/key_parameter.rs b/keystore2/src/key_parameter.rs
index 02a1f16..bd45207 100644
--- a/keystore2/src/key_parameter.rs
+++ b/keystore2/src/key_parameter.rs
@@ -912,7 +912,8 @@
     /// The time in seconds for which the key is authorized for use, after user authentication
     #[key_param(tag = AUTH_TIMEOUT, field = Integer)]
     AuthTimeout(i32),
-    /// The key may be used after authentication timeout if device is still on-body
+    /// The key's authentication timeout, if it has one, is automatically expired when the device is
+    /// removed from the user's body. No longer implemented; this tag is no longer enforced.
     #[key_param(tag = ALLOW_WHILE_ON_BODY, field = BoolValue)]
     AllowWhileOnBody,
     /// The key must be unusable except when the user has provided proof of physical presence
diff --git a/keystore2/src/maintenance.rs b/keystore2/src/maintenance.rs
index 3e34cff..8780e9e 100644
--- a/keystore2/src/maintenance.rs
+++ b/keystore2/src/maintenance.rs
@@ -14,7 +14,7 @@
 
 //! This module implements IKeystoreMaintenance AIDL interface.
 
-use crate::database::{BootTime, KeyEntryLoadBits, KeyType};
+use crate::database::{KeyEntryLoadBits, KeyType};
 use crate::error::map_km_error;
 use crate::error::map_or_log_err;
 use crate::error::Error;
@@ -224,14 +224,6 @@
         Maintenance::call_on_all_security_levels("earlyBootEnded", |dev| dev.earlyBootEnded())
     }
 
-    fn on_device_off_body() -> Result<()> {
-        // Security critical permission check. This statement must return on fail.
-        check_keystore_permission(KeystorePerm::ReportOffBody).context(ks_err!())?;
-
-        DB.with(|db| db.borrow_mut().update_last_off_body(BootTime::now()));
-        Ok(())
-    }
-
     fn migrate_key_namespace(source: &KeyDescriptor, destination: &KeyDescriptor) -> Result<()> {
         let calling_uid = ThreadState::get_calling_uid();
 
@@ -355,12 +347,6 @@
         map_or_log_err(Self::early_boot_ended(), Ok)
     }
 
-    fn onDeviceOffBody(&self) -> BinderResult<()> {
-        log::info!("onDeviceOffBody()");
-        let _wp = wd::watch_millis("IKeystoreMaintenance::onDeviceOffBody", 500);
-        map_or_log_err(Self::on_device_off_body(), Ok)
-    }
-
     fn migrateKeyNamespace(
         &self,
         source: &KeyDescriptor,
diff --git a/keystore2/src/permission.rs b/keystore2/src/permission.rs
index bc73744..982bc82 100644
--- a/keystore2/src/permission.rs
+++ b/keystore2/src/permission.rs
@@ -137,10 +137,7 @@
         /// Checked when earlyBootEnded() is called.
         #[selinux(name = early_boot_ended)]
         EarlyBootEnded,
-        /// Checked when IKeystoreMaintenance::onDeviceOffBody is called.
-        #[selinux(name = report_off_body)]
-        ReportOffBody,
-        /// Checked when IkeystoreMetrics::pullMetrics is called.
+        /// Checked when IKeystoreMetrics::pullMetrics is called.
         #[selinux(name = pull_metrics)]
         PullMetrics,
         /// Checked when IKeystoreMaintenance::deleteAllKeys is called.
diff --git a/keystore2/src/super_key.rs b/keystore2/src/super_key.rs
index 44ce9ab..11ab734 100644
--- a/keystore2/src/super_key.rs
+++ b/keystore2/src/super_key.rs
@@ -1011,7 +1011,7 @@
             let mut errs = vec![];
             for sid in &biometric.sids {
                 let sid = *sid;
-                if let Some((auth_token_entry, _)) = db.find_auth_token_entry(|entry| {
+                if let Some(auth_token_entry) = db.find_auth_token_entry(|entry| {
                     entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
                 }) {
                     let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
diff --git a/keystore2/test_utils/run_as.rs b/keystore2/test_utils/run_as.rs
index be643b6..d39d069 100644
--- a/keystore2/test_utils/run_as.rs
+++ b/keystore2/test_utils/run_as.rs
@@ -29,13 +29,14 @@
 use keystore2_selinux as selinux;
 use nix::sys::wait::{waitpid, WaitStatus};
 use nix::unistd::{
-    close, fork, pipe as nix_pipe, read as nix_read, setgid, setuid, write as nix_write,
-    ForkResult, Gid, Pid, Uid,
+    fork, pipe as nix_pipe, read as nix_read, setgid, setuid, write as nix_write, ForkResult, Gid,
+    Pid, Uid,
 };
 use serde::{de::DeserializeOwned, Serialize};
 use std::io::{Read, Write};
 use std::marker::PhantomData;
-use std::os::unix::io::RawFd;
+use std::os::fd::AsRawFd;
+use std::os::fd::OwnedFd;
 
 fn transition(se_context: selinux::Context, uid: Uid, gid: Gid) {
     setgid(gid).expect("Failed to set GID. This test might need more privileges.");
@@ -48,35 +49,23 @@
 /// PipeReader is a simple wrapper around raw pipe file descriptors.
 /// It takes ownership of the file descriptor and closes it on drop. It provides `read_all`, which
 /// reads from the pipe into an expending vector, until no more data can be read.
-struct PipeReader(RawFd);
+struct PipeReader(OwnedFd);
 
 impl Read for PipeReader {
     fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
-        let bytes = nix_read(self.0, buf)?;
+        let bytes = nix_read(self.0.as_raw_fd(), buf)?;
         Ok(bytes)
     }
 }
 
-impl Drop for PipeReader {
-    fn drop(&mut self) {
-        close(self.0).expect("Failed to close reader pipe fd.");
-    }
-}
-
 /// PipeWriter is a simple wrapper around raw pipe file descriptors.
 /// It takes ownership of the file descriptor and closes it on drop. It provides `write`, which
 /// writes the given buffer into the pipe, returning the number of bytes written.
-struct PipeWriter(RawFd);
-
-impl Drop for PipeWriter {
-    fn drop(&mut self) {
-        close(self.0).expect("Failed to close writer pipe fd.");
-    }
-}
+struct PipeWriter(OwnedFd);
 
 impl Write for PipeWriter {
     fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
-        let written = nix_write(self.0, buf)?;
+        let written = nix_write(&self.0, buf)?;
         Ok(written)
     }
 
diff --git a/keystore2/tests/AndroidTest.xml b/keystore2/tests/AndroidTest.xml
index 7db36f7..dde18a9 100644
--- a/keystore2/tests/AndroidTest.xml
+++ b/keystore2/tests/AndroidTest.xml
@@ -14,6 +14,7 @@
      limitations under the License.
 -->
 <configuration description="Config to run keystore2_client_tests device tests.">
+    <option name="config-descriptor:metadata" key="parameter" value="not_multi_abi" />
 
     <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer">
     </target_preparer>
diff --git a/keystore2/tests/keystore2_client_test_utils.rs b/keystore2/tests/keystore2_client_test_utils.rs
index f270297..7534da3 100644
--- a/keystore2/tests/keystore2_client_test_utils.rs
+++ b/keystore2/tests/keystore2_client_test_utils.rs
@@ -95,14 +95,11 @@
     // only system update and not vendor update, newly added attestation properties
     // (ro.product.*_for_attestation) reading logic would not be available for such devices
     // hence skipping this test for such scenario.
-    let api_level = std::str::from_utf8(&get_system_prop("ro.board.first_api_level"))
-        .unwrap()
-        .parse::<i32>()
-        .unwrap();
-    // This file is only present on GSI builds.
-    let path_buf = PathBuf::from("/system/system_ext/etc/init/init.gsi.rc");
 
-    api_level < 34 && path_buf.as_path().is_file()
+    // This file is only present on GSI builds.
+    let gsi_marker = PathBuf::from("/system/system_ext/etc/init/init.gsi.rc");
+
+    get_vsr_api_level() < 34 && gsi_marker.as_path().is_file()
 }
 
 #[macro_export]
@@ -514,15 +511,38 @@
     }
 }
 
+fn get_integer_system_prop(name: &str) -> Option<i32> {
+    let val = get_system_prop(name);
+    if val.is_empty() {
+        return None;
+    }
+    let val = std::str::from_utf8(&val).ok()?;
+    val.parse::<i32>().ok()
+}
+
+pub fn get_vsr_api_level() -> i32 {
+    if let Some(api_level) = get_integer_system_prop("ro.vendor.api_level") {
+        return api_level;
+    }
+
+    let vendor_api_level = get_integer_system_prop("ro.board.api_level")
+        .or_else(|| get_integer_system_prop("ro.board.first_api_level"));
+    let product_api_level = get_integer_system_prop("ro.product.first_api_level")
+        .or_else(|| get_integer_system_prop("ro.build.version.sdk"));
+
+    match (vendor_api_level, product_api_level) {
+        (Some(v), Some(p)) => std::cmp::min(v, p),
+        (Some(v), None) => v,
+        (None, Some(p)) => p,
+        _ => panic!("Could not determine VSR API level"),
+    }
+}
+
 /// Determines whether the SECOND-IMEI can be used as device attest-id.
 pub fn is_second_imei_id_attestation_required(
     keystore2: &binder::Strong<dyn IKeystoreService>,
 ) -> bool {
-    let api_level = std::str::from_utf8(&get_system_prop("ro.vendor.api_level"))
-        .unwrap()
-        .parse::<i32>()
-        .unwrap();
-    keystore2.getInterfaceVersion().unwrap() >= 3 && api_level > 33
+    keystore2.getInterfaceVersion().unwrap() >= 3 && get_vsr_api_level() > 33
 }
 
 /// Run a service command and collect the output.
diff --git a/keystore2/tests/legacy_blobs/keystore2_legacy_blob_tests.rs b/keystore2/tests/legacy_blobs/keystore2_legacy_blob_tests.rs
index 0335159..3be99ee 100644
--- a/keystore2/tests/legacy_blobs/keystore2_legacy_blob_tests.rs
+++ b/keystore2/tests/legacy_blobs/keystore2_legacy_blob_tests.rs
@@ -46,6 +46,10 @@
 static AUTH_SERVICE_NAME: &str = "android.security.authorization";
 const SELINUX_SHELL_NAMESPACE: i64 = 1;
 
+fn rkp_only() -> bool {
+    matches!(rustutils::system_properties::read("remote_provisioning.tee.rkp_only"), Ok(Some(v)) if v == "1")
+}
+
 fn get_maintenance() -> binder::Strong<dyn IKeystoreMaintenance> {
     binder::get_interface(USER_MANAGER_SERVICE_NAME).unwrap()
 }
@@ -162,13 +166,13 @@
                 .getSecurityLevel(SecurityLevel::SecurityLevel::TRUSTED_ENVIRONMENT)
                 .unwrap();
             // Generate Key BLOB and prepare legacy keystore blob files.
-            let att_challenge: &[u8] = b"foo";
+            let att_challenge: Option<&[u8]> = if rkp_only() { None } else { Some(b"foo") };
             let key_metadata = key_generations::generate_ec_p256_signing_key(
                 &sec_level,
                 Domain::BLOB,
                 SELINUX_SHELL_NAMESPACE,
                 None,
-                Some(att_challenge),
+                att_challenge,
             )
             .expect("Failed to generate key blob");
 
@@ -212,14 +216,12 @@
                     .unwrap();
             }
 
-            let mut path_buf = PathBuf::from("/data/misc/keystore/user_99");
-            path_buf.push("9910001_CACERT_authbound");
-            if !path_buf.as_path().is_file() {
-                make_cert_blob_file(
-                    path_buf.as_path(),
-                    key_metadata.certificateChain.as_ref().unwrap(),
-                )
-                .unwrap();
+            if let Some(chain) = key_metadata.certificateChain.as_ref() {
+                let mut path_buf = PathBuf::from("/data/misc/keystore/user_99");
+                path_buf.push("9910001_CACERT_authbound");
+                if !path_buf.as_path().is_file() {
+                    make_cert_blob_file(path_buf.as_path(), chain).unwrap();
+                }
             }
 
             // Keystore2 disables the legacy importer when it finds the legacy database empty.
@@ -246,7 +248,7 @@
 
             KeygenResult {
                 cert: key_metadata.certificate.unwrap(),
-                cert_chain: key_metadata.certificateChain.unwrap(),
+                cert_chain: key_metadata.certificateChain.unwrap_or_default(),
                 key_parameters: key_params,
             }
         })
@@ -275,7 +277,7 @@
                         gen_key_result.cert
                     );
                     assert_eq!(
-                        key_entry_response.metadata.certificateChain.unwrap(),
+                        key_entry_response.metadata.certificateChain.unwrap_or_default(),
                         gen_key_result.cert_chain
                     );
                     assert_eq!(key_entry_response.metadata.key.domain, Domain::KEY_ID);
@@ -415,13 +417,13 @@
                 .getSecurityLevel(SecurityLevel::SecurityLevel::TRUSTED_ENVIRONMENT)
                 .unwrap();
             // Generate Key BLOB and prepare legacy keystore blob files.
-            let att_challenge: &[u8] = b"foo";
+            let att_challenge: Option<&[u8]> = if rkp_only() { None } else { Some(b"foo") };
             let key_metadata = key_generations::generate_ec_p256_signing_key(
                 &sec_level,
                 Domain::BLOB,
                 SELINUX_SHELL_NAMESPACE,
                 None,
-                Some(att_challenge),
+                att_challenge,
             )
             .expect("Failed to generate key blob");
 
@@ -468,15 +470,12 @@
                 .unwrap();
             }
 
-            let mut path_buf = PathBuf::from("/data/misc/keystore/user_98");
-            path_buf.push("9810001_CACERT_authboundcertenc");
-            if !path_buf.as_path().is_file() {
-                make_encrypted_ca_cert_file(
-                    path_buf.as_path(),
-                    &super_key,
-                    key_metadata.certificateChain.as_ref().unwrap(),
-                )
-                .unwrap();
+            if let Some(chain) = key_metadata.certificateChain.as_ref() {
+                let mut path_buf = PathBuf::from("/data/misc/keystore/user_98");
+                path_buf.push("9810001_CACERT_authboundcertenc");
+                if !path_buf.as_path().is_file() {
+                    make_encrypted_ca_cert_file(path_buf.as_path(), &super_key, chain).unwrap();
+                }
             }
 
             // Keystore2 disables the legacy importer when it finds the legacy database empty.
@@ -503,7 +502,7 @@
 
             KeygenResult {
                 cert: key_metadata.certificate.unwrap(),
-                cert_chain: key_metadata.certificateChain.unwrap(),
+                cert_chain: key_metadata.certificateChain.unwrap_or_default(),
                 key_parameters: key_params,
             }
         })
@@ -532,7 +531,7 @@
                         gen_key_result.cert
                     );
                     assert_eq!(
-                        key_entry_response.metadata.certificateChain.unwrap(),
+                        key_entry_response.metadata.certificateChain.unwrap_or_default(),
                         gen_key_result.cert_chain
                     );
 
diff --git a/provisioner/Android.bp b/provisioner/Android.bp
index d0c934d..ede1ae6 100644
--- a/provisioner/Android.bp
+++ b/provisioner/Android.bp
@@ -39,7 +39,7 @@
         "android.hardware.drm-V1-ndk",
         "android.hardware.security.rkp-V3-ndk",
         "libbase",
-        "libcppbor_external",
+        "libcppbor",
         "libcppcose_rkp",
         "libjsoncpp",
         "libkeymint_remote_prov_support",