Merge "Add tests covering android.system.keystore2.IKeystoreOperation::abort API." into main
diff --git a/keystore2/Android.bp b/keystore2/Android.bp
index c482e84..5726078 100644
--- a/keystore2/Android.bp
+++ b/keystore2/Android.bp
@@ -56,7 +56,6 @@
"libkeystore2_hal_names_rust",
"libkeystore2_km_compat",
"libkeystore2_selinux",
- "liblazy_static",
"liblibc",
"liblog_rust",
"libmessage_macro",
diff --git a/keystore2/apc_compat/apc_compat.cpp b/keystore2/apc_compat/apc_compat.cpp
index ffe7595..0ff2fc5 100644
--- a/keystore2/apc_compat/apc_compat.cpp
+++ b/keystore2/apc_compat/apc_compat.cpp
@@ -26,6 +26,7 @@
#include <android/binder_manager.h>
#include <memory>
+#include <set>
#include <string>
#include <thread>
#include <vector>
@@ -214,6 +215,14 @@
return nullptr;
}
+ class DeathRecipientCookie {
+ public:
+ DeathRecipientCookie(std::weak_ptr<ConfuiAidlCompatSession> session)
+ : mAidlSession(session) {}
+ DeathRecipientCookie() = delete;
+ std::weak_ptr<ConfuiAidlCompatSession> mAidlSession;
+ };
+
uint32_t promptUserConfirmation(ApcCompatCallback callback, const char* prompt_text,
const uint8_t* extra_data, size_t extra_data_size,
const char* locale, ApcCompatUiOptions ui_options) {
@@ -234,12 +243,19 @@
if (!aidlService_) {
return APC_COMPAT_ERROR_SYSTEM_ERROR;
}
- auto linkRet =
- AIBinder_linkToDeath(aidlService_->asBinder().get(), death_recipient_.get(), this);
- if (linkRet != STATUS_OK) {
- LOG(ERROR) << "Communication error: promptUserConfirmation: "
- "Trying to register death recipient: ";
- return APC_COMPAT_ERROR_SYSTEM_ERROR;
+
+ {
+ auto cookieLock = std::lock_guard(deathRecipientCookie_lock_);
+ void* cookie = new DeathRecipientCookie(this->ref<ConfuiAidlCompatSession>());
+ auto linkRet = AIBinder_linkToDeath(aidlService_->asBinder().get(),
+ death_recipient_.get(), cookie);
+ if (linkRet != STATUS_OK) {
+ LOG(ERROR) << "Communication error: promptUserConfirmation: "
+ "Trying to register death recipient: ";
+ delete static_cast<DeathRecipientCookie*>(cookie);
+ return APC_COMPAT_ERROR_SYSTEM_ERROR;
+ }
+ deathRecipientCookie_.insert(cookie);
}
auto rc = aidlService_->promptUserConfirmation(ref<ConfuiAidlCompatSession>(), aidl_prompt,
@@ -275,8 +291,21 @@
if (callback.result != nullptr) {
if (aidlService_) {
- AIBinder_unlinkToDeath(aidlService_->asBinder().get(), death_recipient_.get(),
- this);
+ // unlink all of the registered death recipients in case there
+ // were multiple calls to promptUserConfirmation before a call
+ // to finalize
+ std::set<void*> cookiesToUnlink;
+ {
+ auto cookieLock = std::lock_guard(deathRecipientCookie_lock_);
+ cookiesToUnlink = deathRecipientCookie_;
+ deathRecipientCookie_.clear();
+ }
+
+ // Unlink these outside of the lock
+ for (void* cookie : cookiesToUnlink) {
+ AIBinder_unlinkToDeath(aidlService_->asBinder().get(), death_recipient_.get(),
+ cookie);
+ }
}
CompatSessionCB::finalize(responseCode2Compat(responseCode), callback, dataConfirmed,
confirmationToken);
@@ -293,17 +322,46 @@
void serviceDied() {
aidlService_.reset();
aidlService_ = nullptr;
+ {
+ std::lock_guard lock(deathRecipientCookie_lock_);
+ deathRecipientCookie_.clear();
+ }
finalize(AidlConfirmationUI::SYSTEM_ERROR, {}, {});
}
- static void binderDiedCallbackAidl(void* ptr) {
- LOG(ERROR) << __func__ << " : ConfuiAidlCompatSession Service died.";
- auto aidlSession = static_cast<ConfuiAidlCompatSession*>(ptr);
- if (aidlSession == nullptr) {
- LOG(ERROR) << __func__ << ": Null ConfuiAidlCompatSession HAL died.";
- return;
+ void serviceUnlinked(void* cookie) {
+ {
+ std::lock_guard lock(deathRecipientCookie_lock_);
+ deathRecipientCookie_.erase(cookie);
}
- aidlSession->serviceDied();
+ }
+
+ static void binderDiedCallbackAidl(void* ptr) {
+ auto aidlSessionCookie = static_cast<ConfuiAidlCompatSession::DeathRecipientCookie*>(ptr);
+ if (aidlSessionCookie == nullptr) {
+ LOG(ERROR) << __func__ << ": Null cookie for binderDiedCallbackAidl when HAL died!";
+ return;
+ } else if (auto aidlSession = aidlSessionCookie->mAidlSession.lock();
+ aidlSession != nullptr) {
+ LOG(WARNING) << __func__ << " : Notififying ConfuiAidlCompatSession Service died.";
+ aidlSession->serviceDied();
+ } else {
+ LOG(ERROR) << __func__
+ << " : ConfuiAidlCompatSession Service died but object is no longer around "
+ "to be able to notify.";
+ }
+ }
+
+ static void binderUnlinkedCallbackAidl(void* ptr) {
+ auto aidlSessionCookie = static_cast<ConfuiAidlCompatSession::DeathRecipientCookie*>(ptr);
+ if (aidlSessionCookie == nullptr) {
+ LOG(ERROR) << __func__ << ": Null cookie!";
+ return;
+ } else if (auto aidlSession = aidlSessionCookie->mAidlSession.lock();
+ aidlSession != nullptr) {
+ aidlSession->serviceUnlinked(ptr);
+ }
+ delete aidlSessionCookie;
}
int getReturnCode(const ::ndk::ScopedAStatus& result) {
@@ -343,6 +401,7 @@
: aidlService_(service), callback_{nullptr, nullptr} {
death_recipient_ = ::ndk::ScopedAIBinder_DeathRecipient(
AIBinder_DeathRecipient_new(binderDiedCallbackAidl));
+ AIBinder_DeathRecipient_setOnUnlinked(death_recipient_.get(), binderUnlinkedCallbackAidl);
}
virtual ~ConfuiAidlCompatSession() = default;
@@ -351,6 +410,8 @@
private:
std::shared_ptr<AidlConfirmationUI> aidlService_;
+ std::mutex deathRecipientCookie_lock_;
+ std::set<void*> deathRecipientCookie_;
// The callback_lock_ protects the callback_ field against concurrent modification.
// IMPORTANT: It must never be held while calling the call back.
diff --git a/keystore2/selinux/Android.bp b/keystore2/selinux/Android.bp
index 254f95e..8e644e6 100644
--- a/keystore2/selinux/Android.bp
+++ b/keystore2/selinux/Android.bp
@@ -34,7 +34,6 @@
rustlibs: [
"libanyhow",
- "liblazy_static",
"liblog_rust",
"libselinux_bindgen",
"libthiserror",
@@ -57,7 +56,6 @@
rustlibs: [
"libandroid_logger",
"libanyhow",
- "liblazy_static",
"liblog_rust",
"libselinux_bindgen",
"libthiserror",
@@ -77,7 +75,6 @@
"libandroid_logger",
"libanyhow",
"libkeystore2_selinux",
- "liblazy_static",
"liblog_rust",
"libnix",
"libnum_cpus",
diff --git a/keystore2/selinux/src/lib.rs b/keystore2/selinux/src/lib.rs
index d7596a0..d57a99a 100644
--- a/keystore2/selinux/src/lib.rs
+++ b/keystore2/selinux/src/lib.rs
@@ -26,7 +26,6 @@
use anyhow::Context as AnyhowContext;
use anyhow::{anyhow, Result};
-use lazy_static::lazy_static;
pub use selinux::pid_t;
use selinux::SELABEL_CTX_ANDROID_KEYSTORE2_KEY;
use selinux::SELINUX_CB_LOG;
@@ -42,15 +41,13 @@
static SELINUX_LOG_INIT: sync::Once = sync::Once::new();
-lazy_static! {
- /// `selinux_check_access` is only thread safe if avc_init was called with lock callbacks.
- /// However, avc_init is deprecated and not exported by androids version of libselinux.
- /// `selinux_set_callbacks` does not allow setting lock callbacks. So the only option
- /// that remains right now is to put a big lock around calls into libselinux.
- /// TODO b/188079221 It should suffice to protect `selinux_check_access` but until we are
- /// certain of that, we leave the extra locks in place
- static ref LIB_SELINUX_LOCK: sync::Mutex<()> = Default::default();
-}
+/// `selinux_check_access` is only thread safe if avc_init was called with lock callbacks.
+/// However, avc_init is deprecated and not exported by androids version of libselinux.
+/// `selinux_set_callbacks` does not allow setting lock callbacks. So the only option
+/// that remains right now is to put a big lock around calls into libselinux.
+/// TODO b/188079221 It should suffice to protect `selinux_check_access` but until we are
+/// certain of that, we leave the extra locks in place
+static LIB_SELINUX_LOCK: sync::Mutex<()> = sync::Mutex::new(());
fn redirect_selinux_logs_to_logcat() {
// `selinux_set_callback` assigns the static lifetime function pointer
diff --git a/keystore2/src/database.rs b/keystore2/src/database.rs
index 03bf401..8165c54 100644
--- a/keystore2/src/database.rs
+++ b/keystore2/src/database.rs
@@ -70,12 +70,11 @@
};
use anyhow::{anyhow, Context, Result};
use keystore2_flags;
-use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
+use std::{convert::TryFrom, convert::TryInto, ops::Deref, sync::LazyLock, time::SystemTimeError};
use utils as db_utils;
use utils::SqlField;
use keystore2_crypto::ZVec;
-use lazy_static::lazy_static;
use log::error;
#[cfg(not(test))]
use rand::prelude::random;
@@ -529,9 +528,7 @@
}
}
-lazy_static! {
- static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
-}
+static KEY_ID_LOCK: LazyLock<KeyIdLockDb> = LazyLock::new(KeyIdLockDb::new);
struct KeyIdLockDb {
locked_keys: Mutex<HashSet<i64>>,
diff --git a/keystore2/src/database/perboot.rs b/keystore2/src/database/perboot.rs
index 4727015..a1890a6 100644
--- a/keystore2/src/database/perboot.rs
+++ b/keystore2/src/database/perboot.rs
@@ -19,9 +19,9 @@
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::Arc;
+use std::sync::LazyLock;
use std::sync::RwLock;
#[derive(PartialEq, PartialOrd, Ord, Eq, Hash)]
@@ -70,11 +70,9 @@
auth_tokens: RwLock<HashSet<AuthTokenEntryWrap>>,
}
-lazy_static! {
- /// The global instance of the perboot DB. Located here rather than in globals
- /// in order to restrict access to the database module.
- pub static ref PERBOOT_DB: Arc<PerbootDB> = Arc::new(PerbootDB::new());
-}
+/// The global instance of the perboot DB. Located here rather than in globals
+/// in order to restrict access to the database module.
+pub static PERBOOT_DB: LazyLock<Arc<PerbootDB>> = LazyLock::new(|| Arc::new(PerbootDB::new()));
impl PerbootDB {
/// Construct a new perboot database. Currently just uses default values.
diff --git a/keystore2/src/globals.rs b/keystore2/src/globals.rs
index bde83fd..39d6f9c 100644
--- a/keystore2/src/globals.rs
+++ b/keystore2/src/globals.rs
@@ -46,8 +46,7 @@
use anyhow::{Context, Result};
use binder::FromIBinder;
use binder::{get_declared_instances, is_declared};
-use lazy_static::lazy_static;
-use std::sync::{Arc, Mutex, RwLock};
+use std::sync::{Arc, LazyLock, Mutex, RwLock};
use std::{cell::RefCell, sync::Once};
use std::{collections::HashMap, path::Path, path::PathBuf};
@@ -139,32 +138,36 @@
}
}
-lazy_static! {
- /// The path where keystore stores all its keys.
- pub static ref DB_PATH: RwLock<PathBuf> = RwLock::new(
- Path::new("/data/misc/keystore").to_path_buf());
- /// Runtime database of unwrapped super keys.
- pub static ref SUPER_KEY: Arc<RwLock<SuperKeyManager>> = Default::default();
- /// Map of KeyMint devices.
- static ref KEY_MINT_DEVICES: Mutex<DevicesMap<dyn IKeyMintDevice>> = Default::default();
- /// Timestamp service.
- static ref TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Default::default();
- /// A single on-demand worker thread that handles deferred tasks with two different
- /// priorities.
- pub static ref ASYNC_TASK: Arc<AsyncTask> = Default::default();
- /// Singleton for enforcements.
- pub static ref ENFORCEMENTS: Enforcements = Default::default();
- /// LegacyBlobLoader is initialized and exists globally.
- /// The same directory used by the database is used by the LegacyBlobLoader as well.
- pub static ref LEGACY_BLOB_LOADER: Arc<LegacyBlobLoader> = Arc::new(LegacyBlobLoader::new(
- &DB_PATH.read().expect("Could not determine database path for legacy blob loader")));
- /// Legacy migrator. Atomically migrates legacy blobs to the database.
- pub static ref LEGACY_IMPORTER: Arc<LegacyImporter> =
- Arc::new(LegacyImporter::new(Arc::new(Default::default())));
- /// Background thread which handles logging via statsd and logd
- pub static ref LOGS_HANDLER: Arc<AsyncTask> = Default::default();
+/// The path where keystore stores all its keys.
+pub static DB_PATH: LazyLock<RwLock<PathBuf>> =
+ LazyLock::new(|| RwLock::new(Path::new("/data/misc/keystore").to_path_buf()));
+/// Runtime database of unwrapped super keys.
+pub static SUPER_KEY: LazyLock<Arc<RwLock<SuperKeyManager>>> = LazyLock::new(Default::default);
+/// Map of KeyMint devices.
+static KEY_MINT_DEVICES: LazyLock<Mutex<DevicesMap<dyn IKeyMintDevice>>> =
+ LazyLock::new(Default::default);
+/// Timestamp service.
+static TIME_STAMP_DEVICE: Mutex<Option<Strong<dyn ISecureClock>>> = Mutex::new(None);
+/// A single on-demand worker thread that handles deferred tasks with two different
+/// priorities.
+pub static ASYNC_TASK: LazyLock<Arc<AsyncTask>> = LazyLock::new(Default::default);
+/// Singleton for enforcements.
+pub static ENFORCEMENTS: LazyLock<Enforcements> = LazyLock::new(Default::default);
+/// LegacyBlobLoader is initialized and exists globally.
+/// The same directory used by the database is used by the LegacyBlobLoader as well.
+pub static LEGACY_BLOB_LOADER: LazyLock<Arc<LegacyBlobLoader>> = LazyLock::new(|| {
+ Arc::new(LegacyBlobLoader::new(
+ &DB_PATH.read().expect("Could not determine database path for legacy blob loader"),
+ ))
+});
+/// Legacy migrator. Atomically migrates legacy blobs to the database.
+pub static LEGACY_IMPORTER: LazyLock<Arc<LegacyImporter>> =
+ LazyLock::new(|| Arc::new(LegacyImporter::new(Arc::new(Default::default()))));
+/// Background thread which handles logging via statsd and logd
+pub static LOGS_HANDLER: LazyLock<Arc<AsyncTask>> = LazyLock::new(Default::default);
- static ref GC: Arc<Gc> = Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
+static GC: LazyLock<Arc<Gc>> = LazyLock::new(|| {
+ Arc::new(Gc::new_init_with(ASYNC_TASK.clone(), || {
(
Box::new(|uuid, blob| {
let km_dev = get_keymint_dev_by_uuid(uuid).map(|(dev, _)| dev)?;
@@ -172,12 +175,15 @@
map_km_error(km_dev.deleteKey(blob))
.context(ks_err!("Trying to invalidate key blob."))
}),
- KeystoreDB::new(&DB_PATH.read().expect("Could not determine database path for GC"), None)
- .expect("Failed to open database"),
+ KeystoreDB::new(
+ &DB_PATH.read().expect("Could not determine database path for GC"),
+ None,
+ )
+ .expect("Failed to open database"),
SUPER_KEY.clone(),
)
- }));
-}
+ }))
+});
/// Determine the service name for a KeyMint device of the given security level
/// gotten by binder service from the device and determining what services
diff --git a/keystore2/src/legacy_blob.rs b/keystore2/src/legacy_blob.rs
index c27a050..e05e686 100644
--- a/keystore2/src/legacy_blob.rs
+++ b/keystore2/src/legacy_blob.rs
@@ -961,7 +961,7 @@
fn make_user_path_name(&self, user_id: u32) -> PathBuf {
let mut path = self.path.clone();
- path.push(&format!("user_{}", user_id));
+ path.push(format!("user_{}", user_id));
path
}
diff --git a/keystore2/src/metrics_store.rs b/keystore2/src/metrics_store.rs
index 5a76d04..895374c 100644
--- a/keystore2/src/metrics_store.rs
+++ b/keystore2/src/metrics_store.rs
@@ -44,18 +44,15 @@
SecurityLevel::SecurityLevel as MetricsSecurityLevel, Storage::Storage as MetricsStorage,
};
use anyhow::{anyhow, Context, Result};
-use lazy_static::lazy_static;
use std::collections::HashMap;
-use std::sync::Mutex;
+use std::sync::{LazyLock, Mutex};
// Note: Crash events are recorded at keystore restarts, based on the assumption that keystore only
// gets restarted after a crash, during a boot cycle.
const KEYSTORE_CRASH_COUNT_PROPERTY: &str = "keystore.crash_count";
-lazy_static! {
- /// Singleton for MetricsStore.
- pub static ref METRICS_STORE: MetricsStore = Default::default();
-}
+/// Singleton for MetricsStore.
+pub static METRICS_STORE: LazyLock<MetricsStore> = LazyLock::new(Default::default);
/// MetricsStore stores the <atom object, count> as <key, value> in the inner hash map,
/// indexed by the atom id, in the outer hash map.
diff --git a/keystore2/src/permission.rs b/keystore2/src/permission.rs
index d79445b..7bf17b5 100644
--- a/keystore2/src/permission.rs
+++ b/keystore2/src/permission.rs
@@ -26,11 +26,11 @@
};
use anyhow::Context as AnyhowContext;
use keystore2_selinux as selinux;
-use lazy_static::lazy_static;
use selinux::{implement_class, Backend, ClassPermission};
use std::cmp::PartialEq;
use std::convert::From;
use std::ffi::CStr;
+use std::sync::LazyLock;
// Replace getcon with a mock in the test situation
#[cfg(not(test))]
@@ -41,12 +41,10 @@
#[cfg(test)]
mod tests;
-lazy_static! {
- // Panicking here is allowed because keystore cannot function without this backend
- // and it would happen early and indicate a gross misconfiguration of the device.
- static ref KEYSTORE2_KEY_LABEL_BACKEND: selinux::KeystoreKeyBackend =
- selinux::KeystoreKeyBackend::new().unwrap();
-}
+// Panicking here is allowed because keystore cannot function without this backend
+// and it would happen early and indicate a gross misconfiguration of the device.
+static KEYSTORE2_KEY_LABEL_BACKEND: LazyLock<selinux::KeystoreKeyBackend> =
+ LazyLock::new(|| selinux::KeystoreKeyBackend::new().unwrap());
fn lookup_keystore2_key_context(namespace: i64) -> anyhow::Result<selinux::Context> {
KEYSTORE2_KEY_LABEL_BACKEND.lookup(&namespace.to_string())
diff --git a/keystore2/src/watchdog_helper.rs b/keystore2/src/watchdog_helper.rs
index 1072ac0..63383aa 100644
--- a/keystore2/src/watchdog_helper.rs
+++ b/keystore2/src/watchdog_helper.rs
@@ -17,8 +17,7 @@
/// This module provides helpers for simplified use of the watchdog module.
#[cfg(feature = "watchdog")]
pub mod watchdog {
- use lazy_static::lazy_static;
- use std::sync::Arc;
+ use std::sync::{Arc, LazyLock};
use std::time::Duration;
pub use watchdog_rs::WatchPoint;
use watchdog_rs::Watchdog;
@@ -28,10 +27,8 @@
const DEFAULT_TIMEOUT: Duration = Duration::from_millis(DEFAULT_TIMEOUT_MS);
- lazy_static! {
- /// A Watchdog thread, that can be used to create watch points.
- static ref WD: Arc<Watchdog> = Watchdog::new(Duration::from_secs(10));
- }
+ /// A Watchdog thread, that can be used to create watch points.
+ static WD: LazyLock<Arc<Watchdog>> = LazyLock::new(|| Watchdog::new(Duration::from_secs(10)));
/// Sets a watch point with `id` and a timeout of `millis` milliseconds.
pub fn watch_millis(id: &'static str, millis: u64) -> Option<WatchPoint> {
diff --git a/keystore2/test_utils/run_as.rs b/keystore2/test_utils/run_as.rs
index d39d069..2cd9fec 100644
--- a/keystore2/test_utils/run_as.rs
+++ b/keystore2/test_utils/run_as.rs
@@ -357,9 +357,12 @@
// Safety: run_as must be called from a single threaded process.
// This device test is run as a separate single threaded process.
unsafe {
- run_as(selinux::getcon().unwrap().to_str().unwrap(), getuid(), getgid(), || {
- panic!("Closure must panic.")
- })
+ run_as::<_, ()>(
+ selinux::getcon().unwrap().to_str().unwrap(),
+ getuid(),
+ getgid(),
+ || panic!("Closure must panic."),
+ )
};
}
diff --git a/keystore2/tests/legacy_blobs/Android.bp b/keystore2/tests/legacy_blobs/Android.bp
index 0f310f5..92d1307 100644
--- a/keystore2/tests/legacy_blobs/Android.bp
+++ b/keystore2/tests/legacy_blobs/Android.bp
@@ -38,7 +38,6 @@
"libkeystore2_crypto_rust",
"libkeystore2_test_utils",
"libkeystore2_with_test_utils",
- "liblazy_static",
"liblibc",
"libnix",
"librustutils",