• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 //! This is the Keystore 2.0 database module.
16 //! The database module provides a connection to the backing SQLite store.
17 //! We have two databases one for persistent key blob storage and one for
18 //! items that have a per boot life cycle.
19 //!
20 //! ## Persistent database
21 //! The persistent database has tables for key blobs. They are organized
22 //! as follows:
23 //! The `keyentry` table is the primary table for key entries. It is
24 //! accompanied by two tables for blobs and parameters.
25 //! Each key entry occupies exactly one row in the `keyentry` table and
26 //! zero or more rows in the tables `blobentry` and `keyparameter`.
27 //!
28 //! ## Per boot database
29 //! The per boot database stores items with a per boot lifecycle.
30 //! Currently, there is only the `grant` table in this database.
31 //! Grants are references to a key that can be used to access a key by
32 //! clients that don't own that key. Grants can only be created by the
33 //! owner of a key. And only certain components can create grants.
34 //! This is governed by SEPolicy.
35 //!
36 //! ## Access control
37 //! Some database functions that load keys or create grants perform
38 //! access control. This is because in some cases access control
39 //! can only be performed after some information about the designated
40 //! key was loaded from the database. To decouple the permission checks
41 //! from the database module these functions take permission check
42 //! callbacks.
43 
44 mod perboot;
45 pub(crate) mod utils;
46 mod versioning;
47 
48 use crate::gc::Gc;
49 use crate::impl_metadata; // This is in db_utils.rs
50 use crate::key_parameter::{KeyParameter, KeyParameterValue, Tag};
51 use crate::ks_err;
52 use crate::permission::KeyPermSet;
53 use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
54 use crate::{
55     error::{Error as KsError, ErrorCode, ResponseCode},
56     super_key::SuperKeyType,
57 };
58 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
59     HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
60     SecurityLevel::SecurityLevel,
61 };
62 use android_security_metrics::aidl::android::security::metrics::{
63     Storage::Storage as MetricsStorage, StorageStats::StorageStats,
64 };
65 use android_system_keystore2::aidl::android::system::keystore2::{
66     Domain::Domain, KeyDescriptor::KeyDescriptor,
67 };
68 use anyhow::{anyhow, Context, Result};
69 use keystore2_flags;
70 use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
71 use utils as db_utils;
72 use utils::SqlField;
73 
74 use keystore2_crypto::ZVec;
75 use lazy_static::lazy_static;
76 use log::error;
77 #[cfg(not(test))]
78 use rand::prelude::random;
79 use rusqlite::{
80     params, params_from_iter,
81     types::FromSql,
82     types::FromSqlResult,
83     types::ToSqlOutput,
84     types::{FromSqlError, Value, ValueRef},
85     Connection, OptionalExtension, ToSql, Transaction,
86 };
87 
88 use std::{
89     collections::{HashMap, HashSet},
90     path::Path,
91     sync::{Arc, Condvar, Mutex},
92     time::{Duration, SystemTime},
93 };
94 
95 use TransactionBehavior::Immediate;
96 
97 #[cfg(test)]
98 use tests::random;
99 
100 /// Wrapper for `rusqlite::TransactionBehavior` which includes information about the transaction
101 /// being performed.
102 #[derive(Clone, Copy)]
103 enum TransactionBehavior {
104     Deferred,
105     Immediate(&'static str),
106 }
107 
108 impl From<TransactionBehavior> for rusqlite::TransactionBehavior {
from(val: TransactionBehavior) -> Self109     fn from(val: TransactionBehavior) -> Self {
110         match val {
111             TransactionBehavior::Deferred => rusqlite::TransactionBehavior::Deferred,
112             TransactionBehavior::Immediate(_) => rusqlite::TransactionBehavior::Immediate,
113         }
114     }
115 }
116 
117 impl TransactionBehavior {
name(&self) -> Option<&'static str>118     fn name(&self) -> Option<&'static str> {
119         match self {
120             TransactionBehavior::Deferred => None,
121             TransactionBehavior::Immediate(v) => Some(v),
122         }
123     }
124 }
125 
126 /// If the database returns a busy error code, retry after this interval.
127 const DB_BUSY_RETRY_INTERVAL: Duration = Duration::from_micros(500);
128 /// If the database returns a busy error code, keep retrying for this long.
129 const MAX_DB_BUSY_RETRY_PERIOD: Duration = Duration::from_secs(15);
130 
131 /// Check whether a database lock has timed out.
check_lock_timeout(start: &std::time::Instant, timeout: Duration) -> Result<()>132 fn check_lock_timeout(start: &std::time::Instant, timeout: Duration) -> Result<()> {
133     if keystore2_flags::database_loop_timeout() {
134         let elapsed = start.elapsed();
135         if elapsed >= timeout {
136             error!("Abandon locked DB after {elapsed:?}");
137             return Err(&KsError::Rc(ResponseCode::BACKEND_BUSY))
138                 .context(ks_err!("Abandon locked DB after {elapsed:?}",));
139         }
140     }
141     Ok(())
142 }
143 
144 impl_metadata!(
145     /// A set of metadata for key entries.
146     #[derive(Debug, Default, Eq, PartialEq)]
147     pub struct KeyMetaData;
148     /// A metadata entry for key entries.
149     #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
150     pub enum KeyMetaEntry {
151         /// Date of the creation of the key entry.
152         CreationDate(DateTime) with accessor creation_date,
153         /// Expiration date for attestation keys.
154         AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
155         /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
156         /// provisioning
157         AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
158         /// Vector representing the raw public key so results from the server can be matched
159         /// to the right entry
160         AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
161         /// SEC1 public key for ECDH encryption
162         Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
163         //  --- ADD NEW META DATA FIELDS HERE ---
164         // For backwards compatibility add new entries only to
165         // end of this list and above this comment.
166     };
167 );
168 
169 impl KeyMetaData {
load_from_db(key_id: i64, tx: &Transaction) -> Result<Self>170     fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
171         let mut stmt = tx
172             .prepare(
173                 "SELECT tag, data from persistent.keymetadata
174                     WHERE keyentryid = ?;",
175             )
176             .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
177 
178         let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
179 
180         let mut rows = stmt
181             .query(params![key_id])
182             .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
183         db_utils::with_rows_extract_all(&mut rows, |row| {
184             let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
185             metadata.insert(
186                 db_tag,
187                 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
188                     .context("Failed to read KeyMetaEntry.")?,
189             );
190             Ok(())
191         })
192         .context(ks_err!("KeyMetaData::load_from_db."))?;
193 
194         Ok(Self { data: metadata })
195     }
196 
store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()>197     fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
198         let mut stmt = tx
199             .prepare(
200                 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
201                     VALUES (?, ?, ?);",
202             )
203             .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
204 
205         let iter = self.data.iter();
206         for (tag, entry) in iter {
207             stmt.insert(params![key_id, tag, entry,]).with_context(|| {
208                 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
209             })?;
210         }
211         Ok(())
212     }
213 }
214 
215 impl_metadata!(
216     /// A set of metadata for key blobs.
217     #[derive(Debug, Default, Eq, PartialEq)]
218     pub struct BlobMetaData;
219     /// A metadata entry for key blobs.
220     #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
221     pub enum BlobMetaEntry {
222         /// If present, indicates that the blob is encrypted with another key or a key derived
223         /// from a password.
224         EncryptedBy(EncryptedBy) with accessor encrypted_by,
225         /// If the blob is password encrypted this field is set to the
226         /// salt used for the key derivation.
227         Salt(Vec<u8>) with accessor salt,
228         /// If the blob is encrypted, this field is set to the initialization vector.
229         Iv(Vec<u8>) with accessor iv,
230         /// If the blob is encrypted, this field holds the AEAD TAG.
231         AeadTag(Vec<u8>) with accessor aead_tag,
232         /// The uuid of the owning KeyMint instance.
233         KmUuid(Uuid) with accessor km_uuid,
234         /// If the key is ECDH encrypted, this is the ephemeral public key
235         PublicKey(Vec<u8>) with accessor public_key,
236         /// If the key is encrypted with a MaxBootLevel key, this is the boot level
237         /// of that key
238         MaxBootLevel(i32) with accessor max_boot_level,
239         //  --- ADD NEW META DATA FIELDS HERE ---
240         // For backwards compatibility add new entries only to
241         // end of this list and above this comment.
242     };
243 );
244 
245 impl BlobMetaData {
load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self>246     fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
247         let mut stmt = tx
248             .prepare(
249                 "SELECT tag, data from persistent.blobmetadata
250                     WHERE blobentryid = ?;",
251             )
252             .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
253 
254         let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
255 
256         let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
257         db_utils::with_rows_extract_all(&mut rows, |row| {
258             let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
259             metadata.insert(
260                 db_tag,
261                 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
262                     .context("Failed to read BlobMetaEntry.")?,
263             );
264             Ok(())
265         })
266         .context(ks_err!("BlobMetaData::load_from_db"))?;
267 
268         Ok(Self { data: metadata })
269     }
270 
store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()>271     fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
272         let mut stmt = tx
273             .prepare(
274                 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
275                     VALUES (?, ?, ?);",
276             )
277             .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
278 
279         let iter = self.data.iter();
280         for (tag, entry) in iter {
281             stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
282                 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
283             })?;
284         }
285         Ok(())
286     }
287 }
288 
289 /// Indicates the type of the keyentry.
290 #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
291 pub enum KeyType {
292     /// This is a client key type. These keys are created or imported through the Keystore 2.0
293     /// AIDL interface android.system.keystore2.
294     Client,
295     /// This is a super key type. These keys are created by keystore itself and used to encrypt
296     /// other key blobs to provide LSKF binding.
297     Super,
298 }
299 
300 impl ToSql for KeyType {
to_sql(&self) -> rusqlite::Result<ToSqlOutput>301     fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
302         Ok(ToSqlOutput::Owned(Value::Integer(match self {
303             KeyType::Client => 0,
304             KeyType::Super => 1,
305         })))
306     }
307 }
308 
309 impl FromSql for KeyType {
column_result(value: ValueRef) -> FromSqlResult<Self>310     fn column_result(value: ValueRef) -> FromSqlResult<Self> {
311         match i64::column_result(value)? {
312             0 => Ok(KeyType::Client),
313             1 => Ok(KeyType::Super),
314             v => Err(FromSqlError::OutOfRange(v)),
315         }
316     }
317 }
318 
319 /// Uuid representation that can be stored in the database.
320 /// Right now it can only be initialized from SecurityLevel.
321 /// Once KeyMint provides a UUID type a corresponding From impl shall be added.
322 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
323 pub struct Uuid([u8; 16]);
324 
325 impl Deref for Uuid {
326     type Target = [u8; 16];
327 
deref(&self) -> &Self::Target328     fn deref(&self) -> &Self::Target {
329         &self.0
330     }
331 }
332 
333 impl From<SecurityLevel> for Uuid {
from(sec_level: SecurityLevel) -> Self334     fn from(sec_level: SecurityLevel) -> Self {
335         Self((sec_level.0 as u128).to_be_bytes())
336     }
337 }
338 
339 impl ToSql for Uuid {
to_sql(&self) -> rusqlite::Result<ToSqlOutput>340     fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
341         self.0.to_sql()
342     }
343 }
344 
345 impl FromSql for Uuid {
column_result(value: ValueRef<'_>) -> FromSqlResult<Self>346     fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
347         let blob = Vec::<u8>::column_result(value)?;
348         if blob.len() != 16 {
349             return Err(FromSqlError::OutOfRange(blob.len() as i64));
350         }
351         let mut arr = [0u8; 16];
352         arr.copy_from_slice(&blob);
353         Ok(Self(arr))
354     }
355 }
356 
357 /// Key entries that are not associated with any KeyMint instance, such as pure certificate
358 /// entries are associated with this UUID.
359 pub static KEYSTORE_UUID: Uuid = Uuid([
360     0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
361 ]);
362 
363 /// Indicates how the sensitive part of this key blob is encrypted.
364 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
365 pub enum EncryptedBy {
366     /// The keyblob is encrypted by a user password.
367     /// In the database this variant is represented as NULL.
368     Password,
369     /// The keyblob is encrypted by another key with wrapped key id.
370     /// In the database this variant is represented as non NULL value
371     /// that is convertible to i64, typically NUMERIC.
372     KeyId(i64),
373 }
374 
375 impl ToSql for EncryptedBy {
to_sql(&self) -> rusqlite::Result<ToSqlOutput>376     fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
377         match self {
378             Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
379             Self::KeyId(id) => id.to_sql(),
380         }
381     }
382 }
383 
384 impl FromSql for EncryptedBy {
column_result(value: ValueRef) -> FromSqlResult<Self>385     fn column_result(value: ValueRef) -> FromSqlResult<Self> {
386         match value {
387             ValueRef::Null => Ok(Self::Password),
388             _ => Ok(Self::KeyId(i64::column_result(value)?)),
389         }
390     }
391 }
392 
393 /// A database representation of wall clock time. DateTime stores unix epoch time as
394 /// i64 in milliseconds.
395 #[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
396 pub struct DateTime(i64);
397 
398 /// Error type returned when creating DateTime or converting it from and to
399 /// SystemTime.
400 #[derive(thiserror::Error, Debug)]
401 pub enum DateTimeError {
402     /// This is returned when SystemTime and Duration computations fail.
403     #[error(transparent)]
404     SystemTimeError(#[from] SystemTimeError),
405 
406     /// This is returned when type conversions fail.
407     #[error(transparent)]
408     TypeConversion(#[from] std::num::TryFromIntError),
409 
410     /// This is returned when checked time arithmetic failed.
411     #[error("Time arithmetic failed.")]
412     TimeArithmetic,
413 }
414 
415 impl DateTime {
416     /// Constructs a new DateTime object denoting the current time. This may fail during
417     /// conversion to unix epoch time and during conversion to the internal i64 representation.
now() -> Result<Self, DateTimeError>418     pub fn now() -> Result<Self, DateTimeError> {
419         Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
420     }
421 
422     /// Constructs a new DateTime object from milliseconds.
from_millis_epoch(millis: i64) -> Self423     pub fn from_millis_epoch(millis: i64) -> Self {
424         Self(millis)
425     }
426 
427     /// Returns unix epoch time in milliseconds.
to_millis_epoch(self) -> i64428     pub fn to_millis_epoch(self) -> i64 {
429         self.0
430     }
431 }
432 
433 impl ToSql for DateTime {
to_sql(&self) -> rusqlite::Result<ToSqlOutput>434     fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
435         Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
436     }
437 }
438 
439 impl FromSql for DateTime {
column_result(value: ValueRef) -> FromSqlResult<Self>440     fn column_result(value: ValueRef) -> FromSqlResult<Self> {
441         Ok(Self(i64::column_result(value)?))
442     }
443 }
444 
445 impl TryInto<SystemTime> for DateTime {
446     type Error = DateTimeError;
447 
try_into(self) -> Result<SystemTime, Self::Error>448     fn try_into(self) -> Result<SystemTime, Self::Error> {
449         // We want to construct a SystemTime representation equivalent to self, denoting
450         // a point in time THEN, but we cannot set the time directly. We can only construct
451         // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
452         // and between EPOCH and THEN. With this common reference we can construct the
453         // duration between NOW and THEN which we can add to our SystemTime representation
454         // of NOW to get a SystemTime representation of THEN.
455         // Durations can only be positive, thus the if statement below.
456         let now = SystemTime::now();
457         let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
458         let then_epoch = Duration::from_millis(self.0.try_into()?);
459         Ok(if now_epoch > then_epoch {
460             // then = now - (now_epoch - then_epoch)
461             now_epoch
462                 .checked_sub(then_epoch)
463                 .and_then(|d| now.checked_sub(d))
464                 .ok_or(DateTimeError::TimeArithmetic)?
465         } else {
466             // then = now + (then_epoch - now_epoch)
467             then_epoch
468                 .checked_sub(now_epoch)
469                 .and_then(|d| now.checked_add(d))
470                 .ok_or(DateTimeError::TimeArithmetic)?
471         })
472     }
473 }
474 
475 impl TryFrom<SystemTime> for DateTime {
476     type Error = DateTimeError;
477 
try_from(t: SystemTime) -> Result<Self, Self::Error>478     fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
479         Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
480     }
481 }
482 
483 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
484 enum KeyLifeCycle {
485     /// Existing keys have a key ID but are not fully populated yet.
486     /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
487     /// them to Unreferenced for garbage collection.
488     Existing,
489     /// A live key is fully populated and usable by clients.
490     Live,
491     /// An unreferenced key is scheduled for garbage collection.
492     Unreferenced,
493 }
494 
495 impl ToSql for KeyLifeCycle {
to_sql(&self) -> rusqlite::Result<ToSqlOutput>496     fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
497         match self {
498             Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
499             Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
500             Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
501         }
502     }
503 }
504 
505 impl FromSql for KeyLifeCycle {
column_result(value: ValueRef) -> FromSqlResult<Self>506     fn column_result(value: ValueRef) -> FromSqlResult<Self> {
507         match i64::column_result(value)? {
508             0 => Ok(KeyLifeCycle::Existing),
509             1 => Ok(KeyLifeCycle::Live),
510             2 => Ok(KeyLifeCycle::Unreferenced),
511             v => Err(FromSqlError::OutOfRange(v)),
512         }
513     }
514 }
515 
516 /// Keys have a KeyMint blob component and optional public certificate and
517 /// certificate chain components.
518 /// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
519 /// which components shall be loaded from the database if present.
520 #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
521 pub struct KeyEntryLoadBits(u32);
522 
523 impl KeyEntryLoadBits {
524     /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
525     pub const NONE: KeyEntryLoadBits = Self(0);
526     /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
527     pub const KM: KeyEntryLoadBits = Self(1);
528     /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
529     pub const PUBLIC: KeyEntryLoadBits = Self(2);
530     /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
531     pub const BOTH: KeyEntryLoadBits = Self(3);
532 
533     /// Returns true if this object indicates that the public components shall be loaded.
load_public(&self) -> bool534     pub const fn load_public(&self) -> bool {
535         self.0 & Self::PUBLIC.0 != 0
536     }
537 
538     /// Returns true if the object indicates that the KeyMint component shall be loaded.
load_km(&self) -> bool539     pub const fn load_km(&self) -> bool {
540         self.0 & Self::KM.0 != 0
541     }
542 }
543 
544 lazy_static! {
545     static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
546 }
547 
548 struct KeyIdLockDb {
549     locked_keys: Mutex<HashSet<i64>>,
550     cond_var: Condvar,
551 }
552 
553 /// A locked key. While a guard exists for a given key id, the same key cannot be loaded
554 /// from the database a second time. Most functions manipulating the key blob database
555 /// require a KeyIdGuard.
556 #[derive(Debug)]
557 pub struct KeyIdGuard(i64);
558 
559 impl KeyIdLockDb {
new() -> Self560     fn new() -> Self {
561         Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
562     }
563 
564     /// This function blocks until an exclusive lock for the given key entry id can
565     /// be acquired. It returns a guard object, that represents the lifecycle of the
566     /// acquired lock.
get(&self, key_id: i64) -> KeyIdGuard567     fn get(&self, key_id: i64) -> KeyIdGuard {
568         let mut locked_keys = self.locked_keys.lock().unwrap();
569         while locked_keys.contains(&key_id) {
570             locked_keys = self.cond_var.wait(locked_keys).unwrap();
571         }
572         locked_keys.insert(key_id);
573         KeyIdGuard(key_id)
574     }
575 
576     /// This function attempts to acquire an exclusive lock on a given key id. If the
577     /// given key id is already taken the function returns None immediately. If a lock
578     /// can be acquired this function returns a guard object, that represents the
579     /// lifecycle of the acquired lock.
try_get(&self, key_id: i64) -> Option<KeyIdGuard>580     fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
581         let mut locked_keys = self.locked_keys.lock().unwrap();
582         if locked_keys.insert(key_id) {
583             Some(KeyIdGuard(key_id))
584         } else {
585             None
586         }
587     }
588 }
589 
590 impl KeyIdGuard {
591     /// Get the numeric key id of the locked key.
id(&self) -> i64592     pub fn id(&self) -> i64 {
593         self.0
594     }
595 }
596 
597 impl Drop for KeyIdGuard {
drop(&mut self)598     fn drop(&mut self) {
599         let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
600         locked_keys.remove(&self.0);
601         drop(locked_keys);
602         KEY_ID_LOCK.cond_var.notify_all();
603     }
604 }
605 
606 /// This type represents a certificate and certificate chain entry for a key.
607 #[derive(Debug, Default)]
608 pub struct CertificateInfo {
609     cert: Option<Vec<u8>>,
610     cert_chain: Option<Vec<u8>>,
611 }
612 
613 /// This type represents a Blob with its metadata and an optional superseded blob.
614 #[derive(Debug)]
615 pub struct BlobInfo<'a> {
616     blob: &'a [u8],
617     metadata: &'a BlobMetaData,
618     /// Superseded blobs are an artifact of legacy import. In some rare occasions
619     /// the key blob needs to be upgraded during import. In that case two
620     /// blob are imported, the superseded one will have to be imported first,
621     /// so that the garbage collector can reap it.
622     superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
623 }
624 
625 impl<'a> BlobInfo<'a> {
626     /// Create a new instance of blob info with blob and corresponding metadata
627     /// and no superseded blob info.
new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self628     pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
629         Self { blob, metadata, superseded_blob: None }
630     }
631 
632     /// Create a new instance of blob info with blob and corresponding metadata
633     /// as well as superseded blob info.
new_with_superseded( blob: &'a [u8], metadata: &'a BlobMetaData, superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>, ) -> Self634     pub fn new_with_superseded(
635         blob: &'a [u8],
636         metadata: &'a BlobMetaData,
637         superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
638     ) -> Self {
639         Self { blob, metadata, superseded_blob }
640     }
641 }
642 
643 impl CertificateInfo {
644     /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self645     pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
646         Self { cert, cert_chain }
647     }
648 
649     /// Take the cert
take_cert(&mut self) -> Option<Vec<u8>>650     pub fn take_cert(&mut self) -> Option<Vec<u8>> {
651         self.cert.take()
652     }
653 
654     /// Take the cert chain
take_cert_chain(&mut self) -> Option<Vec<u8>>655     pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
656         self.cert_chain.take()
657     }
658 }
659 
660 /// This type represents a certificate chain with a private key corresponding to the leaf
661 /// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
662 pub struct CertificateChain {
663     /// A KM key blob
664     pub private_key: ZVec,
665     /// A batch cert for private_key
666     pub batch_cert: Vec<u8>,
667     /// A full certificate chain from root signing authority to private_key, including batch_cert
668     /// for convenience.
669     pub cert_chain: Vec<u8>,
670 }
671 
672 /// This type represents a Keystore 2.0 key entry.
673 /// An entry has a unique `id` by which it can be found in the database.
674 /// It has a security level field, key parameters, and three optional fields
675 /// for the KeyMint blob, public certificate and a public certificate chain.
676 #[derive(Debug, Default, Eq, PartialEq)]
677 pub struct KeyEntry {
678     id: i64,
679     key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
680     cert: Option<Vec<u8>>,
681     cert_chain: Option<Vec<u8>>,
682     km_uuid: Uuid,
683     parameters: Vec<KeyParameter>,
684     metadata: KeyMetaData,
685     pure_cert: bool,
686 }
687 
688 impl KeyEntry {
689     /// Returns the unique id of the Key entry.
id(&self) -> i64690     pub fn id(&self) -> i64 {
691         self.id
692     }
693     /// Exposes the optional KeyMint blob.
key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)>694     pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
695         &self.key_blob_info
696     }
697     /// Extracts the Optional KeyMint blob including its metadata.
take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)>698     pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
699         self.key_blob_info.take()
700     }
701     /// Exposes the optional public certificate.
cert(&self) -> &Option<Vec<u8>>702     pub fn cert(&self) -> &Option<Vec<u8>> {
703         &self.cert
704     }
705     /// Extracts the optional public certificate.
take_cert(&mut self) -> Option<Vec<u8>>706     pub fn take_cert(&mut self) -> Option<Vec<u8>> {
707         self.cert.take()
708     }
709     /// Extracts the optional public certificate_chain.
take_cert_chain(&mut self) -> Option<Vec<u8>>710     pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
711         self.cert_chain.take()
712     }
713     /// Returns the uuid of the owning KeyMint instance.
km_uuid(&self) -> &Uuid714     pub fn km_uuid(&self) -> &Uuid {
715         &self.km_uuid
716     }
717     /// Consumes this key entry and extracts the keyparameters from it.
into_key_parameters(self) -> Vec<KeyParameter>718     pub fn into_key_parameters(self) -> Vec<KeyParameter> {
719         self.parameters
720     }
721     /// Exposes the key metadata of this key entry.
metadata(&self) -> &KeyMetaData722     pub fn metadata(&self) -> &KeyMetaData {
723         &self.metadata
724     }
725     /// This returns true if the entry is a pure certificate entry with no
726     /// private key component.
pure_cert(&self) -> bool727     pub fn pure_cert(&self) -> bool {
728         self.pure_cert
729     }
730 }
731 
732 /// Indicates the sub component of a key entry for persistent storage.
733 #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
734 pub struct SubComponentType(u32);
735 impl SubComponentType {
736     /// Persistent identifier for a key blob.
737     pub const KEY_BLOB: SubComponentType = Self(0);
738     /// Persistent identifier for a certificate blob.
739     pub const CERT: SubComponentType = Self(1);
740     /// Persistent identifier for a certificate chain blob.
741     pub const CERT_CHAIN: SubComponentType = Self(2);
742 }
743 
744 impl ToSql for SubComponentType {
to_sql(&self) -> rusqlite::Result<ToSqlOutput>745     fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
746         self.0.to_sql()
747     }
748 }
749 
750 impl FromSql for SubComponentType {
column_result(value: ValueRef) -> FromSqlResult<Self>751     fn column_result(value: ValueRef) -> FromSqlResult<Self> {
752         Ok(Self(u32::column_result(value)?))
753     }
754 }
755 
756 /// This trait is private to the database module. It is used to convey whether or not the garbage
757 /// collector shall be invoked after a database access. All closures passed to
758 /// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
759 /// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
760 /// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
761 /// `.need_gc()`.
762 trait DoGc<T> {
do_gc(self, need_gc: bool) -> Result<(bool, T)>763     fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
764 
no_gc(self) -> Result<(bool, T)>765     fn no_gc(self) -> Result<(bool, T)>;
766 
need_gc(self) -> Result<(bool, T)>767     fn need_gc(self) -> Result<(bool, T)>;
768 }
769 
770 impl<T> DoGc<T> for Result<T> {
do_gc(self, need_gc: bool) -> Result<(bool, T)>771     fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
772         self.map(|r| (need_gc, r))
773     }
774 
no_gc(self) -> Result<(bool, T)>775     fn no_gc(self) -> Result<(bool, T)> {
776         self.do_gc(false)
777     }
778 
need_gc(self) -> Result<(bool, T)>779     fn need_gc(self) -> Result<(bool, T)> {
780         self.do_gc(true)
781     }
782 }
783 
784 /// KeystoreDB wraps a connection to an SQLite database and tracks its
785 /// ownership. It also implements all of Keystore 2.0's database functionality.
786 pub struct KeystoreDB {
787     conn: Connection,
788     gc: Option<Arc<Gc>>,
789     perboot: Arc<perboot::PerbootDB>,
790 }
791 
792 /// Database representation of the monotonic time retrieved from the system call clock_gettime with
793 /// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
794 #[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
795 pub struct BootTime(i64);
796 
797 impl BootTime {
798     /// Constructs a new BootTime
now() -> Self799     pub fn now() -> Self {
800         Self(get_current_time_in_milliseconds())
801     }
802 
803     /// Returns the value of BootTime in milliseconds as i64
milliseconds(&self) -> i64804     pub fn milliseconds(&self) -> i64 {
805         self.0
806     }
807 
808     /// Returns the integer value of BootTime as i64
seconds(&self) -> i64809     pub fn seconds(&self) -> i64 {
810         self.0 / 1000
811     }
812 
813     /// Like i64::checked_sub.
checked_sub(&self, other: &Self) -> Option<Self>814     pub fn checked_sub(&self, other: &Self) -> Option<Self> {
815         self.0.checked_sub(other.0).map(Self)
816     }
817 }
818 
819 impl ToSql for BootTime {
to_sql(&self) -> rusqlite::Result<ToSqlOutput>820     fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
821         Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
822     }
823 }
824 
825 impl FromSql for BootTime {
column_result(value: ValueRef) -> FromSqlResult<Self>826     fn column_result(value: ValueRef) -> FromSqlResult<Self> {
827         Ok(Self(i64::column_result(value)?))
828     }
829 }
830 
831 /// This struct encapsulates the information to be stored in the database about the auth tokens
832 /// received by keystore.
833 #[derive(Clone)]
834 pub struct AuthTokenEntry {
835     auth_token: HardwareAuthToken,
836     // Time received in milliseconds
837     time_received: BootTime,
838 }
839 
840 impl AuthTokenEntry {
new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self841     fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
842         AuthTokenEntry { auth_token, time_received }
843     }
844 
845     /// Checks if this auth token satisfies the given authentication information.
satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool846     pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
847         user_secure_ids.iter().any(|&sid| {
848             (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
849                 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
850         })
851     }
852 
853     /// Returns the auth token wrapped by the AuthTokenEntry
auth_token(&self) -> &HardwareAuthToken854     pub fn auth_token(&self) -> &HardwareAuthToken {
855         &self.auth_token
856     }
857 
858     /// Returns the auth token wrapped by the AuthTokenEntry
take_auth_token(self) -> HardwareAuthToken859     pub fn take_auth_token(self) -> HardwareAuthToken {
860         self.auth_token
861     }
862 
863     /// Returns the time that this auth token was received.
time_received(&self) -> BootTime864     pub fn time_received(&self) -> BootTime {
865         self.time_received
866     }
867 
868     /// Returns the challenge value of the auth token.
challenge(&self) -> i64869     pub fn challenge(&self) -> i64 {
870         self.auth_token.challenge
871     }
872 }
873 
874 impl KeystoreDB {
875     const UNASSIGNED_KEY_ID: i64 = -1i64;
876     const CURRENT_DB_VERSION: u32 = 1;
877     const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
878 
879     /// Name of the file that holds the cross-boot persistent database.
880     pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
881 
882     /// This will create a new database connection connecting the two
883     /// files persistent.sqlite and perboot.sqlite in the given directory.
884     /// It also attempts to initialize all of the tables.
885     /// KeystoreDB cannot be used by multiple threads.
886     /// Each thread should open their own connection using `thread_local!`.
new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self>887     pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
888         let _wp = wd::watch("KeystoreDB::new");
889 
890         let persistent_path = Self::make_persistent_path(db_root)?;
891         let conn = Self::make_connection(&persistent_path)?;
892 
893         let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
894         db.with_transaction(Immediate("TX_new"), |tx| {
895             versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
896                 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
897             Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
898         })?;
899         Ok(db)
900     }
901 
902     // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
903     // cryptographic binding to the boot level keys was implemented.
from_0_to_1(tx: &Transaction) -> Result<u32>904     fn from_0_to_1(tx: &Transaction) -> Result<u32> {
905         tx.execute(
906             "UPDATE persistent.keyentry SET state = ?
907              WHERE
908                  id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
909              AND
910                  id NOT IN (
911                      SELECT keyentryid FROM persistent.blobentry
912                      WHERE id IN (
913                          SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
914                      )
915                  );",
916             params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
917         )
918         .context(ks_err!("Failed to delete logical boot level keys."))?;
919         Ok(1)
920     }
921 
init_tables(tx: &Transaction) -> Result<()>922     fn init_tables(tx: &Transaction) -> Result<()> {
923         tx.execute(
924             "CREATE TABLE IF NOT EXISTS persistent.keyentry (
925                      id INTEGER UNIQUE,
926                      key_type INTEGER,
927                      domain INTEGER,
928                      namespace INTEGER,
929                      alias BLOB,
930                      state INTEGER,
931                      km_uuid BLOB);",
932             [],
933         )
934         .context("Failed to initialize \"keyentry\" table.")?;
935 
936         tx.execute(
937             "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
938             ON keyentry(id);",
939             [],
940         )
941         .context("Failed to create index keyentry_id_index.")?;
942 
943         tx.execute(
944             "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
945             ON keyentry(domain, namespace, alias);",
946             [],
947         )
948         .context("Failed to create index keyentry_domain_namespace_index.")?;
949 
950         tx.execute(
951             "CREATE TABLE IF NOT EXISTS persistent.blobentry (
952                     id INTEGER PRIMARY KEY,
953                     subcomponent_type INTEGER,
954                     keyentryid INTEGER,
955                     blob BLOB);",
956             [],
957         )
958         .context("Failed to initialize \"blobentry\" table.")?;
959 
960         tx.execute(
961             "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
962             ON blobentry(keyentryid);",
963             [],
964         )
965         .context("Failed to create index blobentry_keyentryid_index.")?;
966 
967         tx.execute(
968             "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
969                      id INTEGER PRIMARY KEY,
970                      blobentryid INTEGER,
971                      tag INTEGER,
972                      data ANY,
973                      UNIQUE (blobentryid, tag));",
974             [],
975         )
976         .context("Failed to initialize \"blobmetadata\" table.")?;
977 
978         tx.execute(
979             "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
980             ON blobmetadata(blobentryid);",
981             [],
982         )
983         .context("Failed to create index blobmetadata_blobentryid_index.")?;
984 
985         tx.execute(
986             "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
987                      keyentryid INTEGER,
988                      tag INTEGER,
989                      data ANY,
990                      security_level INTEGER);",
991             [],
992         )
993         .context("Failed to initialize \"keyparameter\" table.")?;
994 
995         tx.execute(
996             "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
997             ON keyparameter(keyentryid);",
998             [],
999         )
1000         .context("Failed to create index keyparameter_keyentryid_index.")?;
1001 
1002         tx.execute(
1003             "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
1004                      keyentryid INTEGER,
1005                      tag INTEGER,
1006                      data ANY,
1007                      UNIQUE (keyentryid, tag));",
1008             [],
1009         )
1010         .context("Failed to initialize \"keymetadata\" table.")?;
1011 
1012         tx.execute(
1013             "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
1014             ON keymetadata(keyentryid);",
1015             [],
1016         )
1017         .context("Failed to create index keymetadata_keyentryid_index.")?;
1018 
1019         tx.execute(
1020             "CREATE TABLE IF NOT EXISTS persistent.grant (
1021                     id INTEGER UNIQUE,
1022                     grantee INTEGER,
1023                     keyentryid INTEGER,
1024                     access_vector INTEGER);",
1025             [],
1026         )
1027         .context("Failed to initialize \"grant\" table.")?;
1028 
1029         Ok(())
1030     }
1031 
make_persistent_path(db_root: &Path) -> Result<String>1032     fn make_persistent_path(db_root: &Path) -> Result<String> {
1033         // Build the path to the sqlite file.
1034         let mut persistent_path = db_root.to_path_buf();
1035         persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1036 
1037         // Now convert them to strings prefixed with "file:"
1038         let mut persistent_path_str = "file:".to_owned();
1039         persistent_path_str.push_str(&persistent_path.to_string_lossy());
1040 
1041         // Connect to database in specific mode
1042         let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1043             "?journal_mode=WAL".to_owned()
1044         } else {
1045             "?journal_mode=DELETE".to_owned()
1046         };
1047         persistent_path_str.push_str(&persistent_path_mode);
1048 
1049         Ok(persistent_path_str)
1050     }
1051 
make_connection(persistent_file: &str) -> Result<Connection>1052     fn make_connection(persistent_file: &str) -> Result<Connection> {
1053         let conn =
1054             Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1055 
1056         loop {
1057             if let Err(e) = conn
1058                 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1059                 .context("Failed to attach database persistent.")
1060             {
1061                 if Self::is_locked_error(&e) {
1062                     std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
1063                     continue;
1064                 } else {
1065                     return Err(e);
1066                 }
1067             }
1068             break;
1069         }
1070 
1071         // Drop the cache size from default (2M) to 0.5M
1072         conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1073             .context("Failed to decrease cache size for persistent db")?;
1074 
1075         Ok(conn)
1076     }
1077 
do_table_size_query( &mut self, storage_type: MetricsStorage, query: &str, params: &[&str], ) -> Result<StorageStats>1078     fn do_table_size_query(
1079         &mut self,
1080         storage_type: MetricsStorage,
1081         query: &str,
1082         params: &[&str],
1083     ) -> Result<StorageStats> {
1084         let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1085             tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
1086                 .with_context(|| {
1087                     ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
1088                 })
1089                 .no_gc()
1090         })?;
1091         Ok(StorageStats { storage_type, size: total, unused_size: unused })
1092     }
1093 
get_total_size(&mut self) -> Result<StorageStats>1094     fn get_total_size(&mut self) -> Result<StorageStats> {
1095         self.do_table_size_query(
1096             MetricsStorage::DATABASE,
1097             "SELECT page_count * page_size, freelist_count * page_size
1098              FROM pragma_page_count('persistent'),
1099                   pragma_page_size('persistent'),
1100                   persistent.pragma_freelist_count();",
1101             &[],
1102         )
1103     }
1104 
get_table_size( &mut self, storage_type: MetricsStorage, schema: &str, table: &str, ) -> Result<StorageStats>1105     fn get_table_size(
1106         &mut self,
1107         storage_type: MetricsStorage,
1108         schema: &str,
1109         table: &str,
1110     ) -> Result<StorageStats> {
1111         self.do_table_size_query(
1112             storage_type,
1113             "SELECT pgsize,unused FROM dbstat(?1)
1114              WHERE name=?2 AND aggregate=TRUE;",
1115             &[schema, table],
1116         )
1117     }
1118 
1119     /// Fetches a storage statisitics atom for a given storage type. For storage
1120     /// types that map to a table, information about the table's storage is
1121     /// returned. Requests for storage types that are not DB tables return None.
get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats>1122     pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
1123         let _wp = wd::watch("KeystoreDB::get_storage_stat");
1124 
1125         match storage_type {
1126             MetricsStorage::DATABASE => self.get_total_size(),
1127             MetricsStorage::KEY_ENTRY => {
1128                 self.get_table_size(storage_type, "persistent", "keyentry")
1129             }
1130             MetricsStorage::KEY_ENTRY_ID_INDEX => {
1131                 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1132             }
1133             MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
1134                 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1135             }
1136             MetricsStorage::BLOB_ENTRY => {
1137                 self.get_table_size(storage_type, "persistent", "blobentry")
1138             }
1139             MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
1140                 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1141             }
1142             MetricsStorage::KEY_PARAMETER => {
1143                 self.get_table_size(storage_type, "persistent", "keyparameter")
1144             }
1145             MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
1146                 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1147             }
1148             MetricsStorage::KEY_METADATA => {
1149                 self.get_table_size(storage_type, "persistent", "keymetadata")
1150             }
1151             MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
1152                 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1153             }
1154             MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1155             MetricsStorage::AUTH_TOKEN => {
1156                 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1157                 // reportable
1158                 // Size provided is only an approximation
1159                 Ok(StorageStats {
1160                     storage_type,
1161                     size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1162                         as i32,
1163                     unused_size: 0,
1164                 })
1165             }
1166             MetricsStorage::BLOB_METADATA => {
1167                 self.get_table_size(storage_type, "persistent", "blobmetadata")
1168             }
1169             MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
1170                 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1171             }
1172             _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
1173         }
1174     }
1175 
1176     /// This function is intended to be used by the garbage collector.
1177     /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1178     /// superseded key blobs that might need special handling by the garbage collector.
1179     /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1180     /// need special handling and returns None.
handle_next_superseded_blobs( &mut self, blob_ids_to_delete: &[i64], max_blobs: usize, ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>>1181     pub fn handle_next_superseded_blobs(
1182         &mut self,
1183         blob_ids_to_delete: &[i64],
1184         max_blobs: usize,
1185     ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
1186         let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob");
1187         self.with_transaction(Immediate("TX_handle_next_superseded_blob"), |tx| {
1188             // Delete the given blobs.
1189             for blob_id in blob_ids_to_delete {
1190                 tx.execute(
1191                     "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1192                     params![blob_id],
1193                 )
1194                 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
1195                 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1196                     .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
1197             }
1198 
1199             Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1200 
1201             // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1202             let result: Vec<(i64, Vec<u8>)> = {
1203                 let mut stmt = tx
1204                     .prepare(
1205                         "SELECT id, blob FROM persistent.blobentry
1206                         WHERE subcomponent_type = ?
1207                         AND (
1208                             id NOT IN (
1209                                 SELECT MAX(id) FROM persistent.blobentry
1210                                 WHERE subcomponent_type = ?
1211                                 GROUP BY keyentryid, subcomponent_type
1212                             )
1213                         OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1214                     ) LIMIT ?;",
1215                     )
1216                     .context("Trying to prepare query for superseded blobs.")?;
1217 
1218                 let rows = stmt
1219                     .query_map(
1220                         params![
1221                             SubComponentType::KEY_BLOB,
1222                             SubComponentType::KEY_BLOB,
1223                             max_blobs as i64,
1224                         ],
1225                         |row| Ok((row.get(0)?, row.get(1)?)),
1226                     )
1227                     .context("Trying to query superseded blob.")?;
1228 
1229                 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1230                     .context("Trying to extract superseded blobs.")?
1231             };
1232 
1233             let result = result
1234                 .into_iter()
1235                 .map(|(blob_id, blob)| {
1236                     Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1237                 })
1238                 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1239                 .context("Trying to load blob metadata.")?;
1240             if !result.is_empty() {
1241                 return Ok(result).no_gc();
1242             }
1243 
1244             // We did not find any superseded key blob, so let's remove other superseded blob in
1245             // one transaction.
1246             tx.execute(
1247                 "DELETE FROM persistent.blobentry
1248                  WHERE NOT subcomponent_type = ?
1249                  AND (
1250                      id NOT IN (
1251                         SELECT MAX(id) FROM persistent.blobentry
1252                         WHERE NOT subcomponent_type = ?
1253                         GROUP BY keyentryid, subcomponent_type
1254                      ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1255                  );",
1256                 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1257             )
1258             .context("Trying to purge superseded blobs.")?;
1259 
1260             Ok(vec![]).no_gc()
1261         })
1262         .context(ks_err!())
1263     }
1264 
1265     /// This maintenance function should be called only once before the database is used for the
1266     /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1267     /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1268     /// returns the number of rows affected. If this returns a value greater than 0, it means that
1269     /// Keystore crashed at some point during key generation. Callers may want to log such
1270     /// occurrences.
1271     /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1272     /// it to `KeyLifeCycle::Live` may have grants.
cleanup_leftovers(&mut self) -> Result<usize>1273     pub fn cleanup_leftovers(&mut self) -> Result<usize> {
1274         let _wp = wd::watch("KeystoreDB::cleanup_leftovers");
1275 
1276         self.with_transaction(Immediate("TX_cleanup_leftovers"), |tx| {
1277             tx.execute(
1278                 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1279                 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1280             )
1281             .context("Failed to execute query.")
1282             .need_gc()
1283         })
1284         .context(ks_err!())
1285     }
1286 
1287     /// Checks if a key exists with given key type and key descriptor properties.
key_exists( &mut self, domain: Domain, nspace: i64, alias: &str, key_type: KeyType, ) -> Result<bool>1288     pub fn key_exists(
1289         &mut self,
1290         domain: Domain,
1291         nspace: i64,
1292         alias: &str,
1293         key_type: KeyType,
1294     ) -> Result<bool> {
1295         let _wp = wd::watch("KeystoreDB::key_exists");
1296 
1297         self.with_transaction(Immediate("TX_key_exists"), |tx| {
1298             let key_descriptor =
1299                 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1300             let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
1301             match result {
1302                 Ok(_) => Ok(true),
1303                 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1304                     Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1305                     _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
1306                 },
1307             }
1308             .no_gc()
1309         })
1310         .context(ks_err!())
1311     }
1312 
1313     /// Stores a super key in the database.
store_super_key( &mut self, user_id: u32, key_type: &SuperKeyType, blob: &[u8], blob_metadata: &BlobMetaData, key_metadata: &KeyMetaData, ) -> Result<KeyEntry>1314     pub fn store_super_key(
1315         &mut self,
1316         user_id: u32,
1317         key_type: &SuperKeyType,
1318         blob: &[u8],
1319         blob_metadata: &BlobMetaData,
1320         key_metadata: &KeyMetaData,
1321     ) -> Result<KeyEntry> {
1322         let _wp = wd::watch("KeystoreDB::store_super_key");
1323 
1324         self.with_transaction(Immediate("TX_store_super_key"), |tx| {
1325             let key_id = Self::insert_with_retry(|id| {
1326                 tx.execute(
1327                     "INSERT into persistent.keyentry
1328                             (id, key_type, domain, namespace, alias, state, km_uuid)
1329                             VALUES(?, ?, ?, ?, ?, ?, ?);",
1330                     params![
1331                         id,
1332                         KeyType::Super,
1333                         Domain::APP.0,
1334                         user_id as i64,
1335                         key_type.alias,
1336                         KeyLifeCycle::Live,
1337                         &KEYSTORE_UUID,
1338                     ],
1339                 )
1340             })
1341             .context("Failed to insert into keyentry table.")?;
1342 
1343             key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1344 
1345             Self::set_blob_internal(
1346                 tx,
1347                 key_id,
1348                 SubComponentType::KEY_BLOB,
1349                 Some(blob),
1350                 Some(blob_metadata),
1351             )
1352             .context("Failed to store key blob.")?;
1353 
1354             Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1355                 .context("Trying to load key components.")
1356                 .no_gc()
1357         })
1358         .context(ks_err!())
1359     }
1360 
1361     /// Loads super key of a given user, if exists
load_super_key( &mut self, key_type: &SuperKeyType, user_id: u32, ) -> Result<Option<(KeyIdGuard, KeyEntry)>>1362     pub fn load_super_key(
1363         &mut self,
1364         key_type: &SuperKeyType,
1365         user_id: u32,
1366     ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
1367         let _wp = wd::watch("KeystoreDB::load_super_key");
1368 
1369         self.with_transaction(Immediate("TX_load_super_key"), |tx| {
1370             let key_descriptor = KeyDescriptor {
1371                 domain: Domain::APP,
1372                 nspace: user_id as i64,
1373                 alias: Some(key_type.alias.into()),
1374                 blob: None,
1375             };
1376             let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
1377             match id {
1378                 Ok(id) => {
1379                     let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
1380                         .context(ks_err!("Failed to load key entry."))?;
1381                     Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1382                 }
1383                 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1384                     Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1385                     _ => Err(error).context(ks_err!()),
1386                 },
1387             }
1388             .no_gc()
1389         })
1390         .context(ks_err!())
1391     }
1392 
1393     /// Creates a transaction with the given behavior and executes f with the new transaction.
1394     /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1395     /// or DatabaseLocked is encountered.
with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T> where F: Fn(&Transaction) -> Result<(bool, T)>,1396     fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1397     where
1398         F: Fn(&Transaction) -> Result<(bool, T)>,
1399     {
1400         self.with_transaction_timeout(behavior, MAX_DB_BUSY_RETRY_PERIOD, f)
1401     }
with_transaction_timeout<T, F>( &mut self, behavior: TransactionBehavior, timeout: Duration, f: F, ) -> Result<T> where F: Fn(&Transaction) -> Result<(bool, T)>,1402     fn with_transaction_timeout<T, F>(
1403         &mut self,
1404         behavior: TransactionBehavior,
1405         timeout: Duration,
1406         f: F,
1407     ) -> Result<T>
1408     where
1409         F: Fn(&Transaction) -> Result<(bool, T)>,
1410     {
1411         let start = std::time::Instant::now();
1412         let name = behavior.name();
1413         loop {
1414             let result = self
1415                 .conn
1416                 .transaction_with_behavior(behavior.into())
1417                 .context(ks_err!())
1418                 .and_then(|tx| {
1419                     let _wp = name.map(wd::watch);
1420                     f(&tx).map(|result| (result, tx))
1421                 })
1422                 .and_then(|(result, tx)| {
1423                     tx.commit().context(ks_err!("Failed to commit transaction."))?;
1424                     Ok(result)
1425                 });
1426             match result {
1427                 Ok(result) => break Ok(result),
1428                 Err(e) => {
1429                     if Self::is_locked_error(&e) {
1430                         check_lock_timeout(&start, timeout)?;
1431                         std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
1432                         continue;
1433                     } else {
1434                         return Err(e).context(ks_err!());
1435                     }
1436                 }
1437             }
1438         }
1439         .map(|(need_gc, result)| {
1440             if need_gc {
1441                 if let Some(ref gc) = self.gc {
1442                     gc.notify_gc();
1443                 }
1444             }
1445             result
1446         })
1447     }
1448 
is_locked_error(e: &anyhow::Error) -> bool1449     fn is_locked_error(e: &anyhow::Error) -> bool {
1450         matches!(
1451             e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1452             Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1453                 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1454         )
1455     }
1456 
create_key_entry_internal( tx: &Transaction, domain: &Domain, namespace: &i64, key_type: KeyType, km_uuid: &Uuid, ) -> Result<KeyIdGuard>1457     fn create_key_entry_internal(
1458         tx: &Transaction,
1459         domain: &Domain,
1460         namespace: &i64,
1461         key_type: KeyType,
1462         km_uuid: &Uuid,
1463     ) -> Result<KeyIdGuard> {
1464         match *domain {
1465             Domain::APP | Domain::SELINUX => {}
1466             _ => {
1467                 return Err(KsError::sys())
1468                     .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
1469             }
1470         }
1471         Ok(KEY_ID_LOCK.get(
1472             Self::insert_with_retry(|id| {
1473                 tx.execute(
1474                     "INSERT into persistent.keyentry
1475                      (id, key_type, domain, namespace, alias, state, km_uuid)
1476                      VALUES(?, ?, ?, ?, NULL, ?, ?);",
1477                     params![
1478                         id,
1479                         key_type,
1480                         domain.0 as u32,
1481                         *namespace,
1482                         KeyLifeCycle::Existing,
1483                         km_uuid,
1484                     ],
1485                 )
1486             })
1487             .context(ks_err!())?,
1488         ))
1489     }
1490 
1491     /// Set a new blob and associates it with the given key id. Each blob
1492     /// has a sub component type.
1493     /// Each key can have one of each sub component type associated. If more
1494     /// are added only the most recent can be retrieved, and superseded blobs
1495     /// will get garbage collected.
1496     /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1497     /// removed by setting blob to None.
set_blob( &mut self, key_id: &KeyIdGuard, sc_type: SubComponentType, blob: Option<&[u8]>, blob_metadata: Option<&BlobMetaData>, ) -> Result<()>1498     pub fn set_blob(
1499         &mut self,
1500         key_id: &KeyIdGuard,
1501         sc_type: SubComponentType,
1502         blob: Option<&[u8]>,
1503         blob_metadata: Option<&BlobMetaData>,
1504     ) -> Result<()> {
1505         let _wp = wd::watch("KeystoreDB::set_blob");
1506 
1507         self.with_transaction(Immediate("TX_set_blob"), |tx| {
1508             Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
1509         })
1510         .context(ks_err!())
1511     }
1512 
1513     /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1514     /// key migration in the case where we bulk delete all the keys of an app or even a user.
1515     /// We use this to insert key blobs into the database which can then be garbage collected
1516     /// lazily by the key garbage collector.
set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()>1517     pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
1518         let _wp = wd::watch("KeystoreDB::set_deleted_blob");
1519 
1520         self.with_transaction(Immediate("TX_set_deleted_blob"), |tx| {
1521             Self::set_blob_internal(
1522                 tx,
1523                 Self::UNASSIGNED_KEY_ID,
1524                 SubComponentType::KEY_BLOB,
1525                 Some(blob),
1526                 Some(blob_metadata),
1527             )
1528             .need_gc()
1529         })
1530         .context(ks_err!())
1531     }
1532 
set_blob_internal( tx: &Transaction, key_id: i64, sc_type: SubComponentType, blob: Option<&[u8]>, blob_metadata: Option<&BlobMetaData>, ) -> Result<()>1533     fn set_blob_internal(
1534         tx: &Transaction,
1535         key_id: i64,
1536         sc_type: SubComponentType,
1537         blob: Option<&[u8]>,
1538         blob_metadata: Option<&BlobMetaData>,
1539     ) -> Result<()> {
1540         match (blob, sc_type) {
1541             (Some(blob), _) => {
1542                 tx.execute(
1543                     "INSERT INTO persistent.blobentry
1544                      (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1545                     params![sc_type, key_id, blob],
1546                 )
1547                 .context(ks_err!("Failed to insert blob."))?;
1548                 if let Some(blob_metadata) = blob_metadata {
1549                     let blob_id = tx
1550                         .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
1551                             row.get(0)
1552                         })
1553                         .context(ks_err!("Failed to get new blob id."))?;
1554                     blob_metadata
1555                         .store_in_db(blob_id, tx)
1556                         .context(ks_err!("Trying to store blob metadata."))?;
1557                 }
1558             }
1559             (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1560                 tx.execute(
1561                     "DELETE FROM persistent.blobentry
1562                     WHERE subcomponent_type = ? AND keyentryid = ?;",
1563                     params![sc_type, key_id],
1564                 )
1565                 .context(ks_err!("Failed to delete blob."))?;
1566             }
1567             (None, _) => {
1568                 return Err(KsError::sys())
1569                     .context(ks_err!("Other blobs cannot be deleted in this way."));
1570             }
1571         }
1572         Ok(())
1573     }
1574 
1575     /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1576     /// and associates them with the given `key_id`.
1577     #[cfg(test)]
insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()>1578     fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
1579         self.with_transaction(Immediate("TX_insert_keyparameter"), |tx| {
1580             Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
1581         })
1582         .context(ks_err!())
1583     }
1584 
insert_keyparameter_internal( tx: &Transaction, key_id: &KeyIdGuard, params: &[KeyParameter], ) -> Result<()>1585     fn insert_keyparameter_internal(
1586         tx: &Transaction,
1587         key_id: &KeyIdGuard,
1588         params: &[KeyParameter],
1589     ) -> Result<()> {
1590         let mut stmt = tx
1591             .prepare(
1592                 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1593                 VALUES (?, ?, ?, ?);",
1594             )
1595             .context(ks_err!("Failed to prepare statement."))?;
1596 
1597         for p in params.iter() {
1598             stmt.insert(params![
1599                 key_id.0,
1600                 p.get_tag().0,
1601                 p.key_parameter_value(),
1602                 p.security_level().0
1603             ])
1604             .with_context(|| ks_err!("Failed to insert {:?}", p))?;
1605         }
1606         Ok(())
1607     }
1608 
1609     /// Insert a set of key entry specific metadata into the database.
1610     #[cfg(test)]
insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()>1611     fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
1612         self.with_transaction(Immediate("TX_insert_key_metadata"), |tx| {
1613             metadata.store_in_db(key_id.0, tx).no_gc()
1614         })
1615         .context(ks_err!())
1616     }
1617 
1618     /// Updates the alias column of the given key id `newid` with the given alias,
1619     /// and atomically, removes the alias, domain, and namespace from another row
1620     /// with the same alias-domain-namespace tuple if such row exits.
1621     /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1622     /// collector.
rebind_alias( tx: &Transaction, newid: &KeyIdGuard, alias: &str, domain: &Domain, namespace: &i64, key_type: KeyType, ) -> Result<bool>1623     fn rebind_alias(
1624         tx: &Transaction,
1625         newid: &KeyIdGuard,
1626         alias: &str,
1627         domain: &Domain,
1628         namespace: &i64,
1629         key_type: KeyType,
1630     ) -> Result<bool> {
1631         match *domain {
1632             Domain::APP | Domain::SELINUX => {}
1633             _ => {
1634                 return Err(KsError::sys())
1635                     .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
1636             }
1637         }
1638         let updated = tx
1639             .execute(
1640                 "UPDATE persistent.keyentry
1641                  SET alias = NULL, domain = NULL, namespace = NULL, state = ?
1642                  WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1643                 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
1644             )
1645             .context(ks_err!("Failed to rebind existing entry."))?;
1646         let result = tx
1647             .execute(
1648                 "UPDATE persistent.keyentry
1649                     SET alias = ?, state = ?
1650                     WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
1651                 params![
1652                     alias,
1653                     KeyLifeCycle::Live,
1654                     newid.0,
1655                     domain.0 as u32,
1656                     *namespace,
1657                     KeyLifeCycle::Existing,
1658                     key_type,
1659                 ],
1660             )
1661             .context(ks_err!("Failed to set alias."))?;
1662         if result != 1 {
1663             return Err(KsError::sys()).context(ks_err!(
1664                 "Expected to update a single entry but instead updated {}.",
1665                 result
1666             ));
1667         }
1668         Ok(updated != 0)
1669     }
1670 
1671     /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1672     /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
migrate_key_namespace( &mut self, key_id_guard: KeyIdGuard, destination: &KeyDescriptor, caller_uid: u32, check_permission: impl Fn(&KeyDescriptor) -> Result<()>, ) -> Result<()>1673     pub fn migrate_key_namespace(
1674         &mut self,
1675         key_id_guard: KeyIdGuard,
1676         destination: &KeyDescriptor,
1677         caller_uid: u32,
1678         check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1679     ) -> Result<()> {
1680         let _wp = wd::watch("KeystoreDB::migrate_key_namespace");
1681 
1682         let destination = match destination.domain {
1683             Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1684             Domain::SELINUX => (*destination).clone(),
1685             domain => {
1686                 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1687                     .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1688             }
1689         };
1690 
1691         // Security critical: Must return immediately on failure. Do not remove the '?';
1692         check_permission(&destination).context(ks_err!("Trying to check permission."))?;
1693 
1694         let alias = destination
1695             .alias
1696             .as_ref()
1697             .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1698             .context(ks_err!("Alias must be specified."))?;
1699 
1700         self.with_transaction(Immediate("TX_migrate_key_namespace"), |tx| {
1701             // Query the destination location. If there is a key, the migration request fails.
1702             if tx
1703                 .query_row(
1704                     "SELECT id FROM persistent.keyentry
1705                      WHERE alias = ? AND domain = ? AND namespace = ?;",
1706                     params![alias, destination.domain.0, destination.nspace],
1707                     |_| Ok(()),
1708                 )
1709                 .optional()
1710                 .context("Failed to query destination.")?
1711                 .is_some()
1712             {
1713                 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1714                     .context("Target already exists.");
1715             }
1716 
1717             let updated = tx
1718                 .execute(
1719                     "UPDATE persistent.keyentry
1720                  SET alias = ?, domain = ?, namespace = ?
1721                  WHERE id = ?;",
1722                     params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1723                 )
1724                 .context("Failed to update key entry.")?;
1725 
1726             if updated != 1 {
1727                 return Err(KsError::sys())
1728                     .context(format!("Update succeeded, but {} rows were updated.", updated));
1729             }
1730             Ok(()).no_gc()
1731         })
1732         .context(ks_err!())
1733     }
1734 
1735     /// Store a new key in a single transaction.
1736     /// The function creates a new key entry, populates the blob, key parameter, and metadata
1737     /// fields, and rebinds the given alias to the new key.
1738     /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1739     /// is now unreferenced and needs to be collected.
1740     #[allow(clippy::too_many_arguments)]
store_new_key( &mut self, key: &KeyDescriptor, key_type: KeyType, params: &[KeyParameter], blob_info: &BlobInfo, cert_info: &CertificateInfo, metadata: &KeyMetaData, km_uuid: &Uuid, ) -> Result<KeyIdGuard>1741     pub fn store_new_key(
1742         &mut self,
1743         key: &KeyDescriptor,
1744         key_type: KeyType,
1745         params: &[KeyParameter],
1746         blob_info: &BlobInfo,
1747         cert_info: &CertificateInfo,
1748         metadata: &KeyMetaData,
1749         km_uuid: &Uuid,
1750     ) -> Result<KeyIdGuard> {
1751         let _wp = wd::watch("KeystoreDB::store_new_key");
1752 
1753         let (alias, domain, namespace) = match key {
1754             KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1755             | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1756                 (alias, key.domain, nspace)
1757             }
1758             _ => {
1759                 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1760                     .context(ks_err!("Need alias and domain must be APP or SELINUX."));
1761             }
1762         };
1763         self.with_transaction(Immediate("TX_store_new_key"), |tx| {
1764             let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
1765                 .context("Trying to create new key entry.")?;
1766             let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1767 
1768             // In some occasions the key blob is already upgraded during the import.
1769             // In order to make sure it gets properly deleted it is inserted into the
1770             // database here and then immediately replaced by the superseding blob.
1771             // The garbage collector will then subject the blob to deleteKey of the
1772             // KM back end to permanently invalidate the key.
1773             let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1774                 Self::set_blob_internal(
1775                     tx,
1776                     key_id.id(),
1777                     SubComponentType::KEY_BLOB,
1778                     Some(blob),
1779                     Some(blob_metadata),
1780                 )
1781                 .context("Trying to insert superseded key blob.")?;
1782                 true
1783             } else {
1784                 false
1785             };
1786 
1787             Self::set_blob_internal(
1788                 tx,
1789                 key_id.id(),
1790                 SubComponentType::KEY_BLOB,
1791                 Some(blob),
1792                 Some(blob_metadata),
1793             )
1794             .context("Trying to insert the key blob.")?;
1795             if let Some(cert) = &cert_info.cert {
1796                 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
1797                     .context("Trying to insert the certificate.")?;
1798             }
1799             if let Some(cert_chain) = &cert_info.cert_chain {
1800                 Self::set_blob_internal(
1801                     tx,
1802                     key_id.id(),
1803                     SubComponentType::CERT_CHAIN,
1804                     Some(cert_chain),
1805                     None,
1806                 )
1807                 .context("Trying to insert the certificate chain.")?;
1808             }
1809             Self::insert_keyparameter_internal(tx, &key_id, params)
1810                 .context("Trying to insert key parameters.")?;
1811             metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1812             let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
1813                 .context("Trying to rebind alias.")?
1814                 || need_gc;
1815             Ok(key_id).do_gc(need_gc)
1816         })
1817         .context(ks_err!())
1818     }
1819 
1820     /// Store a new certificate
1821     /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1822     /// the given alias to the new cert.
store_new_certificate( &mut self, key: &KeyDescriptor, key_type: KeyType, cert: &[u8], km_uuid: &Uuid, ) -> Result<KeyIdGuard>1823     pub fn store_new_certificate(
1824         &mut self,
1825         key: &KeyDescriptor,
1826         key_type: KeyType,
1827         cert: &[u8],
1828         km_uuid: &Uuid,
1829     ) -> Result<KeyIdGuard> {
1830         let _wp = wd::watch("KeystoreDB::store_new_certificate");
1831 
1832         let (alias, domain, namespace) = match key {
1833             KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1834             | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1835                 (alias, key.domain, nspace)
1836             }
1837             _ => {
1838                 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1839                     .context(ks_err!("Need alias and domain must be APP or SELINUX."));
1840             }
1841         };
1842         self.with_transaction(Immediate("TX_store_new_certificate"), |tx| {
1843             let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
1844                 .context("Trying to create new key entry.")?;
1845 
1846             Self::set_blob_internal(
1847                 tx,
1848                 key_id.id(),
1849                 SubComponentType::CERT_CHAIN,
1850                 Some(cert),
1851                 None,
1852             )
1853             .context("Trying to insert certificate.")?;
1854 
1855             let mut metadata = KeyMetaData::new();
1856             metadata.add(KeyMetaEntry::CreationDate(
1857                 DateTime::now().context("Trying to make creation time.")?,
1858             ));
1859 
1860             metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1861 
1862             let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
1863                 .context("Trying to rebind alias.")?;
1864             Ok(key_id).do_gc(need_gc)
1865         })
1866         .context(ks_err!())
1867     }
1868 
1869     // Helper function loading the key_id given the key descriptor
1870     // tuple comprising domain, namespace, and alias.
1871     // Requires a valid transaction.
load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64>1872     fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
1873         let alias = key
1874             .alias
1875             .as_ref()
1876             .map_or_else(|| Err(KsError::sys()), Ok)
1877             .context("In load_key_entry_id: Alias must be specified.")?;
1878         let mut stmt = tx
1879             .prepare(
1880                 "SELECT id FROM persistent.keyentry
1881                     WHERE
1882                     key_type = ?
1883                     AND domain = ?
1884                     AND namespace = ?
1885                     AND alias = ?
1886                     AND state = ?;",
1887             )
1888             .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1889         let mut rows = stmt
1890             .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
1891             .context("In load_key_entry_id: Failed to read from keyentry table.")?;
1892         db_utils::with_rows_extract_one(&mut rows, |row| {
1893             row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1894                 .get(0)
1895                 .context("Failed to unpack id.")
1896         })
1897         .context(ks_err!())
1898     }
1899 
1900     /// This helper function completes the access tuple of a key, which is required
1901     /// to perform access control. The strategy depends on the `domain` field in the
1902     /// key descriptor.
1903     /// * Domain::SELINUX: The access tuple is complete and this function only loads
1904     ///       the key_id for further processing.
1905     /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
1906     ///       which serves as the namespace.
1907     /// * Domain::GRANT: The grant table is queried for the `key_id` and the
1908     ///       `access_vector`.
1909     /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
1910     ///       `namespace`.
1911     /// In each case the information returned is sufficient to perform the access
1912     /// check and the key id can be used to load further key artifacts.
load_access_tuple( tx: &Transaction, key: &KeyDescriptor, key_type: KeyType, caller_uid: u32, ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)>1913     fn load_access_tuple(
1914         tx: &Transaction,
1915         key: &KeyDescriptor,
1916         key_type: KeyType,
1917         caller_uid: u32,
1918     ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1919         match key.domain {
1920             // Domain App or SELinux. In this case we load the key_id from
1921             // the keyentry database for further loading of key components.
1922             // We already have the full access tuple to perform access control.
1923             // The only distinction is that we use the caller_uid instead
1924             // of the caller supplied namespace if the domain field is
1925             // Domain::APP.
1926             Domain::APP | Domain::SELINUX => {
1927                 let mut access_key = key.clone();
1928                 if access_key.domain == Domain::APP {
1929                     access_key.nspace = caller_uid as i64;
1930                 }
1931                 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
1932                     .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
1933 
1934                 Ok((key_id, access_key, None))
1935             }
1936 
1937             // Domain::GRANT. In this case we load the key_id and the access_vector
1938             // from the grant table.
1939             Domain::GRANT => {
1940                 let mut stmt = tx
1941                     .prepare(
1942                         "SELECT keyentryid, access_vector FROM persistent.grant
1943                             WHERE grantee = ? AND id = ? AND
1944                             (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
1945                     )
1946                     .context("Domain::GRANT prepare statement failed")?;
1947                 let mut rows = stmt
1948                     .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
1949                     .context("Domain:Grant: query failed.")?;
1950                 let (key_id, access_vector): (i64, i32) =
1951                     db_utils::with_rows_extract_one(&mut rows, |row| {
1952                         let r =
1953                             row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
1954                         Ok((
1955                             r.get(0).context("Failed to unpack key_id.")?,
1956                             r.get(1).context("Failed to unpack access_vector.")?,
1957                         ))
1958                     })
1959                     .context("Domain::GRANT.")?;
1960                 Ok((key_id, key.clone(), Some(access_vector.into())))
1961             }
1962 
1963             // Domain::KEY_ID. In this case we load the domain and namespace from the
1964             // keyentry database because we need them for access control.
1965             Domain::KEY_ID => {
1966                 let (domain, namespace): (Domain, i64) = {
1967                     let mut stmt = tx
1968                         .prepare(
1969                             "SELECT domain, namespace FROM persistent.keyentry
1970                                 WHERE
1971                                 id = ?
1972                                 AND state = ?;",
1973                         )
1974                         .context("Domain::KEY_ID: prepare statement failed")?;
1975                     let mut rows = stmt
1976                         .query(params![key.nspace, KeyLifeCycle::Live])
1977                         .context("Domain::KEY_ID: query failed.")?;
1978                     db_utils::with_rows_extract_one(&mut rows, |row| {
1979                         let r =
1980                             row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
1981                         Ok((
1982                             Domain(r.get(0).context("Failed to unpack domain.")?),
1983                             r.get(1).context("Failed to unpack namespace.")?,
1984                         ))
1985                     })
1986                     .context("Domain::KEY_ID.")?
1987                 };
1988 
1989                 // We may use a key by id after loading it by grant.
1990                 // In this case we have to check if the caller has a grant for this particular
1991                 // key. We can skip this if we already know that the caller is the owner.
1992                 // But we cannot know this if domain is anything but App. E.g. in the case
1993                 // of Domain::SELINUX we have to speculatively check for grants because we have to
1994                 // consult the SEPolicy before we know if the caller is the owner.
1995                 let access_vector: Option<KeyPermSet> =
1996                     if domain != Domain::APP || namespace != caller_uid as i64 {
1997                         let access_vector: Option<i32> = tx
1998                             .query_row(
1999                                 "SELECT access_vector FROM persistent.grant
2000                                 WHERE grantee = ? AND keyentryid = ?;",
2001                                 params![caller_uid as i64, key.nspace],
2002                                 |row| row.get(0),
2003                             )
2004                             .optional()
2005                             .context("Domain::KEY_ID: query grant failed.")?;
2006                         access_vector.map(|p| p.into())
2007                     } else {
2008                         None
2009                     };
2010 
2011                 let key_id = key.nspace;
2012                 let mut access_key: KeyDescriptor = key.clone();
2013                 access_key.domain = domain;
2014                 access_key.nspace = namespace;
2015 
2016                 Ok((key_id, access_key, access_vector))
2017             }
2018             _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
2019         }
2020     }
2021 
load_blob_components( key_id: i64, load_bits: KeyEntryLoadBits, tx: &Transaction, ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)>2022     fn load_blob_components(
2023         key_id: i64,
2024         load_bits: KeyEntryLoadBits,
2025         tx: &Transaction,
2026     ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
2027         let mut stmt = tx
2028             .prepare(
2029                 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
2030                     WHERE keyentryid = ? GROUP BY subcomponent_type;",
2031             )
2032             .context(ks_err!("prepare statement failed."))?;
2033 
2034         let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
2035 
2036         let mut key_blob: Option<(i64, Vec<u8>)> = None;
2037         let mut cert_blob: Option<Vec<u8>> = None;
2038         let mut cert_chain_blob: Option<Vec<u8>> = None;
2039         let mut has_km_blob: bool = false;
2040         db_utils::with_rows_extract_all(&mut rows, |row| {
2041             let sub_type: SubComponentType =
2042                 row.get(1).context("Failed to extract subcomponent_type.")?;
2043             has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
2044             match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2045                 (SubComponentType::KEY_BLOB, _, true) => {
2046                     key_blob = Some((
2047                         row.get(0).context("Failed to extract key blob id.")?,
2048                         row.get(2).context("Failed to extract key blob.")?,
2049                     ));
2050                 }
2051                 (SubComponentType::CERT, true, _) => {
2052                     cert_blob =
2053                         Some(row.get(2).context("Failed to extract public certificate blob.")?);
2054                 }
2055                 (SubComponentType::CERT_CHAIN, true, _) => {
2056                     cert_chain_blob =
2057                         Some(row.get(2).context("Failed to extract certificate chain blob.")?);
2058                 }
2059                 (SubComponentType::CERT, _, _)
2060                 | (SubComponentType::CERT_CHAIN, _, _)
2061                 | (SubComponentType::KEY_BLOB, _, _) => {}
2062                 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2063             }
2064             Ok(())
2065         })
2066         .context(ks_err!())?;
2067 
2068         let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2069             Ok(Some((
2070                 blob,
2071                 BlobMetaData::load_from_db(blob_id, tx)
2072                     .context(ks_err!("Trying to load blob_metadata."))?,
2073             )))
2074         })?;
2075 
2076         Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
2077     }
2078 
load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>>2079     fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2080         let mut stmt = tx
2081             .prepare(
2082                 "SELECT tag, data, security_level from persistent.keyparameter
2083                     WHERE keyentryid = ?;",
2084             )
2085             .context("In load_key_parameters: prepare statement failed.")?;
2086 
2087         let mut parameters: Vec<KeyParameter> = Vec::new();
2088 
2089         let mut rows =
2090             stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
2091         db_utils::with_rows_extract_all(&mut rows, |row| {
2092             let tag = Tag(row.get(0).context("Failed to read tag.")?);
2093             let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
2094             parameters.push(
2095                 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
2096                     .context("Failed to read KeyParameter.")?,
2097             );
2098             Ok(())
2099         })
2100         .context(ks_err!())?;
2101 
2102         Ok(parameters)
2103     }
2104 
2105     /// Decrements the usage count of a limited use key. This function first checks whether the
2106     /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2107     /// zero, the key also gets marked unreferenced and scheduled for deletion.
2108     /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()>2109     pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
2110         let _wp = wd::watch("KeystoreDB::check_and_update_key_usage_count");
2111 
2112         self.with_transaction(Immediate("TX_check_and_update_key_usage_count"), |tx| {
2113             let limit: Option<i32> = tx
2114                 .query_row(
2115                     "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2116                     params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2117                     |row| row.get(0),
2118                 )
2119                 .optional()
2120                 .context("Trying to load usage count")?;
2121 
2122             let limit = limit
2123                 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2124                 .context("The Key no longer exists. Key is exhausted.")?;
2125 
2126             tx.execute(
2127                 "UPDATE persistent.keyparameter
2128                  SET data = data - 1
2129                  WHERE keyentryid = ? AND tag = ? AND data > 0;",
2130                 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2131             )
2132             .context("Failed to update key usage count.")?;
2133 
2134             match limit {
2135                 1 => Self::mark_unreferenced(tx, key_id)
2136                     .map(|need_gc| (need_gc, ()))
2137                     .context("Trying to mark limited use key for deletion."),
2138                 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
2139                 _ => Ok(()).no_gc(),
2140             }
2141         })
2142         .context(ks_err!())
2143     }
2144 
2145     /// Load a key entry by the given key descriptor.
2146     /// It uses the `check_permission` callback to verify if the access is allowed
2147     /// given the key access tuple read from the database using `load_access_tuple`.
2148     /// With `load_bits` the caller may specify which blobs shall be loaded from
2149     /// the blob database.
load_key_entry( &mut self, key: &KeyDescriptor, key_type: KeyType, load_bits: KeyEntryLoadBits, caller_uid: u32, check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, ) -> Result<(KeyIdGuard, KeyEntry)>2150     pub fn load_key_entry(
2151         &mut self,
2152         key: &KeyDescriptor,
2153         key_type: KeyType,
2154         load_bits: KeyEntryLoadBits,
2155         caller_uid: u32,
2156         check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2157     ) -> Result<(KeyIdGuard, KeyEntry)> {
2158         let _wp = wd::watch("KeystoreDB::load_key_entry");
2159         let start = std::time::Instant::now();
2160 
2161         loop {
2162             match self.load_key_entry_internal(
2163                 key,
2164                 key_type,
2165                 load_bits,
2166                 caller_uid,
2167                 &check_permission,
2168             ) {
2169                 Ok(result) => break Ok(result),
2170                 Err(e) => {
2171                     if Self::is_locked_error(&e) {
2172                         check_lock_timeout(&start, MAX_DB_BUSY_RETRY_PERIOD)?;
2173                         std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
2174                         continue;
2175                     } else {
2176                         return Err(e).context(ks_err!());
2177                     }
2178                 }
2179             }
2180         }
2181     }
2182 
load_key_entry_internal( &mut self, key: &KeyDescriptor, key_type: KeyType, load_bits: KeyEntryLoadBits, caller_uid: u32, check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, ) -> Result<(KeyIdGuard, KeyEntry)>2183     fn load_key_entry_internal(
2184         &mut self,
2185         key: &KeyDescriptor,
2186         key_type: KeyType,
2187         load_bits: KeyEntryLoadBits,
2188         caller_uid: u32,
2189         check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2190     ) -> Result<(KeyIdGuard, KeyEntry)> {
2191         // KEY ID LOCK 1/2
2192         // If we got a key descriptor with a key id we can get the lock right away.
2193         // Otherwise we have to defer it until we know the key id.
2194         let key_id_guard = match key.domain {
2195             Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2196             _ => None,
2197         };
2198 
2199         let tx = self
2200             .conn
2201             .unchecked_transaction()
2202             .context(ks_err!("Failed to initialize transaction."))?;
2203 
2204         // Load the key_id and complete the access control tuple.
2205         let (key_id, access_key_descriptor, access_vector) =
2206             Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
2207 
2208         // Perform access control. It is vital that we return here if the permission is denied.
2209         // So do not touch that '?' at the end.
2210         check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
2211 
2212         // KEY ID LOCK 2/2
2213         // If we did not get a key id lock by now, it was because we got a key descriptor
2214         // without a key id. At this point we got the key id, so we can try and get a lock.
2215         // However, we cannot block here, because we are in the middle of the transaction.
2216         // So first we try to get the lock non blocking. If that fails, we roll back the
2217         // transaction and block until we get the lock. After we successfully got the lock,
2218         // we start a new transaction and load the access tuple again.
2219         //
2220         // We don't need to perform access control again, because we already established
2221         // that the caller had access to the given key. But we need to make sure that the
2222         // key id still exists. So we have to load the key entry by key id this time.
2223         let (key_id_guard, tx) = match key_id_guard {
2224             None => match KEY_ID_LOCK.try_get(key_id) {
2225                 None => {
2226                     // Roll back the transaction.
2227                     tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
2228 
2229                     // Block until we have a key id lock.
2230                     let key_id_guard = KEY_ID_LOCK.get(key_id);
2231 
2232                     // Create a new transaction.
2233                     let tx = self
2234                         .conn
2235                         .unchecked_transaction()
2236                         .context(ks_err!("Failed to initialize transaction."))?;
2237 
2238                     Self::load_access_tuple(
2239                         &tx,
2240                         // This time we have to load the key by the retrieved key id, because the
2241                         // alias may have been rebound after we rolled back the transaction.
2242                         &KeyDescriptor {
2243                             domain: Domain::KEY_ID,
2244                             nspace: key_id,
2245                             ..Default::default()
2246                         },
2247                         key_type,
2248                         caller_uid,
2249                     )
2250                     .context(ks_err!("(deferred key lock)"))?;
2251                     (key_id_guard, tx)
2252                 }
2253                 Some(l) => (l, tx),
2254             },
2255             Some(key_id_guard) => (key_id_guard, tx),
2256         };
2257 
2258         let key_entry =
2259             Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
2260 
2261         tx.commit().context(ks_err!("Failed to commit transaction."))?;
2262 
2263         Ok((key_id_guard, key_entry))
2264     }
2265 
mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool>2266     fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
2267         let updated = tx
2268             .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2269             .context("Trying to delete keyentry.")?;
2270         tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2271             .context("Trying to delete keymetadata.")?;
2272         tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2273             .context("Trying to delete keyparameters.")?;
2274         tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2275             .context("Trying to delete grants.")?;
2276         Ok(updated != 0)
2277     }
2278 
2279     /// Marks the given key as unreferenced and removes all of the grants to this key.
2280     /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
unbind_key( &mut self, key: &KeyDescriptor, key_type: KeyType, caller_uid: u32, check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>, ) -> Result<()>2281     pub fn unbind_key(
2282         &mut self,
2283         key: &KeyDescriptor,
2284         key_type: KeyType,
2285         caller_uid: u32,
2286         check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2287     ) -> Result<()> {
2288         let _wp = wd::watch("KeystoreDB::unbind_key");
2289 
2290         self.with_transaction(Immediate("TX_unbind_key"), |tx| {
2291             let (key_id, access_key_descriptor, access_vector) =
2292                 Self::load_access_tuple(tx, key, key_type, caller_uid)
2293                     .context("Trying to get access tuple.")?;
2294 
2295             // Perform access control. It is vital that we return here if the permission is denied.
2296             // So do not touch that '?' at the end.
2297             check_permission(&access_key_descriptor, access_vector)
2298                 .context("While checking permission.")?;
2299 
2300             Self::mark_unreferenced(tx, key_id)
2301                 .map(|need_gc| (need_gc, ()))
2302                 .context("Trying to mark the key unreferenced.")
2303         })
2304         .context(ks_err!())
2305     }
2306 
get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid>2307     fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2308         tx.query_row(
2309             "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2310             params![key_id],
2311             |row| row.get(0),
2312         )
2313         .context(ks_err!())
2314     }
2315 
2316     /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2317     /// This leaves all of the blob entries orphaned for subsequent garbage collection.
unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()>2318     pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
2319         let _wp = wd::watch("KeystoreDB::unbind_keys_for_namespace");
2320 
2321         if !(domain == Domain::APP || domain == Domain::SELINUX) {
2322             return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
2323         }
2324         self.with_transaction(Immediate("TX_unbind_keys_for_namespace"), |tx| {
2325             tx.execute(
2326                 "DELETE FROM persistent.keymetadata
2327                 WHERE keyentryid IN (
2328                     SELECT id FROM persistent.keyentry
2329                     WHERE domain = ? AND namespace = ? AND key_type = ?
2330                 );",
2331                 params![domain.0, namespace, KeyType::Client],
2332             )
2333             .context("Trying to delete keymetadata.")?;
2334             tx.execute(
2335                 "DELETE FROM persistent.keyparameter
2336                 WHERE keyentryid IN (
2337                     SELECT id FROM persistent.keyentry
2338                     WHERE domain = ? AND namespace = ? AND key_type = ?
2339                 );",
2340                 params![domain.0, namespace, KeyType::Client],
2341             )
2342             .context("Trying to delete keyparameters.")?;
2343             tx.execute(
2344                 "DELETE FROM persistent.grant
2345                 WHERE keyentryid IN (
2346                     SELECT id FROM persistent.keyentry
2347                     WHERE domain = ? AND namespace = ? AND key_type = ?
2348                 );",
2349                 params![domain.0, namespace, KeyType::Client],
2350             )
2351             .context("Trying to delete grants.")?;
2352             tx.execute(
2353                 "DELETE FROM persistent.keyentry
2354                  WHERE domain = ? AND namespace = ? AND key_type = ?;",
2355                 params![domain.0, namespace, KeyType::Client],
2356             )
2357             .context("Trying to delete keyentry.")?;
2358             Ok(()).need_gc()
2359         })
2360         .context(ks_err!())
2361     }
2362 
cleanup_unreferenced(tx: &Transaction) -> Result<()>2363     fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2364         let _wp = wd::watch("KeystoreDB::cleanup_unreferenced");
2365         {
2366             tx.execute(
2367                 "DELETE FROM persistent.keymetadata
2368             WHERE keyentryid IN (
2369                 SELECT id FROM persistent.keyentry
2370                 WHERE state = ?
2371             );",
2372                 params![KeyLifeCycle::Unreferenced],
2373             )
2374             .context("Trying to delete keymetadata.")?;
2375             tx.execute(
2376                 "DELETE FROM persistent.keyparameter
2377             WHERE keyentryid IN (
2378                 SELECT id FROM persistent.keyentry
2379                 WHERE state = ?
2380             );",
2381                 params![KeyLifeCycle::Unreferenced],
2382             )
2383             .context("Trying to delete keyparameters.")?;
2384             tx.execute(
2385                 "DELETE FROM persistent.grant
2386             WHERE keyentryid IN (
2387                 SELECT id FROM persistent.keyentry
2388                 WHERE state = ?
2389             );",
2390                 params![KeyLifeCycle::Unreferenced],
2391             )
2392             .context("Trying to delete grants.")?;
2393             tx.execute(
2394                 "DELETE FROM persistent.keyentry
2395                 WHERE state = ?;",
2396                 params![KeyLifeCycle::Unreferenced],
2397             )
2398             .context("Trying to delete keyentry.")?;
2399             Result::<()>::Ok(())
2400         }
2401         .context(ks_err!())
2402     }
2403 
2404     /// Delete the keys created on behalf of the user, denoted by the user id.
2405     /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2406     /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2407     /// The caller of this function should notify the gc if the returned value is true.
unbind_keys_for_user( &mut self, user_id: u32, keep_non_super_encrypted_keys: bool, ) -> Result<()>2408     pub fn unbind_keys_for_user(
2409         &mut self,
2410         user_id: u32,
2411         keep_non_super_encrypted_keys: bool,
2412     ) -> Result<()> {
2413         let _wp = wd::watch("KeystoreDB::unbind_keys_for_user");
2414 
2415         self.with_transaction(Immediate("TX_unbind_keys_for_user"), |tx| {
2416             let mut stmt = tx
2417                 .prepare(&format!(
2418                     "SELECT id from persistent.keyentry
2419                      WHERE (
2420                          key_type = ?
2421                          AND domain = ?
2422                          AND cast ( (namespace/{aid_user_offset}) as int) = ?
2423                          AND state = ?
2424                      ) OR (
2425                          key_type = ?
2426                          AND namespace = ?
2427                          AND state = ?
2428                      );",
2429                     aid_user_offset = AID_USER_OFFSET
2430                 ))
2431                 .context(concat!(
2432                     "In unbind_keys_for_user. ",
2433                     "Failed to prepare the query to find the keys created by apps."
2434                 ))?;
2435 
2436             let mut rows = stmt
2437                 .query(params![
2438                     // WHERE client key:
2439                     KeyType::Client,
2440                     Domain::APP.0 as u32,
2441                     user_id,
2442                     KeyLifeCycle::Live,
2443                     // OR super key:
2444                     KeyType::Super,
2445                     user_id,
2446                     KeyLifeCycle::Live
2447                 ])
2448                 .context(ks_err!("Failed to query the keys created by apps."))?;
2449 
2450             let mut key_ids: Vec<i64> = Vec::new();
2451             db_utils::with_rows_extract_all(&mut rows, |row| {
2452                 key_ids
2453                     .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2454                 Ok(())
2455             })
2456             .context(ks_err!())?;
2457 
2458             let mut notify_gc = false;
2459             for key_id in key_ids {
2460                 if keep_non_super_encrypted_keys {
2461                     // Load metadata and filter out non-super-encrypted keys.
2462                     if let (_, Some((_, blob_metadata)), _, _) =
2463                         Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2464                             .context(ks_err!("Trying to load blob info."))?
2465                     {
2466                         if blob_metadata.encrypted_by().is_none() {
2467                             continue;
2468                         }
2469                     }
2470                 }
2471                 notify_gc = Self::mark_unreferenced(tx, key_id)
2472                     .context("In unbind_keys_for_user.")?
2473                     || notify_gc;
2474             }
2475             Ok(()).do_gc(notify_gc)
2476         })
2477         .context(ks_err!())
2478     }
2479 
2480     /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2481     /// This runs when the user's lock screen is being changed to Swipe or None.
2482     ///
2483     /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2484     /// such keys also require user authentication.  Keystore's concept of user authentication is
2485     /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2486     /// authentication is no longer possible.  In contrast, keys that just require that the device
2487     /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2488     /// is always considered "unlocked" in that case.
unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()>2489     pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2490         let _wp = wd::watch("KeystoreDB::unbind_auth_bound_keys_for_user");
2491 
2492         self.with_transaction(Immediate("TX_unbind_auth_bound_keys_for_user"), |tx| {
2493             let mut stmt = tx
2494                 .prepare(&format!(
2495                     "SELECT id from persistent.keyentry
2496                      WHERE key_type = ?
2497                      AND domain = ?
2498                      AND cast ( (namespace/{aid_user_offset}) as int) = ?
2499                      AND state = ?;",
2500                     aid_user_offset = AID_USER_OFFSET
2501                 ))
2502                 .context(concat!(
2503                     "In unbind_auth_bound_keys_for_user. ",
2504                     "Failed to prepare the query to find the keys created by apps."
2505                 ))?;
2506 
2507             let mut rows = stmt
2508                 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2509                 .context(ks_err!("Failed to query the keys created by apps."))?;
2510 
2511             let mut key_ids: Vec<i64> = Vec::new();
2512             db_utils::with_rows_extract_all(&mut rows, |row| {
2513                 key_ids
2514                     .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2515                 Ok(())
2516             })
2517             .context(ks_err!())?;
2518 
2519             let mut notify_gc = false;
2520             let mut num_unbound = 0;
2521             for key_id in key_ids {
2522                 // Load the key parameters and filter out non-auth-bound keys.  To identify
2523                 // auth-bound keys, use the presence of UserSecureID.  The absence of NoAuthRequired
2524                 // could also be used, but UserSecureID is what Keystore treats as authoritative
2525                 // when actually enforcing the key parameters (it might not matter, though).
2526                 let params = Self::load_key_parameters(key_id, tx)
2527                     .context("Failed to load key parameters.")?;
2528                 let is_auth_bound_key = params.iter().any(|kp| {
2529                     matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2530                 });
2531                 if is_auth_bound_key {
2532                     notify_gc = Self::mark_unreferenced(tx, key_id)
2533                         .context("In unbind_auth_bound_keys_for_user.")?
2534                         || notify_gc;
2535                     num_unbound += 1;
2536                 }
2537             }
2538             log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2539             Ok(()).do_gc(notify_gc)
2540         })
2541         .context(ks_err!())
2542     }
2543 
load_key_components( tx: &Transaction, load_bits: KeyEntryLoadBits, key_id: i64, ) -> Result<KeyEntry>2544     fn load_key_components(
2545         tx: &Transaction,
2546         load_bits: KeyEntryLoadBits,
2547         key_id: i64,
2548     ) -> Result<KeyEntry> {
2549         let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
2550 
2551         let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
2552             Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
2553 
2554         let parameters = Self::load_key_parameters(key_id, tx)
2555             .context("In load_key_components: Trying to load key parameters.")?;
2556 
2557         let km_uuid = Self::get_key_km_uuid(tx, key_id)
2558             .context("In load_key_components: Trying to get KM uuid.")?;
2559 
2560         Ok(KeyEntry {
2561             id: key_id,
2562             key_blob_info,
2563             cert: cert_blob,
2564             cert_chain: cert_chain_blob,
2565             km_uuid,
2566             parameters,
2567             metadata,
2568             pure_cert: !has_km_blob,
2569         })
2570     }
2571 
2572     /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2573     /// aliases are greater than the specified 'start_past_alias'. If no value
2574     /// is provided, returns all KeyDescriptors.
2575     /// The key descriptors will have the domain, nspace, and alias field set.
2576     /// The returned list will be sorted by alias.
2577     /// Domain must be APP or SELINUX, the caller must make sure of that.
list_past_alias( &mut self, domain: Domain, namespace: i64, key_type: KeyType, start_past_alias: Option<&str>, ) -> Result<Vec<KeyDescriptor>>2578     pub fn list_past_alias(
2579         &mut self,
2580         domain: Domain,
2581         namespace: i64,
2582         key_type: KeyType,
2583         start_past_alias: Option<&str>,
2584     ) -> Result<Vec<KeyDescriptor>> {
2585         let _wp = wd::watch("KeystoreDB::list_past_alias");
2586 
2587         let query = format!(
2588             "SELECT DISTINCT alias FROM persistent.keyentry
2589                      WHERE domain = ?
2590                      AND namespace = ?
2591                      AND alias IS NOT NULL
2592                      AND state = ?
2593                      AND key_type = ?
2594                      {}
2595                      ORDER BY alias ASC;",
2596             if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2597         );
2598 
2599         self.with_transaction(TransactionBehavior::Deferred, |tx| {
2600             let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2601 
2602             let mut rows = match start_past_alias {
2603                 Some(past_alias) => stmt
2604                     .query(params![
2605                         domain.0 as u32,
2606                         namespace,
2607                         KeyLifeCycle::Live,
2608                         key_type,
2609                         past_alias
2610                     ])
2611                     .context(ks_err!("Failed to query."))?,
2612                 None => stmt
2613                     .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2614                     .context(ks_err!("Failed to query."))?,
2615             };
2616 
2617             let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2618             db_utils::with_rows_extract_all(&mut rows, |row| {
2619                 descriptors.push(KeyDescriptor {
2620                     domain,
2621                     nspace: namespace,
2622                     alias: Some(row.get(0).context("Trying to extract alias.")?),
2623                     blob: None,
2624                 });
2625                 Ok(())
2626             })
2627             .context(ks_err!("Failed to extract rows."))?;
2628             Ok(descriptors).no_gc()
2629         })
2630     }
2631 
2632     /// Returns a number of KeyDescriptors in the selected domain/namespace.
2633     /// Domain must be APP or SELINUX, the caller must make sure of that.
count_keys( &mut self, domain: Domain, namespace: i64, key_type: KeyType, ) -> Result<usize>2634     pub fn count_keys(
2635         &mut self,
2636         domain: Domain,
2637         namespace: i64,
2638         key_type: KeyType,
2639     ) -> Result<usize> {
2640         let _wp = wd::watch("KeystoreDB::countKeys");
2641 
2642         let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2643             tx.query_row(
2644                 "SELECT COUNT(alias) FROM persistent.keyentry
2645                      WHERE domain = ?
2646                      AND namespace = ?
2647                      AND alias IS NOT NULL
2648                      AND state = ?
2649                      AND key_type = ?;",
2650                 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2651                 |row| row.get(0),
2652             )
2653             .context(ks_err!("Failed to count number of keys."))
2654             .no_gc()
2655         })?;
2656         Ok(num_keys)
2657     }
2658 
2659     /// Adds a grant to the grant table.
2660     /// Like `load_key_entry` this function loads the access tuple before
2661     /// it uses the callback for a permission check. Upon success,
2662     /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2663     /// grant table. The new row will have a randomized id, which is used as
2664     /// grant id in the namespace field of the resulting KeyDescriptor.
grant( &mut self, key: &KeyDescriptor, caller_uid: u32, grantee_uid: u32, access_vector: KeyPermSet, check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>, ) -> Result<KeyDescriptor>2665     pub fn grant(
2666         &mut self,
2667         key: &KeyDescriptor,
2668         caller_uid: u32,
2669         grantee_uid: u32,
2670         access_vector: KeyPermSet,
2671         check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
2672     ) -> Result<KeyDescriptor> {
2673         let _wp = wd::watch("KeystoreDB::grant");
2674 
2675         self.with_transaction(Immediate("TX_grant"), |tx| {
2676             // Load the key_id and complete the access control tuple.
2677             // We ignore the access vector here because grants cannot be granted.
2678             // The access vector returned here expresses the permissions the
2679             // grantee has if key.domain == Domain::GRANT. But this vector
2680             // cannot include the grant permission by design, so there is no way the
2681             // subsequent permission check can pass.
2682             // We could check key.domain == Domain::GRANT and fail early.
2683             // But even if we load the access tuple by grant here, the permission
2684             // check denies the attempt to create a grant by grant descriptor.
2685             let (key_id, access_key_descriptor, _) =
2686                 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
2687 
2688             // Perform access control. It is vital that we return here if the permission
2689             // was denied. So do not touch that '?' at the end of the line.
2690             // This permission check checks if the caller has the grant permission
2691             // for the given key and in addition to all of the permissions
2692             // expressed in `access_vector`.
2693             check_permission(&access_key_descriptor, &access_vector)
2694                 .context(ks_err!("check_permission failed"))?;
2695 
2696             let grant_id = if let Some(grant_id) = tx
2697                 .query_row(
2698                     "SELECT id FROM persistent.grant
2699                 WHERE keyentryid = ? AND grantee = ?;",
2700                     params![key_id, grantee_uid],
2701                     |row| row.get(0),
2702                 )
2703                 .optional()
2704                 .context(ks_err!("Failed get optional existing grant id."))?
2705             {
2706                 tx.execute(
2707                     "UPDATE persistent.grant
2708                     SET access_vector = ?
2709                     WHERE id = ?;",
2710                     params![i32::from(access_vector), grant_id],
2711                 )
2712                 .context(ks_err!("Failed to update existing grant."))?;
2713                 grant_id
2714             } else {
2715                 Self::insert_with_retry(|id| {
2716                     tx.execute(
2717                         "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2718                         VALUES (?, ?, ?, ?);",
2719                         params![id, grantee_uid, key_id, i32::from(access_vector)],
2720                     )
2721                 })
2722                 .context(ks_err!())?
2723             };
2724 
2725             Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
2726                 .no_gc()
2727         })
2728     }
2729 
2730     /// This function checks permissions like `grant` and `load_key_entry`
2731     /// before removing a grant from the grant table.
ungrant( &mut self, key: &KeyDescriptor, caller_uid: u32, grantee_uid: u32, check_permission: impl Fn(&KeyDescriptor) -> Result<()>, ) -> Result<()>2732     pub fn ungrant(
2733         &mut self,
2734         key: &KeyDescriptor,
2735         caller_uid: u32,
2736         grantee_uid: u32,
2737         check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2738     ) -> Result<()> {
2739         let _wp = wd::watch("KeystoreDB::ungrant");
2740 
2741         self.with_transaction(Immediate("TX_ungrant"), |tx| {
2742             // Load the key_id and complete the access control tuple.
2743             // We ignore the access vector here because grants cannot be granted.
2744             let (key_id, access_key_descriptor, _) =
2745                 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
2746 
2747             // Perform access control. We must return here if the permission
2748             // was denied. So do not touch the '?' at the end of this line.
2749             check_permission(&access_key_descriptor)
2750                 .context(ks_err!("check_permission failed."))?;
2751 
2752             tx.execute(
2753                 "DELETE FROM persistent.grant
2754                 WHERE keyentryid = ? AND grantee = ?;",
2755                 params![key_id, grantee_uid],
2756             )
2757             .context("Failed to delete grant.")?;
2758 
2759             Ok(()).no_gc()
2760         })
2761     }
2762 
2763     // Generates a random id and passes it to the given function, which will
2764     // try to insert it into a database.  If that insertion fails, retry;
2765     // otherwise return the id.
insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64>2766     fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2767         loop {
2768             let newid: i64 = match random() {
2769                 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2770                 i => i,
2771             };
2772             match inserter(newid) {
2773                 // If the id already existed, try again.
2774                 Err(rusqlite::Error::SqliteFailure(
2775                     libsqlite3_sys::Error {
2776                         code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2777                         extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2778                     },
2779                     _,
2780                 )) => (),
2781                 Err(e) => {
2782                     return Err(e).context(ks_err!("failed to insert into database."));
2783                 }
2784                 _ => return Ok(newid),
2785             }
2786         }
2787     }
2788 
2789     /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
insert_auth_token(&mut self, auth_token: &HardwareAuthToken)2790     pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
2791         self.perboot
2792             .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
2793     }
2794 
2795     /// Find the newest auth token matching the given predicate.
find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry> where F: Fn(&AuthTokenEntry) -> bool,2796     pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
2797     where
2798         F: Fn(&AuthTokenEntry) -> bool,
2799     {
2800         self.perboot.find_auth_token_entry(p)
2801     }
2802 
2803     /// Load descriptor of a key by key id
load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>>2804     pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2805         let _wp = wd::watch("KeystoreDB::load_key_descriptor");
2806 
2807         self.with_transaction(TransactionBehavior::Deferred, |tx| {
2808             tx.query_row(
2809                 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2810                 params![key_id],
2811                 |row| {
2812                     Ok(KeyDescriptor {
2813                         domain: Domain(row.get(0)?),
2814                         nspace: row.get(1)?,
2815                         alias: row.get(2)?,
2816                         blob: None,
2817                     })
2818                 },
2819             )
2820             .optional()
2821             .context("Trying to load key descriptor")
2822             .no_gc()
2823         })
2824         .context(ks_err!())
2825     }
2826 
2827     /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2828     /// (for the given user_id).
2829     /// This is helpful for finding out which apps will have their keys invalidated when
2830     /// the user changes biometrics enrollment or removes their LSKF.
get_app_uids_affected_by_sid( &mut self, user_id: i32, secure_user_id: i64, ) -> Result<Vec<i64>>2831     pub fn get_app_uids_affected_by_sid(
2832         &mut self,
2833         user_id: i32,
2834         secure_user_id: i64,
2835     ) -> Result<Vec<i64>> {
2836         let _wp = wd::watch("KeystoreDB::get_app_uids_affected_by_sid");
2837 
2838         let ids = self.with_transaction(Immediate("TX_get_app_uids_affected_by_sid"), |tx| {
2839             let mut stmt = tx
2840                 .prepare(&format!(
2841                     "SELECT id, namespace from persistent.keyentry
2842                      WHERE key_type = ?
2843                      AND domain = ?
2844                      AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2845                      AND state = ?;",
2846                 ))
2847                 .context(concat!(
2848                     "In get_app_uids_affected_by_sid, ",
2849                     "failed to prepare the query to find the keys created by apps."
2850                 ))?;
2851 
2852             let mut rows = stmt
2853                 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2854                 .context(ks_err!("Failed to query the keys created by apps."))?;
2855 
2856             let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2857             db_utils::with_rows_extract_all(&mut rows, |row| {
2858                 key_ids_and_app_uids.insert(
2859                     row.get(0).context("Failed to read key id of a key created by an app.")?,
2860                     row.get(1).context("Failed to read the app uid")?,
2861                 );
2862                 Ok(())
2863             })?;
2864             Ok(key_ids_and_app_uids).no_gc()
2865         })?;
2866         let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2867         for (key_id, app_uid) in ids {
2868             // Read the key parameters for each key in its own transaction. It is OK to ignore
2869             // an error to get the properties of a particular key since it might have been deleted
2870             // under our feet after the previous transaction concluded. If the key was deleted
2871             // then it is no longer applicable if it was auth-bound or not.
2872             if let Ok(is_key_bound_to_sid) =
2873                 self.with_transaction(Immediate("TX_get_app_uids_affects_by_sid 2"), |tx| {
2874                     let params = Self::load_key_parameters(key_id, tx)
2875                         .context("Failed to load key parameters.")?;
2876                     // Check if the key is bound to this secure user ID.
2877                     let is_key_bound_to_sid = params.iter().any(|kp| {
2878                         matches!(
2879                             kp.key_parameter_value(),
2880                             KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2881                         )
2882                     });
2883                     Ok(is_key_bound_to_sid).no_gc()
2884                 })
2885             {
2886                 if is_key_bound_to_sid {
2887                     app_uids_affected_by_sid.insert(app_uid);
2888                 }
2889             }
2890         }
2891 
2892         let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2893         Ok(app_uids_vec)
2894     }
2895 }
2896 
2897 #[cfg(test)]
2898 pub mod tests {
2899 
2900     use super::*;
2901     use crate::key_parameter::{
2902         Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2903         KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2904     };
2905     use crate::key_perm_set;
2906     use crate::permission::{KeyPerm, KeyPermSet};
2907     use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
2908     use keystore2_test_utils::TempDir;
2909     use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2910         HardwareAuthToken::HardwareAuthToken,
2911         HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
2912     };
2913     use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
2914         Timestamp::Timestamp,
2915     };
2916     use std::cell::RefCell;
2917     use std::collections::BTreeMap;
2918     use std::fmt::Write;
2919     use std::sync::atomic::{AtomicU8, Ordering};
2920     use std::sync::Arc;
2921     use std::thread;
2922     use std::time::{Duration, SystemTime};
2923     use crate::utils::AesGcm;
2924     #[cfg(disabled)]
2925     use std::time::Instant;
2926 
new_test_db() -> Result<KeystoreDB>2927     pub fn new_test_db() -> Result<KeystoreDB> {
2928         let conn = KeystoreDB::make_connection("file::memory:")?;
2929 
2930         let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
2931         db.with_transaction(Immediate("TX_new_test_db"), |tx| {
2932             KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
2933         })?;
2934         Ok(db)
2935     }
2936 
rebind_alias( db: &mut KeystoreDB, newid: &KeyIdGuard, alias: &str, domain: Domain, namespace: i64, ) -> Result<bool>2937     fn rebind_alias(
2938         db: &mut KeystoreDB,
2939         newid: &KeyIdGuard,
2940         alias: &str,
2941         domain: Domain,
2942         namespace: i64,
2943     ) -> Result<bool> {
2944         db.with_transaction(Immediate("TX_rebind_alias"), |tx| {
2945             KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
2946         })
2947         .context(ks_err!())
2948     }
2949 
2950     #[test]
datetime() -> Result<()>2951     fn datetime() -> Result<()> {
2952         let conn = Connection::open_in_memory()?;
2953         conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
2954         let now = SystemTime::now();
2955         let duration = Duration::from_secs(1000);
2956         let then = now.checked_sub(duration).unwrap();
2957         let soon = now.checked_add(duration).unwrap();
2958         conn.execute(
2959             "INSERT INTO test (ts) VALUES (?), (?), (?);",
2960             params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2961         )?;
2962         let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
2963         let mut rows = stmt.query([])?;
2964         assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2965         assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2966         assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2967         assert!(rows.next()?.is_none());
2968         assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2969         assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2970         assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2971         Ok(())
2972     }
2973 
2974     // Ensure that we're using the "injected" random function, not the real one.
2975     #[test]
test_mocked_random()2976     fn test_mocked_random() {
2977         let rand1 = random();
2978         let rand2 = random();
2979         let rand3 = random();
2980         if rand1 == rand2 {
2981             assert_eq!(rand2 + 1, rand3);
2982         } else {
2983             assert_eq!(rand1 + 1, rand2);
2984             assert_eq!(rand2, rand3);
2985         }
2986     }
2987 
2988     // Test that we have the correct tables.
2989     #[test]
test_tables() -> Result<()>2990     fn test_tables() -> Result<()> {
2991         let db = new_test_db()?;
2992         let tables = db
2993             .conn
2994             .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
2995             .query_map(params![], |row| row.get(0))?
2996             .collect::<rusqlite::Result<Vec<String>>>()?;
2997         assert_eq!(tables.len(), 6);
2998         assert_eq!(tables[0], "blobentry");
2999         assert_eq!(tables[1], "blobmetadata");
3000         assert_eq!(tables[2], "grant");
3001         assert_eq!(tables[3], "keyentry");
3002         assert_eq!(tables[4], "keymetadata");
3003         assert_eq!(tables[5], "keyparameter");
3004         Ok(())
3005     }
3006 
3007     #[test]
test_auth_token_table_invariant() -> Result<()>3008     fn test_auth_token_table_invariant() -> Result<()> {
3009         let mut db = new_test_db()?;
3010         let auth_token1 = HardwareAuthToken {
3011             challenge: i64::MAX,
3012             userId: 200,
3013             authenticatorId: 200,
3014             authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3015             timestamp: Timestamp { milliSeconds: 500 },
3016             mac: String::from("mac").into_bytes(),
3017         };
3018         db.insert_auth_token(&auth_token1);
3019         let auth_tokens_returned = get_auth_tokens(&db);
3020         assert_eq!(auth_tokens_returned.len(), 1);
3021 
3022         // insert another auth token with the same values for the columns in the UNIQUE constraint
3023         // of the auth token table and different value for timestamp
3024         let auth_token2 = HardwareAuthToken {
3025             challenge: i64::MAX,
3026             userId: 200,
3027             authenticatorId: 200,
3028             authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3029             timestamp: Timestamp { milliSeconds: 600 },
3030             mac: String::from("mac").into_bytes(),
3031         };
3032 
3033         db.insert_auth_token(&auth_token2);
3034         let mut auth_tokens_returned = get_auth_tokens(&db);
3035         assert_eq!(auth_tokens_returned.len(), 1);
3036 
3037         if let Some(auth_token) = auth_tokens_returned.pop() {
3038             assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3039         }
3040 
3041         // insert another auth token with the different values for the columns in the UNIQUE
3042         // constraint of the auth token table
3043         let auth_token3 = HardwareAuthToken {
3044             challenge: i64::MAX,
3045             userId: 201,
3046             authenticatorId: 200,
3047             authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3048             timestamp: Timestamp { milliSeconds: 600 },
3049             mac: String::from("mac").into_bytes(),
3050         };
3051 
3052         db.insert_auth_token(&auth_token3);
3053         let auth_tokens_returned = get_auth_tokens(&db);
3054         assert_eq!(auth_tokens_returned.len(), 2);
3055 
3056         Ok(())
3057     }
3058 
3059     // utility function for test_auth_token_table_invariant()
get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry>3060     fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3061         db.perboot.get_all_auth_token_entries()
3062     }
3063 
create_key_entry( db: &mut KeystoreDB, domain: &Domain, namespace: &i64, key_type: KeyType, km_uuid: &Uuid, ) -> Result<KeyIdGuard>3064     fn create_key_entry(
3065         db: &mut KeystoreDB,
3066         domain: &Domain,
3067         namespace: &i64,
3068         key_type: KeyType,
3069         km_uuid: &Uuid,
3070     ) -> Result<KeyIdGuard> {
3071         db.with_transaction(Immediate("TX_create_key_entry"), |tx| {
3072             KeystoreDB::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
3073         })
3074     }
3075 
3076     #[test]
test_persistence_for_files() -> Result<()>3077     fn test_persistence_for_files() -> Result<()> {
3078         let temp_dir = TempDir::new("persistent_db_test")?;
3079         let mut db = KeystoreDB::new(temp_dir.path(), None)?;
3080 
3081         create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3082         let entries = get_keyentry(&db)?;
3083         assert_eq!(entries.len(), 1);
3084 
3085         let db = KeystoreDB::new(temp_dir.path(), None)?;
3086 
3087         let entries_new = get_keyentry(&db)?;
3088         assert_eq!(entries, entries_new);
3089         Ok(())
3090     }
3091 
3092     #[test]
test_create_key_entry() -> Result<()>3093     fn test_create_key_entry() -> Result<()> {
3094         fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3095             (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
3096         }
3097 
3098         let mut db = new_test_db()?;
3099 
3100         create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3101         create_key_entry(&mut db, &Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
3102 
3103         let entries = get_keyentry(&db)?;
3104         assert_eq!(entries.len(), 2);
3105         assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3106         assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
3107 
3108         // Test that we must pass in a valid Domain.
3109         check_result_is_error_containing_string(
3110             create_key_entry(&mut db, &Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
3111             &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
3112         );
3113         check_result_is_error_containing_string(
3114             create_key_entry(&mut db, &Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
3115             &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
3116         );
3117         check_result_is_error_containing_string(
3118             create_key_entry(&mut db, &Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
3119             &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
3120         );
3121 
3122         Ok(())
3123     }
3124 
3125     #[test]
test_rebind_alias() -> Result<()>3126     fn test_rebind_alias() -> Result<()> {
3127         fn extractor(
3128             ke: &KeyEntryRow,
3129         ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3130             (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
3131         }
3132 
3133         let mut db = new_test_db()?;
3134         create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3135         create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3136         let entries = get_keyentry(&db)?;
3137         assert_eq!(entries.len(), 2);
3138         assert_eq!(
3139             extractor(&entries[0]),
3140             (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3141         );
3142         assert_eq!(
3143             extractor(&entries[1]),
3144             (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3145         );
3146 
3147         // Test that the first call to rebind_alias sets the alias.
3148         rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
3149         let entries = get_keyentry(&db)?;
3150         assert_eq!(entries.len(), 2);
3151         assert_eq!(
3152             extractor(&entries[0]),
3153             (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3154         );
3155         assert_eq!(
3156             extractor(&entries[1]),
3157             (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3158         );
3159 
3160         // Test that the second call to rebind_alias also empties the old one.
3161         rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
3162         let entries = get_keyentry(&db)?;
3163         assert_eq!(entries.len(), 2);
3164         assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3165         assert_eq!(
3166             extractor(&entries[1]),
3167             (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3168         );
3169 
3170         // Test that we must pass in a valid Domain.
3171         check_result_is_error_containing_string(
3172             rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
3173             &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
3174         );
3175         check_result_is_error_containing_string(
3176             rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
3177             &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
3178         );
3179         check_result_is_error_containing_string(
3180             rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
3181             &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
3182         );
3183 
3184         // Test that we correctly handle setting an alias for something that does not exist.
3185         check_result_is_error_containing_string(
3186             rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
3187             "Expected to update a single entry but instead updated 0",
3188         );
3189         // Test that we correctly abort the transaction in this case.
3190         let entries = get_keyentry(&db)?;
3191         assert_eq!(entries.len(), 2);
3192         assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3193         assert_eq!(
3194             extractor(&entries[1]),
3195             (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3196         );
3197 
3198         Ok(())
3199     }
3200 
3201     #[test]
test_grant_ungrant() -> Result<()>3202     fn test_grant_ungrant() -> Result<()> {
3203         const CALLER_UID: u32 = 15;
3204         const GRANTEE_UID: u32 = 12;
3205         const SELINUX_NAMESPACE: i64 = 7;
3206 
3207         let mut db = new_test_db()?;
3208         db.conn.execute(
3209             "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3210                 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3211             params![KEYSTORE_UUID, KEYSTORE_UUID],
3212         )?;
3213         let app_key = KeyDescriptor {
3214             domain: super::Domain::APP,
3215             nspace: 0,
3216             alias: Some("key".to_string()),
3217             blob: None,
3218         };
3219         const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3220         const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
3221 
3222         // Reset totally predictable random number generator in case we
3223         // are not the first test running on this thread.
3224         reset_random();
3225         let next_random = 0i64;
3226 
3227         let app_granted_key = db
3228             .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
3229                 assert_eq!(*a, PVEC1);
3230                 assert_eq!(
3231                     *k,
3232                     KeyDescriptor {
3233                         domain: super::Domain::APP,
3234                         // namespace must be set to the caller_uid.
3235                         nspace: CALLER_UID as i64,
3236                         alias: Some("key".to_string()),
3237                         blob: None,
3238                     }
3239                 );
3240                 Ok(())
3241             })
3242             .unwrap();
3243 
3244         assert_eq!(
3245             app_granted_key,
3246             KeyDescriptor {
3247                 domain: super::Domain::GRANT,
3248                 // The grantid is next_random due to the mock random number generator.
3249                 nspace: next_random,
3250                 alias: None,
3251                 blob: None,
3252             }
3253         );
3254 
3255         let selinux_key = KeyDescriptor {
3256             domain: super::Domain::SELINUX,
3257             nspace: SELINUX_NAMESPACE,
3258             alias: Some("yek".to_string()),
3259             blob: None,
3260         };
3261 
3262         let selinux_granted_key = db
3263             .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
3264                 assert_eq!(*a, PVEC1);
3265                 assert_eq!(
3266                     *k,
3267                     KeyDescriptor {
3268                         domain: super::Domain::SELINUX,
3269                         // namespace must be the supplied SELinux
3270                         // namespace.
3271                         nspace: SELINUX_NAMESPACE,
3272                         alias: Some("yek".to_string()),
3273                         blob: None,
3274                     }
3275                 );
3276                 Ok(())
3277             })
3278             .unwrap();
3279 
3280         assert_eq!(
3281             selinux_granted_key,
3282             KeyDescriptor {
3283                 domain: super::Domain::GRANT,
3284                 // The grantid is next_random + 1 due to the mock random number generator.
3285                 nspace: next_random + 1,
3286                 alias: None,
3287                 blob: None,
3288             }
3289         );
3290 
3291         // This should update the existing grant with PVEC2.
3292         let selinux_granted_key = db
3293             .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
3294                 assert_eq!(*a, PVEC2);
3295                 assert_eq!(
3296                     *k,
3297                     KeyDescriptor {
3298                         domain: super::Domain::SELINUX,
3299                         // namespace must be the supplied SELinux
3300                         // namespace.
3301                         nspace: SELINUX_NAMESPACE,
3302                         alias: Some("yek".to_string()),
3303                         blob: None,
3304                     }
3305                 );
3306                 Ok(())
3307             })
3308             .unwrap();
3309 
3310         assert_eq!(
3311             selinux_granted_key,
3312             KeyDescriptor {
3313                 domain: super::Domain::GRANT,
3314                 // Same grant id as before. The entry was only updated.
3315                 nspace: next_random + 1,
3316                 alias: None,
3317                 blob: None,
3318             }
3319         );
3320 
3321         {
3322             // Limiting scope of stmt, because it borrows db.
3323             let mut stmt = db
3324                 .conn
3325                 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
3326             let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3327                 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3328             })?;
3329 
3330             let r = rows.next().unwrap().unwrap();
3331             assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
3332             let r = rows.next().unwrap().unwrap();
3333             assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
3334             assert!(rows.next().is_none());
3335         }
3336 
3337         debug_dump_keyentry_table(&mut db)?;
3338         println!("app_key {:?}", app_key);
3339         println!("selinux_key {:?}", selinux_key);
3340 
3341         db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3342         db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3343 
3344         Ok(())
3345     }
3346 
3347     static TEST_KEY_BLOB: &[u8] = b"my test blob";
3348     static TEST_CERT_BLOB: &[u8] = b"my test cert";
3349     static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3350 
3351     #[test]
test_set_blob() -> Result<()>3352     fn test_set_blob() -> Result<()> {
3353         let key_id = KEY_ID_LOCK.get(3000);
3354         let mut db = new_test_db()?;
3355         let mut blob_metadata = BlobMetaData::new();
3356         blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3357         db.set_blob(
3358             &key_id,
3359             SubComponentType::KEY_BLOB,
3360             Some(TEST_KEY_BLOB),
3361             Some(&blob_metadata),
3362         )?;
3363         db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3364         db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
3365         drop(key_id);
3366 
3367         let mut stmt = db.conn.prepare(
3368             "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
3369                 ORDER BY subcomponent_type ASC;",
3370         )?;
3371         let mut rows = stmt
3372             .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
3373                 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
3374             })?;
3375         let (r, id) = rows.next().unwrap().unwrap();
3376         assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
3377         let (r, _) = rows.next().unwrap().unwrap();
3378         assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
3379         let (r, _) = rows.next().unwrap().unwrap();
3380         assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
3381 
3382         drop(rows);
3383         drop(stmt);
3384 
3385         assert_eq!(
3386             db.with_transaction(Immediate("TX_test"), |tx| {
3387                 BlobMetaData::load_from_db(id, tx).no_gc()
3388             })
3389             .expect("Should find blob metadata."),
3390             blob_metadata
3391         );
3392         Ok(())
3393     }
3394 
3395     static TEST_ALIAS: &str = "my super duper key";
3396 
3397     #[test]
test_insert_and_load_full_keyentry_domain_app() -> Result<()>3398     fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3399         let mut db = new_test_db()?;
3400         let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
3401             .context("test_insert_and_load_full_keyentry_domain_app")?
3402             .0;
3403         let (_key_guard, key_entry) = db
3404             .load_key_entry(
3405                 &KeyDescriptor {
3406                     domain: Domain::APP,
3407                     nspace: 0,
3408                     alias: Some(TEST_ALIAS.to_string()),
3409                     blob: None,
3410                 },
3411                 KeyType::Client,
3412                 KeyEntryLoadBits::BOTH,
3413                 1,
3414                 |_k, _av| Ok(()),
3415             )
3416             .unwrap();
3417         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3418 
3419         db.unbind_key(
3420             &KeyDescriptor {
3421                 domain: Domain::APP,
3422                 nspace: 0,
3423                 alias: Some(TEST_ALIAS.to_string()),
3424                 blob: None,
3425             },
3426             KeyType::Client,
3427             1,
3428             |_, _| Ok(()),
3429         )
3430         .unwrap();
3431 
3432         assert_eq!(
3433             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3434             db.load_key_entry(
3435                 &KeyDescriptor {
3436                     domain: Domain::APP,
3437                     nspace: 0,
3438                     alias: Some(TEST_ALIAS.to_string()),
3439                     blob: None,
3440                 },
3441                 KeyType::Client,
3442                 KeyEntryLoadBits::NONE,
3443                 1,
3444                 |_k, _av| Ok(()),
3445             )
3446             .unwrap_err()
3447             .root_cause()
3448             .downcast_ref::<KsError>()
3449         );
3450 
3451         Ok(())
3452     }
3453 
3454     #[test]
test_insert_and_load_certificate_entry_domain_app() -> Result<()>3455     fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3456         let mut db = new_test_db()?;
3457 
3458         db.store_new_certificate(
3459             &KeyDescriptor {
3460                 domain: Domain::APP,
3461                 nspace: 1,
3462                 alias: Some(TEST_ALIAS.to_string()),
3463                 blob: None,
3464             },
3465             KeyType::Client,
3466             TEST_CERT_BLOB,
3467             &KEYSTORE_UUID,
3468         )
3469         .expect("Trying to insert cert.");
3470 
3471         let (_key_guard, mut key_entry) = db
3472             .load_key_entry(
3473                 &KeyDescriptor {
3474                     domain: Domain::APP,
3475                     nspace: 1,
3476                     alias: Some(TEST_ALIAS.to_string()),
3477                     blob: None,
3478                 },
3479                 KeyType::Client,
3480                 KeyEntryLoadBits::PUBLIC,
3481                 1,
3482                 |_k, _av| Ok(()),
3483             )
3484             .expect("Trying to read certificate entry.");
3485 
3486         assert!(key_entry.pure_cert());
3487         assert!(key_entry.cert().is_none());
3488         assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3489 
3490         db.unbind_key(
3491             &KeyDescriptor {
3492                 domain: Domain::APP,
3493                 nspace: 1,
3494                 alias: Some(TEST_ALIAS.to_string()),
3495                 blob: None,
3496             },
3497             KeyType::Client,
3498             1,
3499             |_, _| Ok(()),
3500         )
3501         .unwrap();
3502 
3503         assert_eq!(
3504             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3505             db.load_key_entry(
3506                 &KeyDescriptor {
3507                     domain: Domain::APP,
3508                     nspace: 1,
3509                     alias: Some(TEST_ALIAS.to_string()),
3510                     blob: None,
3511                 },
3512                 KeyType::Client,
3513                 KeyEntryLoadBits::NONE,
3514                 1,
3515                 |_k, _av| Ok(()),
3516             )
3517             .unwrap_err()
3518             .root_cause()
3519             .downcast_ref::<KsError>()
3520         );
3521 
3522         Ok(())
3523     }
3524 
3525     #[test]
test_insert_and_load_full_keyentry_domain_selinux() -> Result<()>3526     fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3527         let mut db = new_test_db()?;
3528         let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
3529             .context("test_insert_and_load_full_keyentry_domain_selinux")?
3530             .0;
3531         let (_key_guard, key_entry) = db
3532             .load_key_entry(
3533                 &KeyDescriptor {
3534                     domain: Domain::SELINUX,
3535                     nspace: 1,
3536                     alias: Some(TEST_ALIAS.to_string()),
3537                     blob: None,
3538                 },
3539                 KeyType::Client,
3540                 KeyEntryLoadBits::BOTH,
3541                 1,
3542                 |_k, _av| Ok(()),
3543             )
3544             .unwrap();
3545         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3546 
3547         db.unbind_key(
3548             &KeyDescriptor {
3549                 domain: Domain::SELINUX,
3550                 nspace: 1,
3551                 alias: Some(TEST_ALIAS.to_string()),
3552                 blob: None,
3553             },
3554             KeyType::Client,
3555             1,
3556             |_, _| Ok(()),
3557         )
3558         .unwrap();
3559 
3560         assert_eq!(
3561             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3562             db.load_key_entry(
3563                 &KeyDescriptor {
3564                     domain: Domain::SELINUX,
3565                     nspace: 1,
3566                     alias: Some(TEST_ALIAS.to_string()),
3567                     blob: None,
3568                 },
3569                 KeyType::Client,
3570                 KeyEntryLoadBits::NONE,
3571                 1,
3572                 |_k, _av| Ok(()),
3573             )
3574             .unwrap_err()
3575             .root_cause()
3576             .downcast_ref::<KsError>()
3577         );
3578 
3579         Ok(())
3580     }
3581 
3582     #[test]
test_insert_and_load_full_keyentry_domain_key_id() -> Result<()>3583     fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3584         let mut db = new_test_db()?;
3585         let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
3586             .context("test_insert_and_load_full_keyentry_domain_key_id")?
3587             .0;
3588         let (_, key_entry) = db
3589             .load_key_entry(
3590                 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
3591                 KeyType::Client,
3592                 KeyEntryLoadBits::BOTH,
3593                 1,
3594                 |_k, _av| Ok(()),
3595             )
3596             .unwrap();
3597 
3598         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3599 
3600         db.unbind_key(
3601             &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
3602             KeyType::Client,
3603             1,
3604             |_, _| Ok(()),
3605         )
3606         .unwrap();
3607 
3608         assert_eq!(
3609             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3610             db.load_key_entry(
3611                 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
3612                 KeyType::Client,
3613                 KeyEntryLoadBits::NONE,
3614                 1,
3615                 |_k, _av| Ok(()),
3616             )
3617             .unwrap_err()
3618             .root_cause()
3619             .downcast_ref::<KsError>()
3620         );
3621 
3622         Ok(())
3623     }
3624 
3625     #[test]
test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()>3626     fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3627         let mut db = new_test_db()?;
3628         let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3629             .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3630             .0;
3631         // Update the usage count of the limited use key.
3632         db.check_and_update_key_usage_count(key_id)?;
3633 
3634         let (_key_guard, key_entry) = db.load_key_entry(
3635             &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
3636             KeyType::Client,
3637             KeyEntryLoadBits::BOTH,
3638             1,
3639             |_k, _av| Ok(()),
3640         )?;
3641 
3642         // The usage count is decremented now.
3643         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3644 
3645         Ok(())
3646     }
3647 
3648     #[test]
test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()>3649     fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3650         let mut db = new_test_db()?;
3651         let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3652             .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3653             .0;
3654         // Update the usage count of the limited use key.
3655         db.check_and_update_key_usage_count(key_id).expect(concat!(
3656             "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3657             "This should succeed."
3658         ));
3659 
3660         // Try to update the exhausted limited use key.
3661         let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3662             "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3663             "This should fail."
3664         ));
3665         assert_eq!(
3666             &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3667             e.root_cause().downcast_ref::<KsError>().unwrap()
3668         );
3669 
3670         Ok(())
3671     }
3672 
3673     #[test]
test_insert_and_load_full_keyentry_from_grant() -> Result<()>3674     fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3675         let mut db = new_test_db()?;
3676         let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
3677             .context("test_insert_and_load_full_keyentry_from_grant")?
3678             .0;
3679 
3680         let granted_key = db
3681             .grant(
3682                 &KeyDescriptor {
3683                     domain: Domain::APP,
3684                     nspace: 0,
3685                     alias: Some(TEST_ALIAS.to_string()),
3686                     blob: None,
3687                 },
3688                 1,
3689                 2,
3690                 key_perm_set![KeyPerm::Use],
3691                 |_k, _av| Ok(()),
3692             )
3693             .unwrap();
3694 
3695         debug_dump_grant_table(&mut db)?;
3696 
3697         let (_key_guard, key_entry) = db
3698             .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3699                 assert_eq!(Domain::GRANT, k.domain);
3700                 assert!(av.unwrap().includes(KeyPerm::Use));
3701                 Ok(())
3702             })
3703             .unwrap();
3704 
3705         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3706 
3707         db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
3708 
3709         assert_eq!(
3710             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3711             db.load_key_entry(
3712                 &granted_key,
3713                 KeyType::Client,
3714                 KeyEntryLoadBits::NONE,
3715                 2,
3716                 |_k, _av| Ok(()),
3717             )
3718             .unwrap_err()
3719             .root_cause()
3720             .downcast_ref::<KsError>()
3721         );
3722 
3723         Ok(())
3724     }
3725 
3726     // This test attempts to load a key by key id while the caller is not the owner
3727     // but a grant exists for the given key and the caller.
3728     #[test]
test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()>3729     fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3730         let mut db = new_test_db()?;
3731         const OWNER_UID: u32 = 1u32;
3732         const GRANTEE_UID: u32 = 2u32;
3733         const SOMEONE_ELSE_UID: u32 = 3u32;
3734         let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3735             .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3736             .0;
3737 
3738         db.grant(
3739             &KeyDescriptor {
3740                 domain: Domain::APP,
3741                 nspace: 0,
3742                 alias: Some(TEST_ALIAS.to_string()),
3743                 blob: None,
3744             },
3745             OWNER_UID,
3746             GRANTEE_UID,
3747             key_perm_set![KeyPerm::Use],
3748             |_k, _av| Ok(()),
3749         )
3750         .unwrap();
3751 
3752         debug_dump_grant_table(&mut db)?;
3753 
3754         let id_descriptor =
3755             KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3756 
3757         let (_, key_entry) = db
3758             .load_key_entry(
3759                 &id_descriptor,
3760                 KeyType::Client,
3761                 KeyEntryLoadBits::BOTH,
3762                 GRANTEE_UID,
3763                 |k, av| {
3764                     assert_eq!(Domain::APP, k.domain);
3765                     assert_eq!(OWNER_UID as i64, k.nspace);
3766                     assert!(av.unwrap().includes(KeyPerm::Use));
3767                     Ok(())
3768                 },
3769             )
3770             .unwrap();
3771 
3772         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3773 
3774         let (_, key_entry) = db
3775             .load_key_entry(
3776                 &id_descriptor,
3777                 KeyType::Client,
3778                 KeyEntryLoadBits::BOTH,
3779                 SOMEONE_ELSE_UID,
3780                 |k, av| {
3781                     assert_eq!(Domain::APP, k.domain);
3782                     assert_eq!(OWNER_UID as i64, k.nspace);
3783                     assert!(av.is_none());
3784                     Ok(())
3785                 },
3786             )
3787             .unwrap();
3788 
3789         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3790 
3791         db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
3792 
3793         assert_eq!(
3794             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3795             db.load_key_entry(
3796                 &id_descriptor,
3797                 KeyType::Client,
3798                 KeyEntryLoadBits::NONE,
3799                 GRANTEE_UID,
3800                 |_k, _av| Ok(()),
3801             )
3802             .unwrap_err()
3803             .root_cause()
3804             .downcast_ref::<KsError>()
3805         );
3806 
3807         Ok(())
3808     }
3809 
3810     // Creates a key migrates it to a different location and then tries to access it by the old
3811     // and new location.
3812     #[test]
test_migrate_key_app_to_app() -> Result<()>3813     fn test_migrate_key_app_to_app() -> Result<()> {
3814         let mut db = new_test_db()?;
3815         const SOURCE_UID: u32 = 1u32;
3816         const DESTINATION_UID: u32 = 2u32;
3817         static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3818         static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
3819         let key_id_guard =
3820             make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3821                 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3822 
3823         let source_descriptor: KeyDescriptor = KeyDescriptor {
3824             domain: Domain::APP,
3825             nspace: -1,
3826             alias: Some(SOURCE_ALIAS.to_string()),
3827             blob: None,
3828         };
3829 
3830         let destination_descriptor: KeyDescriptor = KeyDescriptor {
3831             domain: Domain::APP,
3832             nspace: -1,
3833             alias: Some(DESTINATION_ALIAS.to_string()),
3834             blob: None,
3835         };
3836 
3837         let key_id = key_id_guard.id();
3838 
3839         db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3840             Ok(())
3841         })
3842         .unwrap();
3843 
3844         let (_, key_entry) = db
3845             .load_key_entry(
3846                 &destination_descriptor,
3847                 KeyType::Client,
3848                 KeyEntryLoadBits::BOTH,
3849                 DESTINATION_UID,
3850                 |k, av| {
3851                     assert_eq!(Domain::APP, k.domain);
3852                     assert_eq!(DESTINATION_UID as i64, k.nspace);
3853                     assert!(av.is_none());
3854                     Ok(())
3855                 },
3856             )
3857             .unwrap();
3858 
3859         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3860 
3861         assert_eq!(
3862             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3863             db.load_key_entry(
3864                 &source_descriptor,
3865                 KeyType::Client,
3866                 KeyEntryLoadBits::NONE,
3867                 SOURCE_UID,
3868                 |_k, _av| Ok(()),
3869             )
3870             .unwrap_err()
3871             .root_cause()
3872             .downcast_ref::<KsError>()
3873         );
3874 
3875         Ok(())
3876     }
3877 
3878     // Creates a key migrates it to a different location and then tries to access it by the old
3879     // and new location.
3880     #[test]
test_migrate_key_app_to_selinux() -> Result<()>3881     fn test_migrate_key_app_to_selinux() -> Result<()> {
3882         let mut db = new_test_db()?;
3883         const SOURCE_UID: u32 = 1u32;
3884         const DESTINATION_UID: u32 = 2u32;
3885         const DESTINATION_NAMESPACE: i64 = 1000i64;
3886         static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3887         static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
3888         let key_id_guard =
3889             make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3890                 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3891 
3892         let source_descriptor: KeyDescriptor = KeyDescriptor {
3893             domain: Domain::APP,
3894             nspace: -1,
3895             alias: Some(SOURCE_ALIAS.to_string()),
3896             blob: None,
3897         };
3898 
3899         let destination_descriptor: KeyDescriptor = KeyDescriptor {
3900             domain: Domain::SELINUX,
3901             nspace: DESTINATION_NAMESPACE,
3902             alias: Some(DESTINATION_ALIAS.to_string()),
3903             blob: None,
3904         };
3905 
3906         let key_id = key_id_guard.id();
3907 
3908         db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3909             Ok(())
3910         })
3911         .unwrap();
3912 
3913         let (_, key_entry) = db
3914             .load_key_entry(
3915                 &destination_descriptor,
3916                 KeyType::Client,
3917                 KeyEntryLoadBits::BOTH,
3918                 DESTINATION_UID,
3919                 |k, av| {
3920                     assert_eq!(Domain::SELINUX, k.domain);
3921                     assert_eq!(DESTINATION_NAMESPACE, k.nspace);
3922                     assert!(av.is_none());
3923                     Ok(())
3924                 },
3925             )
3926             .unwrap();
3927 
3928         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3929 
3930         assert_eq!(
3931             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3932             db.load_key_entry(
3933                 &source_descriptor,
3934                 KeyType::Client,
3935                 KeyEntryLoadBits::NONE,
3936                 SOURCE_UID,
3937                 |_k, _av| Ok(()),
3938             )
3939             .unwrap_err()
3940             .root_cause()
3941             .downcast_ref::<KsError>()
3942         );
3943 
3944         Ok(())
3945     }
3946 
3947     // Creates two keys and tries to migrate the first to the location of the second which
3948     // is expected to fail.
3949     #[test]
test_migrate_key_destination_occupied() -> Result<()>3950     fn test_migrate_key_destination_occupied() -> Result<()> {
3951         let mut db = new_test_db()?;
3952         const SOURCE_UID: u32 = 1u32;
3953         const DESTINATION_UID: u32 = 2u32;
3954         static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3955         static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
3956         let key_id_guard =
3957             make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3958                 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3959         make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3960             .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3961 
3962         let destination_descriptor: KeyDescriptor = KeyDescriptor {
3963             domain: Domain::APP,
3964             nspace: -1,
3965             alias: Some(DESTINATION_ALIAS.to_string()),
3966             blob: None,
3967         };
3968 
3969         assert_eq!(
3970             Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3971             db.migrate_key_namespace(
3972                 key_id_guard,
3973                 &destination_descriptor,
3974                 DESTINATION_UID,
3975                 |_k| Ok(())
3976             )
3977             .unwrap_err()
3978             .root_cause()
3979             .downcast_ref::<KsError>()
3980         );
3981 
3982         Ok(())
3983     }
3984 
3985     #[test]
test_upgrade_0_to_1()3986     fn test_upgrade_0_to_1() {
3987         const ALIAS1: &str = "test_upgrade_0_to_1_1";
3988         const ALIAS2: &str = "test_upgrade_0_to_1_2";
3989         const ALIAS3: &str = "test_upgrade_0_to_1_3";
3990         const UID: u32 = 33;
3991         let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3992         let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3993         let key_id_untouched1 =
3994             make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3995         let key_id_untouched2 =
3996             make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
3997         let key_id_deleted =
3998             make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
3999 
4000         let (_, key_entry) = db
4001             .load_key_entry(
4002                 &KeyDescriptor {
4003                     domain: Domain::APP,
4004                     nspace: -1,
4005                     alias: Some(ALIAS1.to_string()),
4006                     blob: None,
4007                 },
4008                 KeyType::Client,
4009                 KeyEntryLoadBits::BOTH,
4010                 UID,
4011                 |k, av| {
4012                     assert_eq!(Domain::APP, k.domain);
4013                     assert_eq!(UID as i64, k.nspace);
4014                     assert!(av.is_none());
4015                     Ok(())
4016                 },
4017             )
4018             .unwrap();
4019         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4020         let (_, key_entry) = db
4021             .load_key_entry(
4022                 &KeyDescriptor {
4023                     domain: Domain::APP,
4024                     nspace: -1,
4025                     alias: Some(ALIAS2.to_string()),
4026                     blob: None,
4027                 },
4028                 KeyType::Client,
4029                 KeyEntryLoadBits::BOTH,
4030                 UID,
4031                 |k, av| {
4032                     assert_eq!(Domain::APP, k.domain);
4033                     assert_eq!(UID as i64, k.nspace);
4034                     assert!(av.is_none());
4035                     Ok(())
4036                 },
4037             )
4038             .unwrap();
4039         assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4040         let (_, key_entry) = db
4041             .load_key_entry(
4042                 &KeyDescriptor {
4043                     domain: Domain::APP,
4044                     nspace: -1,
4045                     alias: Some(ALIAS3.to_string()),
4046                     blob: None,
4047                 },
4048                 KeyType::Client,
4049                 KeyEntryLoadBits::BOTH,
4050                 UID,
4051                 |k, av| {
4052                     assert_eq!(Domain::APP, k.domain);
4053                     assert_eq!(UID as i64, k.nspace);
4054                     assert!(av.is_none());
4055                     Ok(())
4056                 },
4057             )
4058             .unwrap();
4059         assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4060 
4061         db.with_transaction(Immediate("TX_test"), |tx| KeystoreDB::from_0_to_1(tx).no_gc())
4062             .unwrap();
4063 
4064         let (_, key_entry) = db
4065             .load_key_entry(
4066                 &KeyDescriptor {
4067                     domain: Domain::APP,
4068                     nspace: -1,
4069                     alias: Some(ALIAS1.to_string()),
4070                     blob: None,
4071                 },
4072                 KeyType::Client,
4073                 KeyEntryLoadBits::BOTH,
4074                 UID,
4075                 |k, av| {
4076                     assert_eq!(Domain::APP, k.domain);
4077                     assert_eq!(UID as i64, k.nspace);
4078                     assert!(av.is_none());
4079                     Ok(())
4080                 },
4081             )
4082             .unwrap();
4083         assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4084         let (_, key_entry) = db
4085             .load_key_entry(
4086                 &KeyDescriptor {
4087                     domain: Domain::APP,
4088                     nspace: -1,
4089                     alias: Some(ALIAS2.to_string()),
4090                     blob: None,
4091                 },
4092                 KeyType::Client,
4093                 KeyEntryLoadBits::BOTH,
4094                 UID,
4095                 |k, av| {
4096                     assert_eq!(Domain::APP, k.domain);
4097                     assert_eq!(UID as i64, k.nspace);
4098                     assert!(av.is_none());
4099                     Ok(())
4100                 },
4101             )
4102             .unwrap();
4103         assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4104         assert_eq!(
4105             Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4106             db.load_key_entry(
4107                 &KeyDescriptor {
4108                     domain: Domain::APP,
4109                     nspace: -1,
4110                     alias: Some(ALIAS3.to_string()),
4111                     blob: None,
4112                 },
4113                 KeyType::Client,
4114                 KeyEntryLoadBits::BOTH,
4115                 UID,
4116                 |k, av| {
4117                     assert_eq!(Domain::APP, k.domain);
4118                     assert_eq!(UID as i64, k.nspace);
4119                     assert!(av.is_none());
4120                     Ok(())
4121                 },
4122             )
4123             .unwrap_err()
4124             .root_cause()
4125             .downcast_ref::<KsError>()
4126         );
4127     }
4128 
4129     static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4130 
4131     #[test]
test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()>4132     fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4133         let handle = {
4134             let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4135             let temp_dir_clone = temp_dir.clone();
4136             let mut db = KeystoreDB::new(temp_dir.path(), None)?;
4137             let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
4138                 .context("test_insert_and_load_full_keyentry_domain_app")?
4139                 .0;
4140             let (_key_guard, key_entry) = db
4141                 .load_key_entry(
4142                     &KeyDescriptor {
4143                         domain: Domain::APP,
4144                         nspace: 0,
4145                         alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4146                         blob: None,
4147                     },
4148                     KeyType::Client,
4149                     KeyEntryLoadBits::BOTH,
4150                     33,
4151                     |_k, _av| Ok(()),
4152                 )
4153                 .unwrap();
4154             assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4155             let state = Arc::new(AtomicU8::new(1));
4156             let state2 = state.clone();
4157 
4158             // Spawning a second thread that attempts to acquire the key id lock
4159             // for the same key as the primary thread. The primary thread then
4160             // waits, thereby forcing the secondary thread into the second stage
4161             // of acquiring the lock (see KEY ID LOCK 2/2 above).
4162             // The test succeeds if the secondary thread observes the transition
4163             // of `state` from 1 to 2, despite having a whole second to overtake
4164             // the primary thread.
4165             let handle = thread::spawn(move || {
4166                 let temp_dir = temp_dir_clone;
4167                 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4168                 assert!(db
4169                     .load_key_entry(
4170                         &KeyDescriptor {
4171                             domain: Domain::APP,
4172                             nspace: 0,
4173                             alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4174                             blob: None,
4175                         },
4176                         KeyType::Client,
4177                         KeyEntryLoadBits::BOTH,
4178                         33,
4179                         |_k, _av| Ok(()),
4180                     )
4181                     .is_ok());
4182                 // We should only see a 2 here because we can only return
4183                 // from load_key_entry when the `_key_guard` expires,
4184                 // which happens at the end of the scope.
4185                 assert_eq!(2, state2.load(Ordering::Relaxed));
4186             });
4187 
4188             thread::sleep(std::time::Duration::from_millis(1000));
4189 
4190             assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4191 
4192             // Return the handle from this scope so we can join with the
4193             // secondary thread after the key id lock has expired.
4194             handle
4195             // This is where the `_key_guard` goes out of scope,
4196             // which is the reason for concurrent load_key_entry on the same key
4197             // to unblock.
4198         };
4199         // Join with the secondary thread and unwrap, to propagate failing asserts to the
4200         // main test thread. We will not see failing asserts in secondary threads otherwise.
4201         handle.join().unwrap();
4202         Ok(())
4203     }
4204 
4205     #[test]
test_database_busy_error_code()4206     fn test_database_busy_error_code() {
4207         let temp_dir =
4208             TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4209 
4210         let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4211         let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
4212 
4213         let _tx1 = db1
4214             .conn
4215             .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
4216             .expect("Failed to create first transaction.");
4217 
4218         let error = db2
4219             .conn
4220             .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
4221             .context("Transaction begin failed.")
4222             .expect_err("This should fail.");
4223         let root_cause = error.root_cause();
4224         if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4225             root_cause.downcast_ref::<rusqlite::ffi::Error>()
4226         {
4227             return;
4228         }
4229         panic!(
4230             "Unexpected error {:?} \n{:?} \n{:?}",
4231             error,
4232             root_cause,
4233             root_cause.downcast_ref::<rusqlite::ffi::Error>()
4234         )
4235     }
4236 
4237     #[cfg(disabled)]
4238     #[test]
test_large_number_of_concurrent_db_manipulations() -> Result<()>4239     fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4240         let temp_dir = Arc::new(
4241             TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4242                 .expect("Failed to create temp dir."),
4243         );
4244 
4245         let test_begin = Instant::now();
4246 
4247         const KEY_COUNT: u32 = 500u32;
4248         let mut db =
4249             new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
4250         const OPEN_DB_COUNT: u32 = 50u32;
4251 
4252         let mut actual_key_count = KEY_COUNT;
4253         // First insert KEY_COUNT keys.
4254         for count in 0..KEY_COUNT {
4255             if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4256                 actual_key_count = count;
4257                 break;
4258             }
4259             let alias = format!("test_alias_{}", count);
4260             make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4261                 .expect("Failed to make key entry.");
4262         }
4263 
4264         // Insert more keys from a different thread and into a different namespace.
4265         let temp_dir1 = temp_dir.clone();
4266         let handle1 = thread::spawn(move || {
4267             let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4268                 .expect("Failed to open database.");
4269 
4270             for count in 0..actual_key_count {
4271                 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4272                     return;
4273                 }
4274                 let alias = format!("test_alias_{}", count);
4275                 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4276                     .expect("Failed to make key entry.");
4277             }
4278 
4279             // then unbind them again.
4280             for count in 0..actual_key_count {
4281                 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4282                     return;
4283                 }
4284                 let key = KeyDescriptor {
4285                     domain: Domain::APP,
4286                     nspace: -1,
4287                     alias: Some(format!("test_alias_{}", count)),
4288                     blob: None,
4289                 };
4290                 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4291             }
4292         });
4293 
4294         // And start unbinding the first set of keys.
4295         let temp_dir2 = temp_dir.clone();
4296         let handle2 = thread::spawn(move || {
4297             let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4298                 .expect("Failed to open database.");
4299 
4300             for count in 0..actual_key_count {
4301                 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4302                     return;
4303                 }
4304                 let key = KeyDescriptor {
4305                     domain: Domain::APP,
4306                     nspace: -1,
4307                     alias: Some(format!("test_alias_{}", count)),
4308                     blob: None,
4309                 };
4310                 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4311             }
4312         });
4313 
4314         // While a lot of inserting and deleting is going on we have to open database connections
4315         // successfully and use them.
4316         // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4317         // out of scope.
4318         #[allow(clippy::redundant_clone)]
4319         let temp_dir4 = temp_dir.clone();
4320         let handle4 = thread::spawn(move || {
4321             for count in 0..OPEN_DB_COUNT {
4322                 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4323                     return;
4324                 }
4325                 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4326                     .expect("Failed to open database.");
4327 
4328                 let alias = format!("test_alias_{}", count);
4329                 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4330                     .expect("Failed to make key entry.");
4331                 let key = KeyDescriptor {
4332                     domain: Domain::APP,
4333                     nspace: -1,
4334                     alias: Some(alias),
4335                     blob: None,
4336                 };
4337                 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4338             }
4339         });
4340 
4341         handle1.join().expect("Thread 1 panicked.");
4342         handle2.join().expect("Thread 2 panicked.");
4343         handle4.join().expect("Thread 4 panicked.");
4344 
4345         Ok(())
4346     }
4347 
4348     #[test]
list() -> Result<()>4349     fn list() -> Result<()> {
4350         let temp_dir = TempDir::new("list_test")?;
4351         let mut db = KeystoreDB::new(temp_dir.path(), None)?;
4352         static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4353             (Domain::APP, 1, "test1"),
4354             (Domain::APP, 1, "test2"),
4355             (Domain::APP, 1, "test3"),
4356             (Domain::APP, 1, "test4"),
4357             (Domain::APP, 1, "test5"),
4358             (Domain::APP, 1, "test6"),
4359             (Domain::APP, 1, "test7"),
4360             (Domain::APP, 2, "test1"),
4361             (Domain::APP, 2, "test2"),
4362             (Domain::APP, 2, "test3"),
4363             (Domain::APP, 2, "test4"),
4364             (Domain::APP, 2, "test5"),
4365             (Domain::APP, 2, "test6"),
4366             (Domain::APP, 2, "test8"),
4367             (Domain::SELINUX, 100, "test1"),
4368             (Domain::SELINUX, 100, "test2"),
4369             (Domain::SELINUX, 100, "test3"),
4370             (Domain::SELINUX, 100, "test4"),
4371             (Domain::SELINUX, 100, "test5"),
4372             (Domain::SELINUX, 100, "test6"),
4373             (Domain::SELINUX, 100, "test9"),
4374         ];
4375 
4376         let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4377             .iter()
4378             .map(|(domain, ns, alias)| {
4379                 let entry =
4380                     make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
4381                         panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4382                     });
4383                 (entry.id(), *ns)
4384             })
4385             .collect();
4386 
4387         for (domain, namespace) in
4388             &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4389         {
4390             let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4391                 .iter()
4392                 .filter_map(|(domain, ns, alias)| match ns {
4393                     ns if *ns == *namespace => Some(KeyDescriptor {
4394                         domain: *domain,
4395                         nspace: *ns,
4396                         alias: Some(alias.to_string()),
4397                         blob: None,
4398                     }),
4399                     _ => None,
4400                 })
4401                 .collect();
4402             list_o_descriptors.sort();
4403             let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
4404             list_result.sort();
4405             assert_eq!(list_o_descriptors, list_result);
4406 
4407             let mut list_o_ids: Vec<i64> = list_o_descriptors
4408                 .into_iter()
4409                 .map(|d| {
4410                     let (_, entry) = db
4411                         .load_key_entry(
4412                             &d,
4413                             KeyType::Client,
4414                             KeyEntryLoadBits::NONE,
4415                             *namespace as u32,
4416                             |_, _| Ok(()),
4417                         )
4418                         .unwrap();
4419                     entry.id()
4420                 })
4421                 .collect();
4422             list_o_ids.sort_unstable();
4423             let mut loaded_entries: Vec<i64> = list_o_keys
4424                 .iter()
4425                 .filter_map(|(id, ns)| match ns {
4426                     ns if *ns == *namespace => Some(*id),
4427                     _ => None,
4428                 })
4429                 .collect();
4430             loaded_entries.sort_unstable();
4431             assert_eq!(list_o_ids, loaded_entries);
4432         }
4433         assert_eq!(
4434             Vec::<KeyDescriptor>::new(),
4435             db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4436         );
4437 
4438         Ok(())
4439     }
4440 
4441     // Helpers
4442 
4443     // Checks that the given result is an error containing the given string.
check_result_is_error_containing_string<T>(result: Result<T>, target: &str)4444     fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4445         let error_str = format!(
4446             "{:#?}",
4447             result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4448         );
4449         assert!(
4450             error_str.contains(target),
4451             "The string \"{}\" should contain \"{}\"",
4452             error_str,
4453             target
4454         );
4455     }
4456 
4457     #[derive(Debug, PartialEq)]
4458     struct KeyEntryRow {
4459         id: i64,
4460         key_type: KeyType,
4461         domain: Option<Domain>,
4462         namespace: Option<i64>,
4463         alias: Option<String>,
4464         state: KeyLifeCycle,
4465         km_uuid: Option<Uuid>,
4466     }
4467 
get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>>4468     fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4469         db.conn
4470             .prepare("SELECT * FROM persistent.keyentry;")?
4471             .query_map([], |row| {
4472                 Ok(KeyEntryRow {
4473                     id: row.get(0)?,
4474                     key_type: row.get(1)?,
4475                     domain: row.get::<_, Option<_>>(2)?.map(Domain),
4476                     namespace: row.get(3)?,
4477                     alias: row.get(4)?,
4478                     state: row.get(5)?,
4479                     km_uuid: row.get(6)?,
4480                 })
4481             })?
4482             .map(|r| r.context("Could not read keyentry row."))
4483             .collect::<Result<Vec<_>>>()
4484     }
4485 
make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter>4486     fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4487         make_test_params_with_sids(max_usage_count, &[42])
4488     }
4489 
4490     // Note: The parameters and SecurityLevel associations are nonsensical. This
4491     // collection is only used to check if the parameters are preserved as expected by the
4492     // database.
make_test_params_with_sids( max_usage_count: Option<i32>, user_secure_ids: &[i64], ) -> Vec<KeyParameter>4493     fn make_test_params_with_sids(
4494         max_usage_count: Option<i32>,
4495         user_secure_ids: &[i64],
4496     ) -> Vec<KeyParameter> {
4497         let mut params = vec![
4498             KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4499             KeyParameter::new(
4500                 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4501                 SecurityLevel::TRUSTED_ENVIRONMENT,
4502             ),
4503             KeyParameter::new(
4504                 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4505                 SecurityLevel::TRUSTED_ENVIRONMENT,
4506             ),
4507             KeyParameter::new(
4508                 KeyParameterValue::Algorithm(Algorithm::RSA),
4509                 SecurityLevel::TRUSTED_ENVIRONMENT,
4510             ),
4511             KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4512             KeyParameter::new(
4513                 KeyParameterValue::BlockMode(BlockMode::ECB),
4514                 SecurityLevel::TRUSTED_ENVIRONMENT,
4515             ),
4516             KeyParameter::new(
4517                 KeyParameterValue::BlockMode(BlockMode::GCM),
4518                 SecurityLevel::TRUSTED_ENVIRONMENT,
4519             ),
4520             KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4521             KeyParameter::new(
4522                 KeyParameterValue::Digest(Digest::MD5),
4523                 SecurityLevel::TRUSTED_ENVIRONMENT,
4524             ),
4525             KeyParameter::new(
4526                 KeyParameterValue::Digest(Digest::SHA_2_224),
4527                 SecurityLevel::TRUSTED_ENVIRONMENT,
4528             ),
4529             KeyParameter::new(
4530                 KeyParameterValue::Digest(Digest::SHA_2_256),
4531                 SecurityLevel::STRONGBOX,
4532             ),
4533             KeyParameter::new(
4534                 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4535                 SecurityLevel::TRUSTED_ENVIRONMENT,
4536             ),
4537             KeyParameter::new(
4538                 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4539                 SecurityLevel::TRUSTED_ENVIRONMENT,
4540             ),
4541             KeyParameter::new(
4542                 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4543                 SecurityLevel::STRONGBOX,
4544             ),
4545             KeyParameter::new(
4546                 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4547                 SecurityLevel::TRUSTED_ENVIRONMENT,
4548             ),
4549             KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4550             KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4551             KeyParameter::new(
4552                 KeyParameterValue::EcCurve(EcCurve::P_224),
4553                 SecurityLevel::TRUSTED_ENVIRONMENT,
4554             ),
4555             KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4556             KeyParameter::new(
4557                 KeyParameterValue::EcCurve(EcCurve::P_384),
4558                 SecurityLevel::TRUSTED_ENVIRONMENT,
4559             ),
4560             KeyParameter::new(
4561                 KeyParameterValue::EcCurve(EcCurve::P_521),
4562                 SecurityLevel::TRUSTED_ENVIRONMENT,
4563             ),
4564             KeyParameter::new(
4565                 KeyParameterValue::RSAPublicExponent(3),
4566                 SecurityLevel::TRUSTED_ENVIRONMENT,
4567             ),
4568             KeyParameter::new(
4569                 KeyParameterValue::IncludeUniqueID,
4570                 SecurityLevel::TRUSTED_ENVIRONMENT,
4571             ),
4572             KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4573             KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4574             KeyParameter::new(
4575                 KeyParameterValue::ActiveDateTime(1234567890),
4576                 SecurityLevel::STRONGBOX,
4577             ),
4578             KeyParameter::new(
4579                 KeyParameterValue::OriginationExpireDateTime(1234567890),
4580                 SecurityLevel::TRUSTED_ENVIRONMENT,
4581             ),
4582             KeyParameter::new(
4583                 KeyParameterValue::UsageExpireDateTime(1234567890),
4584                 SecurityLevel::TRUSTED_ENVIRONMENT,
4585             ),
4586             KeyParameter::new(
4587                 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4588                 SecurityLevel::TRUSTED_ENVIRONMENT,
4589             ),
4590             KeyParameter::new(
4591                 KeyParameterValue::MaxUsesPerBoot(1234567890),
4592                 SecurityLevel::TRUSTED_ENVIRONMENT,
4593             ),
4594             KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4595             KeyParameter::new(
4596                 KeyParameterValue::NoAuthRequired,
4597                 SecurityLevel::TRUSTED_ENVIRONMENT,
4598             ),
4599             KeyParameter::new(
4600                 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4601                 SecurityLevel::TRUSTED_ENVIRONMENT,
4602             ),
4603             KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4604             KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4605             KeyParameter::new(
4606                 KeyParameterValue::TrustedUserPresenceRequired,
4607                 SecurityLevel::TRUSTED_ENVIRONMENT,
4608             ),
4609             KeyParameter::new(
4610                 KeyParameterValue::TrustedConfirmationRequired,
4611                 SecurityLevel::TRUSTED_ENVIRONMENT,
4612             ),
4613             KeyParameter::new(
4614                 KeyParameterValue::UnlockedDeviceRequired,
4615                 SecurityLevel::TRUSTED_ENVIRONMENT,
4616             ),
4617             KeyParameter::new(
4618                 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4619                 SecurityLevel::SOFTWARE,
4620             ),
4621             KeyParameter::new(
4622                 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4623                 SecurityLevel::SOFTWARE,
4624             ),
4625             KeyParameter::new(
4626                 KeyParameterValue::CreationDateTime(12345677890),
4627                 SecurityLevel::SOFTWARE,
4628             ),
4629             KeyParameter::new(
4630                 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4631                 SecurityLevel::TRUSTED_ENVIRONMENT,
4632             ),
4633             KeyParameter::new(
4634                 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4635                 SecurityLevel::TRUSTED_ENVIRONMENT,
4636             ),
4637             KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4638             KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4639             KeyParameter::new(
4640                 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4641                 SecurityLevel::SOFTWARE,
4642             ),
4643             KeyParameter::new(
4644                 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4645                 SecurityLevel::TRUSTED_ENVIRONMENT,
4646             ),
4647             KeyParameter::new(
4648                 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4649                 SecurityLevel::TRUSTED_ENVIRONMENT,
4650             ),
4651             KeyParameter::new(
4652                 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4653                 SecurityLevel::TRUSTED_ENVIRONMENT,
4654             ),
4655             KeyParameter::new(
4656                 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4657                 SecurityLevel::TRUSTED_ENVIRONMENT,
4658             ),
4659             KeyParameter::new(
4660                 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4661                 SecurityLevel::TRUSTED_ENVIRONMENT,
4662             ),
4663             KeyParameter::new(
4664                 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4665                 SecurityLevel::TRUSTED_ENVIRONMENT,
4666             ),
4667             KeyParameter::new(
4668                 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4669                 SecurityLevel::TRUSTED_ENVIRONMENT,
4670             ),
4671             KeyParameter::new(
4672                 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4673                 SecurityLevel::TRUSTED_ENVIRONMENT,
4674             ),
4675             KeyParameter::new(
4676                 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4677                 SecurityLevel::TRUSTED_ENVIRONMENT,
4678             ),
4679             KeyParameter::new(
4680                 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4681                 SecurityLevel::TRUSTED_ENVIRONMENT,
4682             ),
4683             KeyParameter::new(
4684                 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4685                 SecurityLevel::TRUSTED_ENVIRONMENT,
4686             ),
4687             KeyParameter::new(
4688                 KeyParameterValue::VendorPatchLevel(3),
4689                 SecurityLevel::TRUSTED_ENVIRONMENT,
4690             ),
4691             KeyParameter::new(
4692                 KeyParameterValue::BootPatchLevel(4),
4693                 SecurityLevel::TRUSTED_ENVIRONMENT,
4694             ),
4695             KeyParameter::new(
4696                 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4697                 SecurityLevel::TRUSTED_ENVIRONMENT,
4698             ),
4699             KeyParameter::new(
4700                 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4701                 SecurityLevel::TRUSTED_ENVIRONMENT,
4702             ),
4703             KeyParameter::new(
4704                 KeyParameterValue::MacLength(256),
4705                 SecurityLevel::TRUSTED_ENVIRONMENT,
4706             ),
4707             KeyParameter::new(
4708                 KeyParameterValue::ResetSinceIdRotation,
4709                 SecurityLevel::TRUSTED_ENVIRONMENT,
4710             ),
4711             KeyParameter::new(
4712                 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4713                 SecurityLevel::TRUSTED_ENVIRONMENT,
4714             ),
4715         ];
4716         if let Some(value) = max_usage_count {
4717             params.push(KeyParameter::new(
4718                 KeyParameterValue::UsageCountLimit(value),
4719                 SecurityLevel::SOFTWARE,
4720             ));
4721         }
4722 
4723         for sid in user_secure_ids.iter() {
4724             params.push(KeyParameter::new(
4725                 KeyParameterValue::UserSecureID(*sid),
4726                 SecurityLevel::STRONGBOX,
4727             ));
4728         }
4729         params
4730     }
4731 
make_test_key_entry( db: &mut KeystoreDB, domain: Domain, namespace: i64, alias: &str, max_usage_count: Option<i32>, ) -> Result<KeyIdGuard>4732     pub fn make_test_key_entry(
4733         db: &mut KeystoreDB,
4734         domain: Domain,
4735         namespace: i64,
4736         alias: &str,
4737         max_usage_count: Option<i32>,
4738     ) -> Result<KeyIdGuard> {
4739         make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4740     }
4741 
make_test_key_entry_with_sids( db: &mut KeystoreDB, domain: Domain, namespace: i64, alias: &str, max_usage_count: Option<i32>, sids: &[i64], ) -> Result<KeyIdGuard>4742     pub fn make_test_key_entry_with_sids(
4743         db: &mut KeystoreDB,
4744         domain: Domain,
4745         namespace: i64,
4746         alias: &str,
4747         max_usage_count: Option<i32>,
4748         sids: &[i64],
4749     ) -> Result<KeyIdGuard> {
4750         let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4751         let mut blob_metadata = BlobMetaData::new();
4752         blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4753         blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4754         blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4755         blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4756         blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4757 
4758         db.set_blob(
4759             &key_id,
4760             SubComponentType::KEY_BLOB,
4761             Some(TEST_KEY_BLOB),
4762             Some(&blob_metadata),
4763         )?;
4764         db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4765         db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4766 
4767         let params = make_test_params_with_sids(max_usage_count, sids);
4768         db.insert_keyparameter(&key_id, &params)?;
4769 
4770         let mut metadata = KeyMetaData::new();
4771         metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4772         db.insert_key_metadata(&key_id, &metadata)?;
4773         rebind_alias(db, &key_id, alias, domain, namespace)?;
4774         Ok(key_id)
4775     }
4776 
make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry4777     fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4778         let params = make_test_params(max_usage_count);
4779 
4780         let mut blob_metadata = BlobMetaData::new();
4781         blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4782         blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4783         blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4784         blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4785         blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4786 
4787         let mut metadata = KeyMetaData::new();
4788         metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4789 
4790         KeyEntry {
4791             id: key_id,
4792             key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4793             cert: Some(TEST_CERT_BLOB.to_vec()),
4794             cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4795             km_uuid: KEYSTORE_UUID,
4796             parameters: params,
4797             metadata,
4798             pure_cert: false,
4799         }
4800     }
4801 
make_bootlevel_key_entry( db: &mut KeystoreDB, domain: Domain, namespace: i64, alias: &str, logical_only: bool, ) -> Result<KeyIdGuard>4802     pub fn make_bootlevel_key_entry(
4803         db: &mut KeystoreDB,
4804         domain: Domain,
4805         namespace: i64,
4806         alias: &str,
4807         logical_only: bool,
4808     ) -> Result<KeyIdGuard> {
4809         let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4810         let mut blob_metadata = BlobMetaData::new();
4811         if !logical_only {
4812             blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4813         }
4814         blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4815 
4816         db.set_blob(
4817             &key_id,
4818             SubComponentType::KEY_BLOB,
4819             Some(TEST_KEY_BLOB),
4820             Some(&blob_metadata),
4821         )?;
4822         db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4823         db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4824 
4825         let mut params = make_test_params(None);
4826         params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4827 
4828         db.insert_keyparameter(&key_id, &params)?;
4829 
4830         let mut metadata = KeyMetaData::new();
4831         metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4832         db.insert_key_metadata(&key_id, &metadata)?;
4833         rebind_alias(db, &key_id, alias, domain, namespace)?;
4834         Ok(key_id)
4835     }
4836 
4837     // Creates an app key that is marked as being superencrypted by the given
4838     // super key ID and that has the given authentication and unlocked device
4839     // parameters. This does not actually superencrypt the key blob.
make_superencrypted_key_entry( db: &mut KeystoreDB, namespace: i64, alias: &str, requires_authentication: bool, requires_unlocked_device: bool, super_key_id: i64, ) -> Result<KeyIdGuard>4840     fn make_superencrypted_key_entry(
4841         db: &mut KeystoreDB,
4842         namespace: i64,
4843         alias: &str,
4844         requires_authentication: bool,
4845         requires_unlocked_device: bool,
4846         super_key_id: i64,
4847     ) -> Result<KeyIdGuard> {
4848         let domain = Domain::APP;
4849         let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4850 
4851         let mut blob_metadata = BlobMetaData::new();
4852         blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4853         blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4854         db.set_blob(
4855             &key_id,
4856             SubComponentType::KEY_BLOB,
4857             Some(TEST_KEY_BLOB),
4858             Some(&blob_metadata),
4859         )?;
4860 
4861         let mut params = vec![];
4862         if requires_unlocked_device {
4863             params.push(KeyParameter::new(
4864                 KeyParameterValue::UnlockedDeviceRequired,
4865                 SecurityLevel::TRUSTED_ENVIRONMENT,
4866             ));
4867         }
4868         if requires_authentication {
4869             params.push(KeyParameter::new(
4870                 KeyParameterValue::UserSecureID(42),
4871                 SecurityLevel::TRUSTED_ENVIRONMENT,
4872             ));
4873         }
4874         db.insert_keyparameter(&key_id, &params)?;
4875 
4876         let mut metadata = KeyMetaData::new();
4877         metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4878         db.insert_key_metadata(&key_id, &metadata)?;
4879 
4880         rebind_alias(db, &key_id, alias, domain, namespace)?;
4881         Ok(key_id)
4882     }
4883 
make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry4884     fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4885         let mut params = make_test_params(None);
4886         params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4887 
4888         let mut blob_metadata = BlobMetaData::new();
4889         if !logical_only {
4890             blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4891         }
4892         blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4893 
4894         let mut metadata = KeyMetaData::new();
4895         metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4896 
4897         KeyEntry {
4898             id: key_id,
4899             key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4900             cert: Some(TEST_CERT_BLOB.to_vec()),
4901             cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4902             km_uuid: KEYSTORE_UUID,
4903             parameters: params,
4904             metadata,
4905             pure_cert: false,
4906         }
4907     }
4908 
debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()>4909     fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
4910         let mut stmt = db.conn.prepare(
4911             "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
4912         )?;
4913         let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
4914             [],
4915             |row| {
4916                 Ok((
4917                     row.get(0)?,
4918                     row.get(1)?,
4919                     row.get(2)?,
4920                     row.get(3)?,
4921                     row.get(4)?,
4922                     row.get(5)?,
4923                     row.get(6)?,
4924                 ))
4925             },
4926         )?;
4927 
4928         println!("Key entry table rows:");
4929         for r in rows {
4930             let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
4931             println!(
4932                 "    id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4933                 id, key_type, domain, namespace, alias, state, km_uuid
4934             );
4935         }
4936         Ok(())
4937     }
4938 
debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()>4939     fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
4940         let mut stmt = db
4941             .conn
4942             .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
4943         let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
4944             Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4945         })?;
4946 
4947         println!("Grant table rows:");
4948         for r in rows {
4949             let (id, gt, ki, av) = r.unwrap();
4950             println!("    id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4951         }
4952         Ok(())
4953     }
4954 
4955     // Use a custom random number generator that repeats each number once.
4956     // This allows us to test repeated elements.
4957 
4958     thread_local! {
4959         static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
4960     }
4961 
reset_random()4962     fn reset_random() {
4963         RANDOM_COUNTER.with(|counter| {
4964             *counter.borrow_mut() = 0;
4965         })
4966     }
4967 
random() -> i644968     pub fn random() -> i64 {
4969         RANDOM_COUNTER.with(|counter| {
4970             let result = *counter.borrow() / 2;
4971             *counter.borrow_mut() += 1;
4972             result
4973         })
4974     }
4975 
4976     #[test]
test_unbind_keys_for_user() -> Result<()>4977     fn test_unbind_keys_for_user() -> Result<()> {
4978         let mut db = new_test_db()?;
4979         db.unbind_keys_for_user(1, false)?;
4980 
4981         make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4982         make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4983         db.unbind_keys_for_user(2, false)?;
4984 
4985         assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4986         assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
4987 
4988         db.unbind_keys_for_user(1, true)?;
4989         assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4990 
4991         Ok(())
4992     }
4993 
4994     #[test]
test_unbind_keys_for_user_removes_superkeys() -> Result<()>4995     fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4996         let mut db = new_test_db()?;
4997         let super_key = keystore2_crypto::generate_aes256_key()?;
4998         let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4999         let (encrypted_super_key, metadata) =
5000             SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5001 
5002         let key_name_enc = SuperKeyType {
5003             alias: "test_super_key_1",
5004             algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5005             name: "test_super_key_1",
5006         };
5007 
5008         let key_name_nonenc = SuperKeyType {
5009             alias: "test_super_key_2",
5010             algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5011             name: "test_super_key_2",
5012         };
5013 
5014         // Install two super keys.
5015         db.store_super_key(
5016             1,
5017             &key_name_nonenc,
5018             &super_key,
5019             &BlobMetaData::new(),
5020             &KeyMetaData::new(),
5021         )?;
5022         db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5023 
5024         // Check that both can be found in the database.
5025         assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5026         assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5027 
5028         // Install the same keys for a different user.
5029         db.store_super_key(
5030             2,
5031             &key_name_nonenc,
5032             &super_key,
5033             &BlobMetaData::new(),
5034             &KeyMetaData::new(),
5035         )?;
5036         db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5037 
5038         // Check that the second pair of keys can be found in the database.
5039         assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5040         assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5041 
5042         // Delete only encrypted keys.
5043         db.unbind_keys_for_user(1, true)?;
5044 
5045         // The encrypted superkey should be gone now.
5046         assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5047         assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5048 
5049         // Reinsert the encrypted key.
5050         db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5051 
5052         // Check that both can be found in the database, again..
5053         assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5054         assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5055 
5056         // Delete all even unencrypted keys.
5057         db.unbind_keys_for_user(1, false)?;
5058 
5059         // Both should be gone now.
5060         assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5061         assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5062 
5063         // Check that the second pair of keys was untouched.
5064         assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5065         assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5066 
5067         Ok(())
5068     }
5069 
app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool>5070     fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5071         db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5072     }
5073 
5074     // Tests the unbind_auth_bound_keys_for_user() function.
5075     #[test]
test_unbind_auth_bound_keys_for_user() -> Result<()>5076     fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5077         let mut db = new_test_db()?;
5078         let user_id = 1;
5079         let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5080         let other_user_id = 2;
5081         let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5082         let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5083 
5084         // Create a superencryption key.
5085         let super_key = keystore2_crypto::generate_aes256_key()?;
5086         let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5087         let (encrypted_super_key, blob_metadata) =
5088             SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5089         db.store_super_key(
5090             user_id,
5091             super_key_type,
5092             &encrypted_super_key,
5093             &blob_metadata,
5094             &KeyMetaData::new(),
5095         )?;
5096         let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5097 
5098         // Store 4 superencrypted app keys, one for each possible combination of
5099         // (authentication required, unlocked device required).
5100         make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5101         make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5102         make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5103         make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5104         assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5105         assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5106         assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5107         assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5108 
5109         // Also store a key for a different user that requires authentication.
5110         make_superencrypted_key_entry(
5111             &mut db,
5112             other_user_nspace,
5113             "auth_ud",
5114             true,
5115             true,
5116             super_key_id,
5117         )?;
5118 
5119         db.unbind_auth_bound_keys_for_user(user_id)?;
5120 
5121         // Verify that only the user's app keys that require authentication were
5122         // deleted. Keys that require an unlocked device but not authentication
5123         // should *not* have been deleted, nor should the super key have been
5124         // deleted, nor should other users' keys have been deleted.
5125         assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5126         assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5127         assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5128         assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5129         assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5130         assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5131 
5132         Ok(())
5133     }
5134 
5135     #[test]
test_store_super_key() -> Result<()>5136     fn test_store_super_key() -> Result<()> {
5137         let mut db = new_test_db()?;
5138         let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5139         let super_key = keystore2_crypto::generate_aes256_key()?;
5140         let secret_bytes = b"keystore2 is great.";
5141         let (encrypted_secret, iv, tag) =
5142             keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
5143 
5144         let (encrypted_super_key, metadata) =
5145             SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5146         db.store_super_key(
5147             1,
5148             &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
5149             &encrypted_super_key,
5150             &metadata,
5151             &KeyMetaData::new(),
5152         )?;
5153 
5154         // Check if super key exists.
5155         assert!(db.key_exists(
5156             Domain::APP,
5157             1,
5158             USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5159             KeyType::Super
5160         )?);
5161 
5162         let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
5163         let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5164             USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
5165             key_entry,
5166             &pw,
5167             None,
5168         )?;
5169 
5170         let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
5171         assert_eq!(secret_bytes, &*decrypted_secret_bytes);
5172 
5173         Ok(())
5174     }
5175 
get_valid_statsd_storage_types() -> Vec<MetricsStorage>5176     fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
5177         vec![
5178             MetricsStorage::KEY_ENTRY,
5179             MetricsStorage::KEY_ENTRY_ID_INDEX,
5180             MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5181             MetricsStorage::BLOB_ENTRY,
5182             MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5183             MetricsStorage::KEY_PARAMETER,
5184             MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5185             MetricsStorage::KEY_METADATA,
5186             MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5187             MetricsStorage::GRANT,
5188             MetricsStorage::AUTH_TOKEN,
5189             MetricsStorage::BLOB_METADATA,
5190             MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
5191         ]
5192     }
5193 
5194     /// Perform a simple check to ensure that we can query all the storage types
5195     /// that are supported by the DB. Check for reasonable values.
5196     #[test]
test_query_all_valid_table_sizes() -> Result<()>5197     fn test_query_all_valid_table_sizes() -> Result<()> {
5198         const PAGE_SIZE: i32 = 4096;
5199 
5200         let mut db = new_test_db()?;
5201 
5202         for t in get_valid_statsd_storage_types() {
5203             let stat = db.get_storage_stat(t)?;
5204             // AuthToken can be less than a page since it's in a btree, not sqlite
5205             // TODO(b/187474736) stop using if-let here
5206             if let MetricsStorage::AUTH_TOKEN = t {
5207             } else {
5208                 assert!(stat.size >= PAGE_SIZE);
5209             }
5210             assert!(stat.size >= stat.unused_size);
5211         }
5212 
5213         Ok(())
5214     }
5215 
get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats>5216     fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
5217         get_valid_statsd_storage_types()
5218             .into_iter()
5219             .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
5220             .collect()
5221     }
5222 
assert_storage_increased( db: &mut KeystoreDB, increased_storage_types: Vec<MetricsStorage>, baseline: &mut BTreeMap<i32, StorageStats>, )5223     fn assert_storage_increased(
5224         db: &mut KeystoreDB,
5225         increased_storage_types: Vec<MetricsStorage>,
5226         baseline: &mut BTreeMap<i32, StorageStats>,
5227     ) {
5228         for storage in increased_storage_types {
5229             // Verify the expected storage increased.
5230             let new = db.get_storage_stat(storage).unwrap();
5231             let old = &baseline[&storage.0];
5232             assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
5233             assert!(
5234                 new.unused_size <= old.unused_size,
5235                 "{}: {} <= {}",
5236                 storage.0,
5237                 new.unused_size,
5238                 old.unused_size
5239             );
5240 
5241             // Update the baseline with the new value so that it succeeds in the
5242             // later comparison.
5243             baseline.insert(storage.0, new);
5244         }
5245 
5246         // Get an updated map of the storage and verify there were no unexpected changes.
5247         let updated_stats = get_storage_stats_map(db);
5248         assert_eq!(updated_stats.len(), baseline.len());
5249 
5250         for &k in baseline.keys() {
5251             let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
5252                 let mut s = String::new();
5253                 for &k in map.keys() {
5254                     writeln!(&mut s, "  {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5255                         .expect("string concat failed");
5256                 }
5257                 s
5258             };
5259 
5260             assert!(
5261                 updated_stats[&k].size == baseline[&k].size
5262                     && updated_stats[&k].unused_size == baseline[&k].unused_size,
5263                 "updated_stats:\n{}\nbaseline:\n{}",
5264                 stringify(&updated_stats),
5265                 stringify(baseline)
5266             );
5267         }
5268     }
5269 
5270     #[test]
test_verify_key_table_size_reporting() -> Result<()>5271     fn test_verify_key_table_size_reporting() -> Result<()> {
5272         let mut db = new_test_db()?;
5273         let mut working_stats = get_storage_stats_map(&mut db);
5274 
5275         let key_id = create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
5276         assert_storage_increased(
5277             &mut db,
5278             vec![
5279                 MetricsStorage::KEY_ENTRY,
5280                 MetricsStorage::KEY_ENTRY_ID_INDEX,
5281                 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5282             ],
5283             &mut working_stats,
5284         );
5285 
5286         let mut blob_metadata = BlobMetaData::new();
5287         blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5288         db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5289         assert_storage_increased(
5290             &mut db,
5291             vec![
5292                 MetricsStorage::BLOB_ENTRY,
5293                 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5294                 MetricsStorage::BLOB_METADATA,
5295                 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
5296             ],
5297             &mut working_stats,
5298         );
5299 
5300         let params = make_test_params(None);
5301         db.insert_keyparameter(&key_id, &params)?;
5302         assert_storage_increased(
5303             &mut db,
5304             vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
5305             &mut working_stats,
5306         );
5307 
5308         let mut metadata = KeyMetaData::new();
5309         metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5310         db.insert_key_metadata(&key_id, &metadata)?;
5311         assert_storage_increased(
5312             &mut db,
5313             vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
5314             &mut working_stats,
5315         );
5316 
5317         let mut sum = 0;
5318         for stat in working_stats.values() {
5319             sum += stat.size;
5320         }
5321         let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
5322         assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5323 
5324         Ok(())
5325     }
5326 
5327     #[test]
test_verify_auth_table_size_reporting() -> Result<()>5328     fn test_verify_auth_table_size_reporting() -> Result<()> {
5329         let mut db = new_test_db()?;
5330         let mut working_stats = get_storage_stats_map(&mut db);
5331         db.insert_auth_token(&HardwareAuthToken {
5332             challenge: 123,
5333             userId: 456,
5334             authenticatorId: 789,
5335             authenticatorType: kmhw_authenticator_type::ANY,
5336             timestamp: Timestamp { milliSeconds: 10 },
5337             mac: b"mac".to_vec(),
5338         });
5339         assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
5340         Ok(())
5341     }
5342 
5343     #[test]
test_verify_grant_table_size_reporting() -> Result<()>5344     fn test_verify_grant_table_size_reporting() -> Result<()> {
5345         const OWNER: i64 = 1;
5346         let mut db = new_test_db()?;
5347         make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5348 
5349         let mut working_stats = get_storage_stats_map(&mut db);
5350         db.grant(
5351             &KeyDescriptor {
5352                 domain: Domain::APP,
5353                 nspace: 0,
5354                 alias: Some(TEST_ALIAS.to_string()),
5355                 blob: None,
5356             },
5357             OWNER as u32,
5358             123,
5359             key_perm_set![KeyPerm::Use],
5360             |_, _| Ok(()),
5361         )?;
5362 
5363         assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
5364 
5365         Ok(())
5366     }
5367 
5368     #[test]
find_auth_token_entry_returns_latest() -> Result<()>5369     fn find_auth_token_entry_returns_latest() -> Result<()> {
5370         let mut db = new_test_db()?;
5371         db.insert_auth_token(&HardwareAuthToken {
5372             challenge: 123,
5373             userId: 456,
5374             authenticatorId: 789,
5375             authenticatorType: kmhw_authenticator_type::ANY,
5376             timestamp: Timestamp { milliSeconds: 10 },
5377             mac: b"mac0".to_vec(),
5378         });
5379         std::thread::sleep(std::time::Duration::from_millis(1));
5380         db.insert_auth_token(&HardwareAuthToken {
5381             challenge: 123,
5382             userId: 457,
5383             authenticatorId: 789,
5384             authenticatorType: kmhw_authenticator_type::ANY,
5385             timestamp: Timestamp { milliSeconds: 12 },
5386             mac: b"mac1".to_vec(),
5387         });
5388         std::thread::sleep(std::time::Duration::from_millis(1));
5389         db.insert_auth_token(&HardwareAuthToken {
5390             challenge: 123,
5391             userId: 458,
5392             authenticatorId: 789,
5393             authenticatorType: kmhw_authenticator_type::ANY,
5394             timestamp: Timestamp { milliSeconds: 3 },
5395             mac: b"mac2".to_vec(),
5396         });
5397         // All three entries are in the database
5398         assert_eq!(db.perboot.auth_tokens_len(), 3);
5399         // It selected the most recent timestamp
5400         assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
5401         Ok(())
5402     }
5403 
5404     #[test]
test_load_key_descriptor() -> Result<()>5405     fn test_load_key_descriptor() -> Result<()> {
5406         let mut db = new_test_db()?;
5407         let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5408 
5409         let key = db.load_key_descriptor(key_id)?.unwrap();
5410 
5411         assert_eq!(key.domain, Domain::APP);
5412         assert_eq!(key.nspace, 1);
5413         assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5414 
5415         // No such id
5416         assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5417         Ok(())
5418     }
5419 
5420     #[test]
test_get_list_app_uids_for_sid() -> Result<()>5421     fn test_get_list_app_uids_for_sid() -> Result<()> {
5422         let uid: i32 = 1;
5423         let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5424         let first_sid = 667;
5425         let second_sid = 669;
5426         let first_app_id: i64 = 123 + uid_offset;
5427         let second_app_id: i64 = 456 + uid_offset;
5428         let third_app_id: i64 = 789 + uid_offset;
5429         let unrelated_app_id: i64 = 1011 + uid_offset;
5430         let mut db = new_test_db()?;
5431         make_test_key_entry_with_sids(
5432             &mut db,
5433             Domain::APP,
5434             first_app_id,
5435             TEST_ALIAS,
5436             None,
5437             &[first_sid],
5438         )
5439         .context("test_get_list_app_uids_for_sid")?;
5440         make_test_key_entry_with_sids(
5441             &mut db,
5442             Domain::APP,
5443             second_app_id,
5444             "alias2",
5445             None,
5446             &[first_sid],
5447         )
5448         .context("test_get_list_app_uids_for_sid")?;
5449         make_test_key_entry_with_sids(
5450             &mut db,
5451             Domain::APP,
5452             second_app_id,
5453             TEST_ALIAS,
5454             None,
5455             &[second_sid],
5456         )
5457         .context("test_get_list_app_uids_for_sid")?;
5458         make_test_key_entry_with_sids(
5459             &mut db,
5460             Domain::APP,
5461             third_app_id,
5462             "alias3",
5463             None,
5464             &[second_sid],
5465         )
5466         .context("test_get_list_app_uids_for_sid")?;
5467         make_test_key_entry_with_sids(
5468             &mut db,
5469             Domain::APP,
5470             unrelated_app_id,
5471             TEST_ALIAS,
5472             None,
5473             &[],
5474         )
5475         .context("test_get_list_app_uids_for_sid")?;
5476 
5477         let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5478         first_sid_apps.sort();
5479         assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5480         let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5481         second_sid_apps.sort();
5482         assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5483         Ok(())
5484     }
5485 
5486     #[test]
test_get_list_app_uids_with_multiple_sids() -> Result<()>5487     fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5488         let uid: i32 = 1;
5489         let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5490         let first_sid = 667;
5491         let second_sid = 669;
5492         let third_sid = 772;
5493         let first_app_id: i64 = 123 + uid_offset;
5494         let second_app_id: i64 = 456 + uid_offset;
5495         let mut db = new_test_db()?;
5496         make_test_key_entry_with_sids(
5497             &mut db,
5498             Domain::APP,
5499             first_app_id,
5500             TEST_ALIAS,
5501             None,
5502             &[first_sid, second_sid],
5503         )
5504         .context("test_get_list_app_uids_for_sid")?;
5505         make_test_key_entry_with_sids(
5506             &mut db,
5507             Domain::APP,
5508             second_app_id,
5509             "alias2",
5510             None,
5511             &[second_sid, third_sid],
5512         )
5513         .context("test_get_list_app_uids_for_sid")?;
5514 
5515         let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5516         assert_eq!(first_sid_apps, vec![first_app_id]);
5517 
5518         let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5519         second_sid_apps.sort();
5520         assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5521 
5522         let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5523         assert_eq!(third_sid_apps, vec![second_app_id]);
5524         Ok(())
5525     }
5526 
5527     #[test]
test_key_id_guard_immediate() -> Result<()>5528     fn test_key_id_guard_immediate() -> Result<()> {
5529         if !keystore2_flags::database_loop_timeout() {
5530             eprintln!("Skipping test as loop timeout flag disabled");
5531             return Ok(());
5532         }
5533         // Emit logging from test.
5534         android_logger::init_once(
5535             android_logger::Config::default()
5536                 .with_tag("keystore_database_tests")
5537                 .with_max_level(log::LevelFilter::Debug),
5538         );
5539 
5540         // Preparation: put a single entry into a test DB.
5541         let temp_dir = Arc::new(TempDir::new("key_id_guard_immediate")?);
5542         let temp_dir_clone_a = temp_dir.clone();
5543         let temp_dir_clone_b = temp_dir.clone();
5544         let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5545         let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5546 
5547         let (a_sender, b_receiver) = std::sync::mpsc::channel();
5548         let (b_sender, a_receiver) = std::sync::mpsc::channel();
5549 
5550         // First thread starts an immediate transaction, then waits on a synchronization channel
5551         // before trying to get the `KeyIdGuard`.
5552         let handle_a = thread::spawn(move || {
5553             let temp_dir = temp_dir_clone_a;
5554             let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
5555 
5556             // Make sure the other thread has initialized its database access before we lock it out.
5557             a_receiver.recv().unwrap();
5558 
5559             let _result =
5560                 db.with_transaction_timeout(Immediate("TX_test"), Duration::from_secs(3), |_tx| {
5561                     // Notify the other thread that we're inside the immediate transaction...
5562                     a_sender.send(()).unwrap();
5563                     // ...then wait to be sure that the other thread has the `KeyIdGuard` before
5564                     // this thread also tries to get it.
5565                     a_receiver.recv().unwrap();
5566 
5567                     let _guard = KEY_ID_LOCK.get(key_id);
5568                     Ok(()).no_gc()
5569                 });
5570         });
5571 
5572         // Second thread gets the `KeyIdGuard`, then waits before trying to perform an immediate
5573         // transaction.
5574         let handle_b = thread::spawn(move || {
5575             let temp_dir = temp_dir_clone_b;
5576             let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
5577             // Notify the other thread that we are initialized (so it can lock the immediate
5578             // transaction).
5579             b_sender.send(()).unwrap();
5580 
5581             let _guard = KEY_ID_LOCK.get(key_id);
5582             // Notify the other thread that we have the `KeyIdGuard`...
5583             b_sender.send(()).unwrap();
5584             // ...then wait to be sure that the other thread is in the immediate transaction before
5585             // this thread also tries to do one.
5586             b_receiver.recv().unwrap();
5587 
5588             let result =
5589                 db.with_transaction_timeout(Immediate("TX_test"), Duration::from_secs(3), |_tx| {
5590                     Ok(()).no_gc()
5591                 });
5592             // Expect the attempt to get an immediate transaction to fail, and then this thread will
5593             // exit and release the `KeyIdGuard`, allowing the other thread to complete.
5594             assert!(result.is_err());
5595             check_result_is_error_containing_string(result, "BACKEND_BUSY");
5596         });
5597 
5598         let _ = handle_a.join();
5599         let _ = handle_b.join();
5600 
5601         Ok(())
5602     }
5603 }
5604