keystore2: rename the ScreenLockBound superencryption keys and type

Rename the ScreenLockBound superencryption keys and superencryption type
to UnlockedDeviceRequired.  This avoids confusion about what "screen
lock bound" means and makes the terminology consistent with the
UnlockedDeviceRequired key parameter in the API.

Bug: 296464083
Test: atest -p --include-subdirs system/security/keystore2
Test: atest CtsKeystoreTestCases
Flag: exempt, mechanical refactoring and comment changes
Change-Id: I98f7716d05c06f8c6db0f3eb616fb6e780407c2d
diff --git a/keystore2/src/authorization.rs b/keystore2/src/authorization.rs
index de7f19a..f840189 100644
--- a/keystore2/src/authorization.rs
+++ b/keystore2/src/authorization.rs
@@ -191,7 +191,7 @@
                 ENFORCEMENTS.set_device_locked(user_id, true);
                 let mut skm = SUPER_KEY.write().unwrap();
                 DB.with(|db| {
-                    skm.lock_screen_lock_bound_key(
+                    skm.lock_unlocked_device_required_keys(
                         &mut db.borrow_mut(),
                         user_id as u32,
                         unlocking_sids.unwrap_or(&[]),
diff --git a/keystore2/src/enforcements.rs b/keystore2/src/enforcements.rs
index 61ec006..bb23b82 100644
--- a/keystore2/src/enforcements.rs
+++ b/keystore2/src/enforcements.rs
@@ -774,7 +774,7 @@
                     Candidate { priority: 3, enc_type: SuperEncryptionType::BootLevel(*level) }
                 }
                 KeyParameterValue::UnlockedDeviceRequired if *domain == Domain::APP => {
-                    Candidate { priority: 2, enc_type: SuperEncryptionType::ScreenLockBound }
+                    Candidate { priority: 2, enc_type: SuperEncryptionType::UnlockedDeviceRequired }
                 }
                 KeyParameterValue::UserSecureID(_) if *domain == Domain::APP => {
                     Candidate { priority: 1, enc_type: SuperEncryptionType::AfterFirstUnlock }
diff --git a/keystore2/src/maintenance.rs b/keystore2/src/maintenance.rs
index 1aa542a..ea48f4d 100644
--- a/keystore2/src/maintenance.rs
+++ b/keystore2/src/maintenance.rs
@@ -77,9 +77,9 @@
 
         if let Some(pw) = password.as_ref() {
             DB.with(|db| {
-                skm.unlock_screen_lock_bound_key(&mut db.borrow_mut(), user_id as u32, pw)
+                skm.unlock_unlocked_device_required_keys(&mut db.borrow_mut(), user_id as u32, pw)
             })
-            .context(ks_err!("unlock_screen_lock_bound_key failed"))?;
+            .context(ks_err!("unlock_unlocked_device_required_keys failed"))?;
         }
 
         if let UserState::BeforeFirstUnlock = DB
diff --git a/keystore2/src/super_key.rs b/keystore2/src/super_key.rs
index 57ea452..128cf4c 100644
--- a/keystore2/src/super_key.rs
+++ b/keystore2/src/super_key.rs
@@ -85,17 +85,17 @@
 /// keys that require user authentication but not an unlocked device.
 pub const USER_AFTER_FIRST_UNLOCK_SUPER_KEY: SuperKeyType =
     SuperKeyType { alias: "USER_SUPER_KEY", algorithm: SuperEncryptionAlgorithm::Aes256Gcm };
-/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
-/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
-/// Symmetric.
-pub const USER_SCREEN_LOCK_BOUND_KEY: SuperKeyType = SuperKeyType {
+/// The user's UnlockedDeviceRequired symmetric super key. This super key is loaded into memory each
+/// time the user unlocks the device, and it is cleared from memory each time the user locks the
+/// device. This is used to encrypt keys that use the UnlockedDeviceRequired key parameter.
+pub const USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY: SuperKeyType = SuperKeyType {
     alias: "USER_SCREEN_LOCK_BOUND_KEY",
     algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
 };
-/// Key used for ScreenLockBound keys; the corresponding superencryption key is loaded in memory
-/// each time the user enters their LSKF, and cleared from memory each time the device is locked.
-/// Asymmetric, so keys can be encrypted when the device is locked.
-pub const USER_SCREEN_LOCK_BOUND_P521_KEY: SuperKeyType = SuperKeyType {
+/// The user's UnlockedDeviceRequired asymmetric super key. This is used to allow, while the device
+/// is locked, the creation of keys that use the UnlockedDeviceRequired key parameter. The private
+/// part of this key is loaded and cleared when the symmetric key is loaded and cleared.
+pub const USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY: SuperKeyType = SuperKeyType {
     alias: "USER_SCREEN_LOCK_BOUND_P521_KEY",
     algorithm: SuperEncryptionAlgorithm::EcdhP521,
 };
@@ -107,8 +107,8 @@
     None,
     /// Superencrypt with the AfterFirstUnlock super key.
     AfterFirstUnlock,
-    /// Superencrypt with a key cleared from memory when the device is locked.
-    ScreenLockBound,
+    /// Superencrypt with an UnlockedDeviceRequired super key.
+    UnlockedDeviceRequired,
     /// Superencrypt with a key based on the desired boot level
     BootLevel(i32),
 }
@@ -225,17 +225,16 @@
     }
 }
 
-/// Keys for unlocking UNLOCKED_DEVICE_REQUIRED keys, as LockedKeys, complete with
-/// a database descriptor for the encrypting key and the sids for the auth tokens
-/// that can be used to decrypt it.
+/// A user's UnlockedDeviceRequired super keys, encrypted with a biometric-bound key, and
+/// information about that biometric-bound key.
 struct BiometricUnlock {
-    /// List of auth token SIDs that can be used to unlock these keys.
+    /// List of auth token SIDs that are accepted by the encrypting biometric-bound key.
     sids: Vec<i64>,
-    /// Database descriptor of key to use to unlock.
+    /// Key descriptor of the encrypting biometric-bound key.
     key_desc: KeyDescriptor,
-    /// Locked versions of the matching UserSuperKeys fields
-    screen_lock_bound: LockedKey,
-    screen_lock_bound_private: LockedKey,
+    /// The UnlockedDeviceRequired super keys, encrypted with a biometric-bound key.
+    symmetric: LockedKey,
+    private: LockedKey,
 }
 
 #[derive(Default)]
@@ -246,12 +245,12 @@
     /// user unlocks the device for the first time, this key is unlocked, i.e., decrypted, and stays
     /// memory resident until the device reboots.
     after_first_unlock: Option<Arc<SuperKey>>,
-    /// The screen lock key works like the per boot key with the distinction that it is cleared
-    /// from memory when the screen lock is engaged.
-    screen_lock_bound: Option<Arc<SuperKey>>,
-    /// When the device is locked, screen-lock-bound keys can still be encrypted, using
-    /// ECDH public-key encryption. This field holds the decryption private key.
-    screen_lock_bound_private: Option<Arc<SuperKey>>,
+    /// The UnlockedDeviceRequired symmetric super key works like the AfterFirstUnlock super key
+    /// with the distinction that it is cleared from memory when the device is locked.
+    unlocked_device_required_symmetric: Option<Arc<SuperKey>>,
+    /// When the device is locked, keys that use the UnlockedDeviceRequired key parameter can still
+    /// be created, using ECDH public-key encryption. This field holds the decryption private key.
+    unlocked_device_required_private: Option<Arc<SuperKey>>,
     /// Versions of the above two keys, locked behind a biometric.
     biometric_unlock: Option<BiometricUnlock>,
 }
@@ -599,7 +598,8 @@
     // the KeystoreDB and encrypts the key_blob using ECDH encryption and marks the keyblob to be
     // re-encrypted with the symmetric super key on the first use.
     //
-    // This hybrid scheme allows lock-screen-bound keys to be added when the screen is locked.
+    // This hybrid scheme allows keys that use the UnlockedDeviceRequired key parameter to be
+    // created while the device is locked.
     fn encrypt_with_hybrid_super_key(
         key_blob: &[u8],
         symmetric_key: Option<&SuperKey>,
@@ -608,8 +608,9 @@
         user_id: UserId,
     ) -> Result<(Vec<u8>, BlobMetaData)> {
         if let Some(super_key) = symmetric_key {
-            Self::encrypt_with_aes_super_key(key_blob, super_key)
-                .context(ks_err!("Failed to encrypt with ScreenLockBound super key."))
+            Self::encrypt_with_aes_super_key(key_blob, super_key).context(ks_err!(
+                "Failed to encrypt with UnlockedDeviceRequired symmetric super key."
+            ))
         } else {
             // Symmetric key is not available, use public key encryption
             let loaded = db
@@ -669,21 +670,21 @@
                         .context(ks_err!("LSKF is not setup for user {user_id}")),
                 }
             }
-            SuperEncryptionType::ScreenLockBound => {
-                let screen_lock_bound_symmetric_key = self
+            SuperEncryptionType::UnlockedDeviceRequired => {
+                let symmetric_key = self
                     .data
                     .user_keys
                     .get(&user_id)
-                    .and_then(|e| e.screen_lock_bound.as_ref())
+                    .and_then(|e| e.unlocked_device_required_symmetric.as_ref())
                     .map(|arc| arc.as_ref());
                 Self::encrypt_with_hybrid_super_key(
                     key_blob,
-                    screen_lock_bound_symmetric_key,
-                    &USER_SCREEN_LOCK_BOUND_P521_KEY,
+                    symmetric_key,
+                    &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
                     db,
                     user_id,
                 )
-                .context(ks_err!("Failed to encrypt with ScreenLockBound hybrid scheme."))
+                .context(ks_err!("Failed to encrypt with UnlockedDeviceRequired hybrid scheme."))
             }
             SuperEncryptionType::BootLevel(level) => {
                 let key_id = SuperKeyIdentifier::BootLevel(level);
@@ -776,43 +777,55 @@
         }
     }
 
-    /// Decrypt the screen-lock bound keys for this user using the password and store in memory.
-    pub fn unlock_screen_lock_bound_key(
+    /// Decrypt the UnlockedDeviceRequired super keys for this user using the password and store
+    /// them in memory. If these keys don't exist yet, create them.
+    pub fn unlock_unlocked_device_required_keys(
         &mut self,
         db: &mut KeystoreDB,
         user_id: UserId,
         password: &Password,
     ) -> Result<()> {
-        let (screen_lock_bound, screen_lock_bound_private) = self
+        let (symmetric, private) = self
             .data
             .user_keys
             .get(&user_id)
-            .map(|e| (e.screen_lock_bound.clone(), e.screen_lock_bound_private.clone()))
+            .map(|e| {
+                (
+                    e.unlocked_device_required_symmetric.clone(),
+                    e.unlocked_device_required_private.clone(),
+                )
+            })
             .unwrap_or((None, None));
 
-        if screen_lock_bound.is_some() && screen_lock_bound_private.is_some() {
+        if symmetric.is_some() && private.is_some() {
             // Already unlocked.
             return Ok(());
         }
 
-        let aes = if let Some(screen_lock_bound) = screen_lock_bound {
-            // This is weird. If this point is reached only one of the screen locked keys was
-            // initialized. This should never happen.
-            screen_lock_bound
-        } else {
-            self.get_or_create_super_key(db, user_id, &USER_SCREEN_LOCK_BOUND_KEY, password, None)
-                .context(ks_err!("Trying to get or create symmetric key."))?
-        };
-
-        let ecdh = if let Some(screen_lock_bound_private) = screen_lock_bound_private {
-            // This is weird. If this point is reached only one of the screen locked keys was
-            // initialized. This should never happen.
-            screen_lock_bound_private
+        let aes = if let Some(symmetric) = symmetric {
+            // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
+            // keys was initialized. This should never happen.
+            symmetric
         } else {
             self.get_or_create_super_key(
                 db,
                 user_id,
-                &USER_SCREEN_LOCK_BOUND_P521_KEY,
+                &USER_UNLOCKED_DEVICE_REQUIRED_SYMMETRIC_SUPER_KEY,
+                password,
+                None,
+            )
+            .context(ks_err!("Trying to get or create symmetric key."))?
+        };
+
+        let ecdh = if let Some(private) = private {
+            // This is weird. If this point is reached only one of the UnlockedDeviceRequired super
+            // keys was initialized. This should never happen.
+            private
+        } else {
+            self.get_or_create_super_key(
+                db,
+                user_id,
+                &USER_UNLOCKED_DEVICE_REQUIRED_P521_SUPER_KEY,
                 password,
                 Some(aes.clone()),
             )
@@ -822,24 +835,28 @@
         self.data.add_key_to_key_index(&aes)?;
         self.data.add_key_to_key_index(&ecdh)?;
         let entry = self.data.user_keys.entry(user_id).or_default();
-        entry.screen_lock_bound = Some(aes);
-        entry.screen_lock_bound_private = Some(ecdh);
+        entry.unlocked_device_required_symmetric = Some(aes);
+        entry.unlocked_device_required_private = Some(ecdh);
         Ok(())
     }
 
-    /// Wipe the screen-lock bound keys for this user from memory.
-    pub fn lock_screen_lock_bound_key(
+    /// Wipe the user's UnlockedDeviceRequired super keys from memory.
+    pub fn lock_unlocked_device_required_keys(
         &mut self,
         db: &mut KeystoreDB,
         user_id: UserId,
         unlocking_sids: &[i64],
     ) {
-        log::info!("Locking screen bound for user {} sids {:?}", user_id, unlocking_sids);
+        log::info!(
+            "Locking UnlockedDeviceRequired super keys for user {}; unlocking_sids={:?}",
+            user_id,
+            unlocking_sids
+        );
         let entry = self.data.user_keys.entry(user_id).or_default();
         if !unlocking_sids.is_empty() {
             if let (Some(aes), Some(ecdh)) = (
-                entry.screen_lock_bound.as_ref().cloned(),
-                entry.screen_lock_bound_private.as_ref().cloned(),
+                entry.unlocked_device_required_symmetric.as_ref().cloned(),
+                entry.unlocked_device_required_private.as_ref().cloned(),
             ) {
                 let res = (|| -> Result<()> {
                     let key_desc = KeyMintDevice::internal_descriptor(format!(
@@ -874,7 +891,7 @@
                         KeyType::Client, /* TODO Should be Super b/189470584 */
                         |dev| {
                             let _wp = wd::watch_millis(
-                                "In lock_screen_lock_bound_key: calling importKey.",
+                                "In lock_unlocked_device_required_keys: calling importKey.",
                                 500,
                             );
                             dev.importKey(
@@ -888,20 +905,20 @@
                     entry.biometric_unlock = Some(BiometricUnlock {
                         sids: unlocking_sids.into(),
                         key_desc,
-                        screen_lock_bound: LockedKey::new(&encrypting_key, &aes)?,
-                        screen_lock_bound_private: LockedKey::new(&encrypting_key, &ecdh)?,
+                        symmetric: LockedKey::new(&encrypting_key, &aes)?,
+                        private: LockedKey::new(&encrypting_key, &ecdh)?,
                     });
                     Ok(())
                 })();
-                // There is no reason to propagate an error here upwards. We must discard
-                // entry.screen_lock_bound* in any case.
+                // There is no reason to propagate an error here upwards. We must clear the keys
+                // from memory in any case.
                 if let Err(e) = res {
                     log::error!("Error setting up biometric unlock: {:#?}", e);
                 }
             }
         }
-        entry.screen_lock_bound = None;
-        entry.screen_lock_bound_private = None;
+        entry.unlocked_device_required_symmetric = None;
+        entry.unlocked_device_required_private = None;
     }
 
     /// User has unlocked, not using a password. See if any of our stored auth tokens can be used
@@ -931,7 +948,7 @@
                     entry.auth_token().userId == sid || entry.auth_token().authenticatorId == sid
                 }) {
                     let res: Result<(Arc<SuperKey>, Arc<SuperKey>)> = (|| {
-                        let slb = biometric.screen_lock_bound.decrypt(
+                        let symmetric = biometric.symmetric.decrypt(
                             db,
                             &km_dev,
                             &key_id_guard,
@@ -939,22 +956,22 @@
                             auth_token_entry.auth_token(),
                             None,
                         )?;
-                        let slbp = biometric.screen_lock_bound_private.decrypt(
+                        let private = biometric.private.decrypt(
                             db,
                             &km_dev,
                             &key_id_guard,
                             &key_entry,
                             auth_token_entry.auth_token(),
-                            Some(slb.clone()),
+                            Some(symmetric.clone()),
                         )?;
-                        Ok((slb, slbp))
+                        Ok((symmetric, private))
                     })();
                     match res {
-                        Ok((slb, slbp)) => {
-                            entry.screen_lock_bound = Some(slb.clone());
-                            entry.screen_lock_bound_private = Some(slbp.clone());
-                            self.data.add_key_to_key_index(&slb)?;
-                            self.data.add_key_to_key_index(&slbp)?;
+                        Ok((symmetric, private)) => {
+                            entry.unlocked_device_required_symmetric = Some(symmetric.clone());
+                            entry.unlocked_device_required_private = Some(private.clone());
+                            self.data.add_key_to_key_index(&symmetric)?;
+                            self.data.add_key_to_key_index(&private)?;
                             log::info!("Successfully unlocked user {user_id} with biometric {sid}",);
                             return Ok(());
                         }
@@ -1104,10 +1121,10 @@
     ///
     /// If the user state is BeforeFirstUnlock:
     /// - Unlock the user's AfterFirstUnlock super key
-    /// - Unlock the screen_lock_bound super key
+    /// - Unlock the user's UnlockedDeviceRequired super keys
     ///
     /// If the user state is AfterFirstUnlock:
-    /// - Unlock the screen_lock_bound super key only
+    /// - Unlock the user's UnlockedDeviceRequired super keys only
     ///
     pub fn unlock_user(
         &mut self,
@@ -1119,7 +1136,7 @@
         log::info!("unlock_user(user={user_id})");
         match self.get_user_state(db, legacy_importer, user_id)? {
             UserState::AfterFirstUnlock(_) => {
-                self.unlock_screen_lock_bound_key(db, user_id, password)
+                self.unlock_unlocked_device_required_keys(db, user_id, password)
             }
             UserState::Uninitialized => {
                 Err(Error::sys()).context(ks_err!("Tried to unlock an uninitialized user!"))
@@ -1141,7 +1158,7 @@
                             password,
                         )
                         .context(ks_err!("Failed when unlocking user."))?;
-                        self.unlock_screen_lock_bound_key(db, user_id, password)
+                        self.unlock_unlocked_device_required_keys(db, user_id, password)
                     }
                     None => {
                         Err(Error::sys()).context(ks_err!("Locked user does not have a super key!"))