Log key integrity violation to NIAP audit log.

Bug: 183201685
Test: atest MixedDeviceOwnerTest#testSecurityLoggingWithSingleUser
Test: atest keystore2_test
Change-Id: Ic2dbbae818e88c520600c21c5d108cdc4dfca104
diff --git a/keystore2/src/audit_log.rs b/keystore2/src/audit_log.rs
index 30fc155..3d7d26e 100644
--- a/keystore2/src/audit_log.rs
+++ b/keystore2/src/audit_log.rs
@@ -25,14 +25,15 @@
 const TAG_KEY_GENERATED: u32 = 210024;
 const TAG_KEY_IMPORTED: u32 = 210025;
 const TAG_KEY_DESTROYED: u32 = 210026;
+const TAG_KEY_INTEGRITY_VIOLATION: u32 = 210032;
 
-const NAMESPACE_MASK: i64 = 0x80000000;
+const FLAG_NAMESPACE: i64 = 0x80000000;
 
-/// For app domain returns calling app uid, for SELinux domain returns masked namespace.
-fn key_owner(key: &KeyDescriptor, calling_app: uid_t) -> i32 {
-    match key.domain {
-        Domain::APP => calling_app as i32,
-        Domain::SELINUX => (key.nspace | NAMESPACE_MASK) as i32,
+/// Encode key owner as either uid or namespace with a flag.
+fn key_owner(domain: Domain, nspace: i64, uid: i32) -> i32 {
+    match domain {
+        Domain::APP => uid,
+        Domain::SELINUX => (nspace | FLAG_NAMESPACE) as i32,
         _ => {
             log::info!("Not logging audit event for key with unexpected domain");
             0
@@ -55,12 +56,29 @@
     log_key_event(TAG_KEY_DESTROYED, key, calling_app, success);
 }
 
+/// 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)
+    })
+}
+
 fn log_key_event(tag: u32, key: &KeyDescriptor, calling_app: uid_t, success: bool) {
-    if let Some(ctx) = LogContext::new(LogIdSecurity, tag) {
-        let event = ctx
-            .append_i32(if success { 1 } else { 0 })
+    with_log_context(tag, |ctx| {
+        let owner = key_owner(key.domain, key.nspace, calling_app as i32);
+        ctx.append_i32(if success { 1 } else { 0 })
             .append_str(key.alias.as_ref().map_or("none", String::as_str))
-            .append_i32(key_owner(key, calling_app));
+            .append_i32(owner)
+    })
+}
+
+fn with_log_context<F>(tag: u32, f: F)
+where
+    F: Fn(LogContext) -> LogContext,
+{
+    if let Some(ctx) = LogContext::new(LogIdSecurity, tag) {
+        let event = f(ctx);
         LOGS_HANDLER.queue_lo(move |_| {
             event.write();
         });
diff --git a/keystore2/src/database.rs b/keystore2/src/database.rs
index 073799b..876f4ce 100644
--- a/keystore2/src/database.rs
+++ b/keystore2/src/database.rs
@@ -3159,6 +3159,30 @@
     fn get_last_off_body(&self) -> MonotonicRawTime {
         self.perboot.get_last_off_body()
     }
+
+    /// Load descriptor of a key by key id
+    pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
+        let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
+
+        self.with_transaction(TransactionBehavior::Deferred, |tx| {
+            tx.query_row(
+                "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
+                params![key_id],
+                |row| {
+                    Ok(KeyDescriptor {
+                        domain: Domain(row.get(0)?),
+                        nspace: row.get(1)?,
+                        alias: row.get(2)?,
+                        blob: None,
+                    })
+                },
+            )
+            .optional()
+            .context("Trying to load key descriptor")
+            .no_gc()
+        })
+        .context("In load_key_descriptor.")
+    }
 }
 
 #[cfg(test)]
@@ -5511,4 +5535,20 @@
         assert_eq!(mode, "wal");
         Ok(())
     }
+
+    #[test]
+    fn test_load_key_descriptor() -> Result<()> {
+        let mut db = new_test_db()?;
+        let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
+
+        let key = db.load_key_descriptor(key_id)?.unwrap();
+
+        assert_eq!(key.domain, Domain::APP);
+        assert_eq!(key.nspace, 1);
+        assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
+
+        // No such id
+        assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
+        Ok(())
+    }
 }
diff --git a/keystore2/src/security_level.rs b/keystore2/src/security_level.rs
index d10aba0..00b26e4 100644
--- a/keystore2/src/security_level.rs
+++ b/keystore2/src/security_level.rs
@@ -15,7 +15,9 @@
 //! This crate implements the IKeystoreSecurityLevel interface.
 
 use crate::attestation_key_utils::{get_attest_key_info, AttestationKeyInfo};
-use crate::audit_log::{log_key_deleted, log_key_generated, log_key_imported};
+use crate::audit_log::{
+    log_key_deleted, log_key_generated, log_key_imported, log_key_integrity_violation,
+};
 use crate::database::{CertificateInfo, KeyIdGuard};
 use crate::error::{self, map_km_error, map_or_log_err, Error, ErrorCode};
 use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
@@ -325,6 +327,18 @@
                             self.operation_db.prune(caller_uid, forced)?;
                             continue;
                         }
+                        v @ Err(Error::Km(ErrorCode::INVALID_KEY_BLOB)) => {
+                            if let Some((key_id, _)) = key_properties {
+                                if let Ok(Some(key)) =
+                                    DB.with(|db| db.borrow_mut().load_key_descriptor(key_id))
+                                {
+                                    log_key_integrity_violation(&key);
+                                } else {
+                                    log::error!("Failed to load key descriptor for audit log");
+                                }
+                            }
+                            return v;
+                        }
                         v => return v,
                     }
                 },