keystore2: rename MonotonicRawTime to BootTime

Due to https://r.android.com/2822970 ("Use CLOCK_BOOTTIME for keystore2
auth token received time"), MonotonicRawTime now uses CLOCK_BOOTTIME
instead of CLOCK_MONOTONIC_RAW.  Therefore, rename it to BootTime.

Bug: 309686873
Test: atest -p --include-subdirs system/security/keystore2
Change-Id: If1fbbac2eccb03dc7360ae742d79e58f871fb80d
This commit is contained in:
Eric Biggers 2024-01-31 22:46:47 +00:00
parent 53d2763a23
commit 19b3b0d894
5 changed files with 33 additions and 35 deletions

View file

@ -761,22 +761,22 @@ pub struct KeystoreDB {
}
/// Database representation of the monotonic time retrieved from the system call clock_gettime with
/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
pub struct MonotonicRawTime(i64);
pub struct BootTime(i64);
impl MonotonicRawTime {
/// Constructs a new MonotonicRawTime
impl BootTime {
/// Constructs a new BootTime
pub fn now() -> Self {
Self(get_current_time_in_milliseconds())
}
/// Returns the value of MonotonicRawTime in milliseconds as i64
/// Returns the value of BootTime in milliseconds as i64
pub fn milliseconds(&self) -> i64 {
self.0
}
/// Returns the integer value of MonotonicRawTime as i64
/// Returns the integer value of BootTime as i64
pub fn seconds(&self) -> i64 {
self.0 / 1000
}
@ -787,13 +787,13 @@ impl MonotonicRawTime {
}
}
impl ToSql for MonotonicRawTime {
impl ToSql for BootTime {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
}
}
impl FromSql for MonotonicRawTime {
impl FromSql for BootTime {
fn column_result(value: ValueRef) -> FromSqlResult<Self> {
Ok(Self(i64::column_result(value)?))
}
@ -805,11 +805,11 @@ impl FromSql for MonotonicRawTime {
pub struct AuthTokenEntry {
auth_token: HardwareAuthToken,
// Time received in milliseconds
time_received: MonotonicRawTime,
time_received: BootTime,
}
impl AuthTokenEntry {
fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
AuthTokenEntry { auth_token, time_received }
}
@ -832,7 +832,7 @@ impl AuthTokenEntry {
}
/// Returns the time that this auth token was received.
pub fn time_received(&self) -> MonotonicRawTime {
pub fn time_received(&self) -> BootTime {
self.time_received
}
@ -2858,14 +2858,12 @@ impl KeystoreDB {
/// Insert or replace the auth token based on (user_id, auth_id, auth_type)
pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
auth_token.clone(),
MonotonicRawTime::now(),
))
self.perboot
.insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
}
/// Find the newest auth token matching the given predicate.
pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, BootTime)>
where
F: Fn(&AuthTokenEntry) -> bool,
{
@ -2873,17 +2871,17 @@ impl KeystoreDB {
}
/// 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: MonotonicRawTime) {
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: MonotonicRawTime) {
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) -> MonotonicRawTime {
fn get_last_off_body(&self) -> BootTime {
self.perboot.get_last_off_body()
}
@ -5054,13 +5052,13 @@ pub mod tests {
#[test]
fn test_last_off_body() -> Result<()> {
let mut db = new_test_db()?;
db.insert_last_off_body(MonotonicRawTime::now());
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(MonotonicRawTime::now());
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();

View file

@ -15,7 +15,7 @@
//! 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.
use super::{AuthTokenEntry, MonotonicRawTime};
use super::{AuthTokenEntry, BootTime};
use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
};
@ -103,11 +103,11 @@ impl PerbootDB {
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) -> MonotonicRawTime {
MonotonicRawTime(self.last_off_body.load(Ordering::Relaxed))
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: MonotonicRawTime) {
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.

View file

@ -20,7 +20,7 @@ use crate::globals::{get_timestamp_service, ASYNC_TASK, DB, ENFORCEMENTS};
use crate::key_parameter::{KeyParameter, KeyParameterValue};
use crate::{authorization::Error as AuthzError, super_key::SuperEncryptionType};
use crate::{
database::{AuthTokenEntry, MonotonicRawTime},
database::{AuthTokenEntry, BootTime},
globals::SUPER_KEY,
};
use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
@ -614,7 +614,7 @@ impl Enforcements {
})
.ok_or(Error::Km(Ec::KEY_USER_NOT_AUTHENTICATED))
.context(ks_err!("No suitable auth token found."))?;
let now = MonotonicRawTime::now();
let now = BootTime::now();
let token_age = now
.checked_sub(&hat.time_received())
.ok_or_else(Error::sys)
@ -680,7 +680,7 @@ impl Enforcements {
// 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 now = MonotonicRawTime::now();
let now = BootTime::now();
let token_age = now
.checked_sub(&hat.time_received())
.ok_or_else(Error::sys)
@ -728,7 +728,7 @@ impl Enforcements {
})
}
fn find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
fn find_auth_token<F>(p: F) -> Option<(AuthTokenEntry, BootTime)>
where
F: Fn(&AuthTokenEntry) -> bool,
{
@ -853,7 +853,7 @@ impl Enforcements {
} else {
// Filter the matching auth tokens by age.
if auth_token_max_age_millis != 0 {
let now_in_millis = MonotonicRawTime::now();
let now_in_millis = BootTime::now();
let result = Self::find_auth_token(|auth_token_entry: &AuthTokenEntry| {
let token_valid = now_in_millis
.checked_sub(&auth_token_entry.time_received())
@ -889,7 +889,7 @@ impl Enforcements {
&self,
secure_user_id: i64,
auth_type: HardwareAuthenticatorType,
) -> Option<MonotonicRawTime> {
) -> Option<BootTime> {
let sids: Vec<i64> = vec![secure_user_id];
let result =

View file

@ -23,7 +23,7 @@ use crate::legacy_blob::LegacyBlobLoader;
use crate::legacy_importer::LegacyImporter;
use crate::super_key::SuperKeyManager;
use crate::utils::watchdog as wd;
use crate::{async_task::AsyncTask, database::MonotonicRawTime};
use crate::{async_task::AsyncTask, database::BootTime};
use crate::{
database::KeystoreDB,
database::Uuid,
@ -68,7 +68,7 @@ pub fn create_thread_local_db() -> KeystoreDB {
DB_INIT.call_once(|| {
log::info!("Touching Keystore 2.0 database for this first time since boot.");
db.insert_last_off_body(MonotonicRawTime::now());
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 {

View file

@ -14,7 +14,7 @@
//! This module implements IKeystoreMaintenance AIDL interface.
use crate::database::{KeyEntryLoadBits, KeyType, MonotonicRawTime};
use crate::database::{BootTime, KeyEntryLoadBits, KeyType};
use crate::error::map_km_error;
use crate::error::map_or_log_err;
use crate::error::Error;
@ -227,7 +227,7 @@ impl Maintenance {
// 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(MonotonicRawTime::now()));
DB.with(|db| db.borrow_mut().update_last_off_body(BootTime::now()));
Ok(())
}