Log key import, generation, deletion for NIAP

Bug: 183201685
Test: atest MixedDeviceOwnerTest#testSecurityLoggingWithSingleUser
Change-Id: Ie4271a769c8a8c3241079cd15efed4e3b9e9468b
diff --git a/keystore2/Android.bp b/keystore2/Android.bp
index dfc1db0..8d0f4e7 100644
--- a/keystore2/Android.bp
+++ b/keystore2/Android.bp
@@ -50,6 +50,7 @@
         "liblazy_static",
         "liblibc",
         "liblibsqlite3_sys",
+        "liblog_event_list",
         "liblog_rust",
         "librand",
         "librusqlite",
diff --git a/keystore2/src/audit_log.rs b/keystore2/src/audit_log.rs
new file mode 100644
index 0000000..30fc155
--- /dev/null
+++ b/keystore2/src/audit_log.rs
@@ -0,0 +1,68 @@
+// Copyright 2021, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! This module implements functions to log audit events to binary security log buffer for NIAP
+//! compliance.
+
+use crate::globals::LOGS_HANDLER;
+use android_system_keystore2::aidl::android::system::keystore2::{
+    Domain::Domain, KeyDescriptor::KeyDescriptor,
+};
+use libc::uid_t;
+use log_event_list::{LogContext, LogIdSecurity};
+
+const TAG_KEY_GENERATED: u32 = 210024;
+const TAG_KEY_IMPORTED: u32 = 210025;
+const TAG_KEY_DESTROYED: u32 = 210026;
+
+const NAMESPACE_MASK: 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,
+        _ => {
+            log::info!("Not logging audit event for key with unexpected domain");
+            0
+        }
+    }
+}
+
+/// Logs key generation event to NIAP audit log.
+pub fn log_key_generated(key: &KeyDescriptor, calling_app: uid_t, success: bool) {
+    log_key_event(TAG_KEY_GENERATED, key, calling_app, success);
+}
+
+/// Logs key import event to NIAP audit log.
+pub fn log_key_imported(key: &KeyDescriptor, calling_app: uid_t, success: bool) {
+    log_key_event(TAG_KEY_IMPORTED, key, calling_app, success);
+}
+
+/// Logs key deletion event to NIAP audit log.
+pub fn log_key_deleted(key: &KeyDescriptor, calling_app: uid_t, success: bool) {
+    log_key_event(TAG_KEY_DESTROYED, key, calling_app, success);
+}
+
+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 })
+            .append_str(key.alias.as_ref().map_or("none", String::as_str))
+            .append_i32(key_owner(key, calling_app));
+        LOGS_HANDLER.queue_lo(move |_| {
+            event.write();
+        });
+    }
+}
diff --git a/keystore2/src/globals.rs b/keystore2/src/globals.rs
index 58142a4..9f38799 100644
--- a/keystore2/src/globals.rs
+++ b/keystore2/src/globals.rs
@@ -173,6 +173,8 @@
     /// Legacy migrator. Atomically migrates legacy blobs to the database.
     pub static ref LEGACY_MIGRATOR: Arc<LegacyMigrator> =
         Arc::new(LegacyMigrator::new(ASYNC_TASK.clone()));
+    /// Background thread which handles logging via statsd and logd
+    pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
 }
 
 static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
diff --git a/keystore2/src/lib.rs b/keystore2/src/lib.rs
index f851d3a..0ce83e6 100644
--- a/keystore2/src/lib.rs
+++ b/keystore2/src/lib.rs
@@ -42,6 +42,7 @@
 pub mod utils;
 
 mod attestation_key_utils;
+mod audit_log;
 mod db_utils;
 mod gc;
 mod super_key;
diff --git a/keystore2/src/metrics.rs b/keystore2/src/metrics.rs
index 5b66307..07c3d64 100644
--- a/keystore2/src/metrics.rs
+++ b/keystore2/src/metrics.rs
@@ -13,9 +13,8 @@
 // limitations under the License.
 
 //! This module provides convenience functions for keystore2 logging.
-use crate::async_task::AsyncTask;
 use crate::error::get_error_code;
-use crate::globals::DB;
+use crate::globals::{DB, LOGS_HANDLER};
 use crate::key_parameter::KeyParameterValue as KsKeyParamValue;
 use crate::operation::Outcome;
 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
@@ -26,7 +25,6 @@
 };
 use anyhow::Result;
 use keystore2_system_property::PropertyWatcher;
-use lazy_static::lazy_static;
 use statslog_rust::{
     keystore2_key_creation_event_reported::{
         Algorithm as StatsdAlgorithm, EcCurve as StatsdEcCurve, KeyOrigin as StatsdKeyOrigin,
@@ -42,11 +40,6 @@
 use statslog_rust_header::Atoms;
 use statspull_rust::{set_pull_atom_callback, StatsPullResult};
 
-lazy_static! {
-    /// Background thread which handles logging via statsd
-    static ref STATSD_LOGS_HANDLER: AsyncTask = Default::default();
-}
-
 fn create_default_key_creation_atom() -> Keystore2KeyCreationEventReported {
     // If a value is not present, fields represented by bitmaps and i32 fields
     // will take 0, except error_code which defaults to 1 indicating NO_ERROR and key_size,
@@ -95,7 +88,7 @@
     let key_creation_event_stats =
         construct_key_creation_event_stats(sec_level, key_params, result);
 
-    STATSD_LOGS_HANDLER.queue_lo(move |_| {
+    LOGS_HANDLER.queue_lo(move |_| {
         let logging_result = key_creation_event_stats.stats_write();
 
         if let Err(e) = logging_result {
@@ -120,7 +113,7 @@
         key_upgraded,
     );
 
-    STATSD_LOGS_HANDLER.queue_lo(move |_| {
+    LOGS_HANDLER.queue_lo(move |_| {
         let logging_result = key_operation_event_stats.stats_write();
 
         if let Err(e) = logging_result {
diff --git a/keystore2/src/security_level.rs b/keystore2/src/security_level.rs
index 03514b3..e8760dc 100644
--- a/keystore2/src/security_level.rs
+++ b/keystore2/src/security_level.rs
@@ -32,6 +32,7 @@
 };
 
 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::database::{CertificateInfo, KeyIdGuard};
 use crate::globals::{DB, ENFORCEMENTS, LEGACY_MIGRATOR, SUPER_KEY};
 use crate::key_parameter::KeyParameter as KsKeyParam;
@@ -877,6 +878,7 @@
     ) -> binder::public_api::Result<KeyMetadata> {
         let result = self.generate_key(key, attestation_key, params, flags, entropy);
         log_key_creation_event_stats(self.security_level, params, &result);
+        log_key_generated(key, ThreadState::get_calling_uid(), result.is_ok());
         map_or_log_err(result, Ok)
     }
     fn importKey(
@@ -889,6 +891,7 @@
     ) -> binder::public_api::Result<KeyMetadata> {
         let result = self.import_key(key, attestation_key, params, flags, key_data);
         log_key_creation_event_stats(self.security_level, params, &result);
+        log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
         map_or_log_err(result, Ok)
     }
     fn importWrappedKey(
@@ -902,6 +905,7 @@
         let result =
             self.import_wrapped_key(key, wrapping_key, masking_key, params, authenticators);
         log_key_creation_event_stats(self.security_level, params, &result);
+        log_key_imported(key, ThreadState::get_calling_uid(), result.is_ok());
         map_or_log_err(result, Ok)
     }
     fn convertStorageKeyToEphemeral(
@@ -911,6 +915,8 @@
         map_or_log_err(self.convert_storage_key_to_ephemeral(storage_key), Ok)
     }
     fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
-        map_or_log_err(self.delete_key(key), Ok)
+        let result = self.delete_key(key);
+        log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
+        map_or_log_err(result, Ok)
     }
 }
diff --git a/keystore2/src/service.rs b/keystore2/src/service.rs
index 8d3b66e..b8ea244 100644
--- a/keystore2/src/service.rs
+++ b/keystore2/src/service.rs
@@ -17,6 +17,7 @@
 
 use std::collections::HashMap;
 
+use crate::audit_log::log_key_deleted;
 use crate::permission::{KeyPerm, KeystorePerm};
 use crate::security_level::KeystoreSecurityLevel;
 use crate::utils::{
@@ -374,7 +375,9 @@
         map_or_log_err(self.list_entries(domain, namespace), Ok)
     }
     fn deleteKey(&self, key: &KeyDescriptor) -> binder::public_api::Result<()> {
-        map_or_log_err(self.delete_key(key), Ok)
+        let result = self.delete_key(key);
+        log_key_deleted(key, ThreadState::get_calling_uid(), result.is_ok());
+        map_or_log_err(result, Ok)
     }
     fn grant(
         &self,