blob: 50cd3ba852b061360b0be547d97209a4fc7c34ae [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// 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
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! 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.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
Janis Danisevskis030ba022021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskis11bd2592022-01-04 19:59:26 -080048use crate::gc::Gc;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use crate::impl_metadata; // This is in db_utils.rs
Eric Biggersb0478cf2023-10-27 03:55:29 +000050use crate::key_parameter::{KeyParameter, KeyParameterValue, Tag};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000051use crate::ks_err;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070052use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000053use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070055 error::{Error as KsError, ErrorCode, ResponseCode},
56 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080057};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000058use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Tri Voa1634bb2022-12-01 15:54:19 -080059 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
60 SecurityLevel::SecurityLevel,
61};
62use android_security_metrics::aidl::android::security::metrics::{
Tri Vo0346bbe2023-05-12 14:16:31 -040063 Storage::Storage as MetricsStorage, StorageStats::StorageStats,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080064};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070065use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070066 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070067};
Shaquille Johnson7f5a8152023-09-27 18:46:27 +010068use anyhow::{anyhow, Context, Result};
69use keystore2_flags;
70use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
71use utils as db_utils;
72use utils::SqlField;
Max Bires2b2e6562020-09-22 11:22:36 -070073
74use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080075use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000076use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070077#[cfg(not(test))]
78use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070079use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070080 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080081 types::FromSql,
82 types::FromSqlResult,
83 types::ToSqlOutput,
84 types::{FromSqlError, Value, ValueRef},
David Drysdale7b9ca232024-05-23 18:19:46 +010085 Connection, OptionalExtension, ToSql, Transaction,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070086};
Max Bires2b2e6562020-09-22 11:22:36 -070087
Janis Danisevskisaec14592020-11-12 09:41:49 -080088use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080089 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080090 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070091 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080093};
Max Bires2b2e6562020-09-22 11:22:36 -070094
David Drysdale7b9ca232024-05-23 18:19:46 +010095use TransactionBehavior::Immediate;
96
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
David Drysdale7b9ca232024-05-23 18:19:46 +0100100/// Wrapper for `rusqlite::TransactionBehavior` which includes information about the transaction
101/// being performed.
102#[derive(Clone, Copy)]
103enum TransactionBehavior {
104 Deferred,
105 Immediate(&'static str),
106}
107
108impl From<TransactionBehavior> for rusqlite::TransactionBehavior {
109 fn from(val: TransactionBehavior) -> Self {
110 match val {
111 TransactionBehavior::Deferred => rusqlite::TransactionBehavior::Deferred,
112 TransactionBehavior::Immediate(_) => rusqlite::TransactionBehavior::Immediate,
113 }
114 }
115}
116
117impl TransactionBehavior {
118 fn name(&self) -> Option<&'static str> {
119 match self {
120 TransactionBehavior::Deferred => None,
121 TransactionBehavior::Immediate(v) => Some(v),
122 }
123 }
124}
125
David Drysdale115c4722024-04-15 14:11:52 +0100126/// If the database returns a busy error code, retry after this interval.
127const DB_BUSY_RETRY_INTERVAL: Duration = Duration::from_micros(500);
128/// If the database returns a busy error code, keep retrying for this long.
129const MAX_DB_BUSY_RETRY_PERIOD: Duration = Duration::from_secs(15);
130
131/// Check whether a database lock has timed out.
132fn 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
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800144impl_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 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800151 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800152 CreationDate(DateTime) with accessor creation_date,
153 /// Expiration date for attestation keys.
154 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700155 /// 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,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700161 /// SEC1 public key for ECDH encryption
162 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800163 // --- 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
169impl KeyMetaData {
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 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000176 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800177
178 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
179
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000180 let mut rows = stmt
181 .query(params![key_id])
182 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800183 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,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700187 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800188 .context("Failed to read KeyMetaEntry.")?,
189 );
190 Ok(())
191 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000192 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800193
194 Ok(Self { data: metadata })
195 }
196
197 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
198 let mut stmt = tx
199 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000200 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800201 VALUES (?, ?, ?);",
202 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000203 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800204
205 let iter = self.data.iter();
206 for (tag, entry) in iter {
207 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000208 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800209 })?;
210 }
211 Ok(())
212 }
213}
214
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800215impl_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,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700234 /// If the key is ECDH encrypted, this is the ephemeral public key
235 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000236 /// 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,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800239 // --- 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
245impl BlobMetaData {
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 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000252 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800253
254 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
255
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000256 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800257 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,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700261 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800262 .context("Failed to read BlobMetaEntry.")?,
263 );
264 Ok(())
265 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000266 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800267
268 Ok(Self { data: metadata })
269 }
270
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 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000277 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800278
279 let iter = self.data.iter();
280 for (tag, entry) in iter {
281 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000282 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800283 })?;
284 }
285 Ok(())
286 }
287}
288
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800289/// Indicates the type of the keyentry.
290#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
291pub 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,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800298}
299
300impl ToSql for KeyType {
301 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
302 Ok(ToSqlOutput::Owned(Value::Integer(match self {
303 KeyType::Client => 0,
304 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800305 })))
306 }
307}
308
309impl FromSql for KeyType {
310 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
311 match i64::column_result(value)? {
312 0 => Ok(KeyType::Client),
313 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800314 v => Err(FromSqlError::OutOfRange(v)),
315 }
316 }
317}
318
Max Bires8e93d2b2021-01-14 13:17:59 -0800319/// 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)]
323pub struct Uuid([u8; 16]);
324
325impl Deref for Uuid {
326 type Target = [u8; 16];
327
328 fn deref(&self) -> &Self::Target {
329 &self.0
330 }
331}
332
333impl From<SecurityLevel> for Uuid {
334 fn from(sec_level: SecurityLevel) -> Self {
335 Self((sec_level.0 as u128).to_be_bytes())
336 }
337}
338
339impl ToSql for Uuid {
340 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
341 self.0.to_sql()
342 }
343}
344
345impl FromSql for Uuid {
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.
359pub static KEYSTORE_UUID: Uuid = Uuid([
360 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
361]);
362
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800363/// Indicates how the sensitive part of this key blob is encrypted.
364#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
365pub 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
375impl ToSql for EncryptedBy {
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
384impl FromSql for EncryptedBy {
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)]
396pub struct DateTime(i64);
397
398/// Error type returned when creating DateTime or converting it from and to
399/// SystemTime.
400#[derive(thiserror::Error, Debug)]
401pub 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
415impl 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.
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.
423 pub fn from_millis_epoch(millis: i64) -> Self {
424 Self(millis)
425 }
426
427 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700428 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800429 self.0
430 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800431}
432
433impl ToSql for DateTime {
434 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
435 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
436 }
437}
438
439impl FromSql for DateTime {
440 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
441 Ok(Self(i64::column_result(value)?))
442 }
443}
444
445impl TryInto<SystemTime> for DateTime {
446 type Error = DateTimeError;
447
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
475impl TryFrom<SystemTime> for DateTime {
476 type Error = DateTimeError;
477
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
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800483#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
484enum 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
495impl ToSql for KeyLifeCycle {
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
505impl FromSql for KeyLifeCycle {
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
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700516/// 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.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800520#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700521pub struct KeyEntryLoadBits(u32);
522
523impl 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.
534 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.
539 pub const fn load_km(&self) -> bool {
540 self.0 & Self::KM.0 != 0
541 }
542}
543
Janis Danisevskisaec14592020-11-12 09:41:49 -0800544lazy_static! {
545 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
546}
547
548struct 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)]
557pub struct KeyIdGuard(i64);
558
559impl KeyIdLockDb {
560 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.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000567 fn get(&self, key_id: i64) -> KeyIdGuard {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800568 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.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000580 fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800581 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
590impl KeyIdGuard {
591 /// Get the numeric key id of the locked key.
592 pub fn id(&self) -> i64 {
593 self.0
594 }
595}
596
597impl Drop for KeyIdGuard {
598 fn drop(&mut self) {
599 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
600 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800601 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800602 KEY_ID_LOCK.cond_var.notify_all();
603 }
604}
605
Max Bires8e93d2b2021-01-14 13:17:59 -0800606/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700607#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800608pub struct CertificateInfo {
609 cert: Option<Vec<u8>>,
610 cert_chain: Option<Vec<u8>>,
611}
612
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800613/// This type represents a Blob with its metadata and an optional superseded blob.
614#[derive(Debug)]
615pub 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
625impl<'a> BlobInfo<'a> {
626 /// Create a new instance of blob info with blob and corresponding metadata
627 /// and no superseded blob info.
628 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.
634 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
Max Bires8e93d2b2021-01-14 13:17:59 -0800643impl CertificateInfo {
644 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
645 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
646 Self { cert, cert_chain }
647 }
648
649 /// Take the cert
650 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
651 self.cert.take()
652 }
653
654 /// Take the cert chain
655 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
656 self.cert_chain.take()
657 }
658}
659
Max Bires2b2e6562020-09-22 11:22:36 -0700660/// 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.
Max Bires2b2e6562020-09-22 11:22:36 -0700662pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800663 /// 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>,
Max Bires2b2e6562020-09-22 11:22:36 -0700670}
671
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700672/// 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.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800676#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677pub struct KeyEntry {
678 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800679 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700680 cert: Option<Vec<u8>>,
681 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800682 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700683 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800684 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800685 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700686}
687
688impl KeyEntry {
689 /// Returns the unique id of the Key entry.
690 pub fn id(&self) -> i64 {
691 self.id
692 }
693 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800694 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
695 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700696 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800697 /// Extracts the Optional KeyMint blob including its metadata.
698 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
699 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700700 }
701 /// Exposes the optional public certificate.
702 pub fn cert(&self) -> &Option<Vec<u8>> {
703 &self.cert
704 }
705 /// Extracts the optional public certificate.
706 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
707 self.cert.take()
708 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700709 /// Extracts the optional public certificate_chain.
710 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
711 self.cert_chain.take()
712 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800713 /// Returns the uuid of the owning KeyMint instance.
714 pub fn km_uuid(&self) -> &Uuid {
715 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700716 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700717 /// Consumes this key entry and extracts the keyparameters from it.
718 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
719 self.parameters
720 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800721 /// Exposes the key metadata of this key entry.
722 pub fn metadata(&self) -> &KeyMetaData {
723 &self.metadata
724 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800725 /// This returns true if the entry is a pure certificate entry with no
726 /// private key component.
727 pub fn pure_cert(&self) -> bool {
728 self.pure_cert
729 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700730}
731
732/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800733#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700734pub struct SubComponentType(u32);
735impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800736 /// Persistent identifier for a key blob.
737 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700738 /// 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
744impl ToSql for SubComponentType {
745 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
746 self.0.to_sql()
747 }
748}
749
750impl FromSql for SubComponentType {
751 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
752 Ok(Self(u32::column_result(value)?))
753 }
754}
755
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800756/// 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()`.
762trait DoGc<T> {
763 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
764
765 fn no_gc(self) -> Result<(bool, T)>;
766
767 fn need_gc(self) -> Result<(bool, T)>;
768}
769
770impl<T> DoGc<T> for Result<T> {
771 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
772 self.map(|r| (need_gc, r))
773 }
774
775 fn no_gc(self) -> Result<(bool, T)> {
776 self.do_gc(false)
777 }
778
779 fn need_gc(self) -> Result<(bool, T)> {
780 self.do_gc(true)
781 }
782}
783
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700784/// KeystoreDB wraps a connection to an SQLite database and tracks its
785/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700786pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700787 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700788 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700789 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700790}
791
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000792/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000793/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000794#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000795pub struct BootTime(i64);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000796
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000797impl BootTime {
798 /// Constructs a new BootTime
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000799 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000800 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000801 }
802
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000803 /// Returns the value of BootTime in milliseconds as i64
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000804 pub fn milliseconds(&self) -> i64 {
805 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000806 }
807
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000808 /// Returns the integer value of BootTime as i64
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000809 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000810 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000811 }
812
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800813 /// Like i64::checked_sub.
814 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
815 self.0.checked_sub(other.0).map(Self)
816 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000817}
818
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000819impl ToSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000820 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
821 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
822 }
823}
824
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000825impl FromSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000826 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
827 Ok(Self(i64::column_result(value)?))
828 }
829}
830
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000831/// This struct encapsulates the information to be stored in the database about the auth tokens
832/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700833#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000834pub struct AuthTokenEntry {
835 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000836 // Time received in milliseconds
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000837 time_received: BootTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000838}
839
840impl AuthTokenEntry {
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000841 fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000842 AuthTokenEntry { auth_token, time_received }
843 }
844
845 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800846 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000847 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800848 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000849 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000850 })
851 }
852
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000853 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800854 pub fn auth_token(&self) -> &HardwareAuthToken {
855 &self.auth_token
856 }
857
858 /// Returns the auth token wrapped by the AuthTokenEntry
859 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000860 self.auth_token
861 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800862
863 /// Returns the time that this auth token was received.
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000864 pub fn time_received(&self) -> BootTime {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800865 self.time_received
866 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000867
868 /// Returns the challenge value of the auth token.
869 pub fn challenge(&self) -> i64 {
870 self.auth_token.challenge
871 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000872}
873
Joel Galenson26f4d012020-07-17 14:57:21 -0700874impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800875 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700876 const CURRENT_DB_VERSION: u32 = 1;
877 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800878
Seth Moore78c091f2021-04-09 21:38:30 +0000879 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700880 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000881
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700882 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800883 /// 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.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700886 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700887 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
David Drysdale541846b2024-05-23 13:16:07 +0100888 let _wp = wd::watch("KeystoreDB::new");
Janis Danisevskis850d4862021-05-05 08:41:14 -0700889
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700890 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700891 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800892
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700893 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
David Drysdale7b9ca232024-05-23 18:19:46 +0100894 db.with_transaction(Immediate("TX_new"), |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700895 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000896 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800897 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800898 })?;
899 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700900 }
901
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700902 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
903 // cryptographic binding to the boot level keys was implemented.
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 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000918 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700919 Ok(1)
920 }
921
Janis Danisevskis66784c42021-01-27 08:40:25 -0800922 fn init_tables(tx: &Transaction) -> Result<()> {
923 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700924 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700925 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800926 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700927 domain INTEGER,
928 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800929 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800930 state INTEGER,
931 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000932 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700933 )
934 .context("Failed to initialize \"keyentry\" table.")?;
935
Janis Danisevskis66784c42021-01-27 08:40:25 -0800936 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800937 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
938 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000939 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800940 )
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);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000946 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800947 )
948 .context("Failed to create index keyentry_domain_namespace_index.")?;
949
950 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700951 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
952 id INTEGER PRIMARY KEY,
953 subcomponent_type INTEGER,
954 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800955 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000956 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700957 )
958 .context("Failed to initialize \"blobentry\" table.")?;
959
Janis Danisevskis66784c42021-01-27 08:40:25 -0800960 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800961 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
962 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000963 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800964 )
965 .context("Failed to create index blobentry_keyentryid_index.")?;
966
967 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800968 "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));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000974 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800975 )
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);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000981 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800982 )
983 .context("Failed to create index blobmetadata_blobentryid_index.")?;
984
985 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700986 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000987 keyentryid INTEGER,
988 tag INTEGER,
989 data ANY,
990 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000991 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700992 )
993 .context("Failed to initialize \"keyparameter\" table.")?;
994
Janis Danisevskis66784c42021-01-27 08:40:25 -0800995 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800996 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
997 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000998 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800999 )
1000 .context("Failed to create index keyparameter_keyentryid_index.")?;
1001
1002 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001003 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
1004 keyentryid INTEGER,
1005 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001006 data ANY,
1007 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001008 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001009 )
1010 .context("Failed to initialize \"keymetadata\" table.")?;
1011
Janis Danisevskis66784c42021-01-27 08:40:25 -08001012 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -08001013 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
1014 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001015 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -08001016 )
1017 .context("Failed to create index keymetadata_keyentryid_index.")?;
1018
1019 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001020 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001021 id INTEGER UNIQUE,
1022 grantee INTEGER,
1023 keyentryid INTEGER,
1024 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001025 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001026 )
1027 .context("Failed to initialize \"grant\" table.")?;
1028
Joel Galenson0891bc12020-07-20 10:37:03 -07001029 Ok(())
1030 }
1031
Seth Moore472fcbb2021-05-12 10:07:51 -07001032 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
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001041 // 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
Seth Moore472fcbb2021-05-12 10:07:51 -07001049 Ok(persistent_path_str)
1050 }
1051
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001052 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001053 let conn =
1054 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1055
Janis Danisevskis66784c42021-01-27 08:40:25 -08001056 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) {
David Drysdale115c4722024-04-15 14:11:52 +01001062 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001063 continue;
1064 } else {
1065 return Err(e);
1066 }
1067 }
1068 break;
1069 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001070
Matthew Maurer4fb19112021-05-06 15:40:44 -07001071 // 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")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001074
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001075 Ok(conn)
1076 }
1077
Seth Moore78c091f2021-04-09 21:38:30 +00001078 fn do_table_size_query(
1079 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001080 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001081 query: &str,
1082 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001083 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001084 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001085 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001086 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001087 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001088 })
1089 .no_gc()
1090 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001091 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001092 }
1093
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001094 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001095 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001096 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001097 "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
1105 fn get_table_size(
1106 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001108 schema: &str,
1109 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001110 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001111 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.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
David Drysdale541846b2024-05-23 13:16:07 +01001123 let _wp = wd::watch("KeystoreDB::get_storage_stat");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001124
Seth Moore78c091f2021-04-09 21:38:30 +00001125 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001126 MetricsStorage::DATABASE => self.get_total_size(),
1127 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001128 self.get_table_size(storage_type, "persistent", "keyentry")
1129 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001131 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1132 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001133 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001134 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1135 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001137 self.get_table_size(storage_type, "persistent", "blobentry")
1138 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001140 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1141 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001142 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001143 self.get_table_size(storage_type, "persistent", "keyparameter")
1144 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001145 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001146 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1147 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001148 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001149 self.get_table_size(storage_type, "persistent", "keymetadata")
1150 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001151 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001152 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1153 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001154 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1155 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001156 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1157 // reportable
1158 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001159 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001160 storage_type,
1161 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001162 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001163 unused_size: 0,
1164 })
Seth Moore78c091f2021-04-09 21:38:30 +00001165 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001166 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001167 self.get_table_size(storage_type, "persistent", "blobmetadata")
1168 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001169 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001170 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1171 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001172 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001173 }
1174 }
1175
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001176 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001177 /// 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.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001179 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1180 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001181 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001182 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001183 blob_ids_to_delete: &[i64],
1184 max_blobs: usize,
1185 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
David Drysdale541846b2024-05-23 13:16:07 +01001186 let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob");
David Drysdale7b9ca232024-05-23 18:19:46 +01001187 self.with_transaction(Immediate("TX_handle_next_superseded_blob"), |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001188 // Delete the given blobs.
1189 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001190 tx.execute(
1191 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001192 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001193 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001194 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001195 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001196 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001197 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001198
1199 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1200
Janis Danisevskis3395f862021-05-06 10:54:17 -07001201 // 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.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001217
Janis Danisevskis3395f862021-05-06 10:54:17 -07001218 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();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001242 }
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
Janis Danisevskis3395f862021-05-06 10:54:17 -07001260 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001261 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001262 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001263 }
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.
1273 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01001274 let _wp = wd::watch("KeystoreDB::cleanup_leftovers");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001275
David Drysdale7b9ca232024-05-23 18:19:46 +01001276 self.with_transaction(Immediate("TX_cleanup_leftovers"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001277 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001278 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1279 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1280 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001281 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001282 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001283 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001284 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001285 }
1286
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001287 /// Checks if a key exists with given key type and key descriptor properties.
1288 pub fn key_exists(
1289 &mut self,
1290 domain: Domain,
1291 nspace: i64,
1292 alias: &str,
1293 key_type: KeyType,
1294 ) -> Result<bool> {
David Drysdale541846b2024-05-23 13:16:07 +01001295 let _wp = wd::watch("KeystoreDB::key_exists");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001296
David Drysdale7b9ca232024-05-23 18:19:46 +01001297 self.with_transaction(Immediate("TX_key_exists"), |tx| {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001298 let key_descriptor =
1299 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001300 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001301 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),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001305 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001306 },
1307 }
1308 .no_gc()
1309 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001310 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001311 }
1312
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 /// Stores a super key in the database.
1314 pub fn store_super_key(
1315 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001316 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001317 key_type: &SuperKeyType,
1318 blob: &[u8],
1319 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001320 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001321 ) -> Result<KeyEntry> {
David Drysdale541846b2024-05-23 13:16:07 +01001322 let _wp = wd::watch("KeystoreDB::store_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001323
David Drysdale7b9ca232024-05-23 18:19:46 +01001324 self.with_transaction(Immediate("TX_store_super_key"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00001325 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)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001329 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001330 params![
1331 id,
1332 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001333 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001334 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001335 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001336 KeyLifeCycle::Live,
1337 &KEYSTORE_UUID,
1338 ],
1339 )
1340 })
1341 .context("Failed to insert into keyentry table.")?;
1342
Paul Crowley8d5b2532021-03-19 10:53:07 -07001343 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1344
Hasini Gunasingheda895552021-01-27 19:34:37 +00001345 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001346 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001347 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 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001358 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001359 }
1360
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001361 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001362 pub fn load_super_key(
1363 &mut self,
1364 key_type: &SuperKeyType,
1365 user_id: u32,
1366 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
David Drysdale541846b2024-05-23 13:16:07 +01001367 let _wp = wd::watch("KeystoreDB::load_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001368
David Drysdale7b9ca232024-05-23 18:19:46 +01001369 self.with_transaction(Immediate("TX_load_super_key"), |tx| {
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001370 let key_descriptor = KeyDescriptor {
1371 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001372 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001373 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001374 blob: None,
1375 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001376 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001377 match id {
1378 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001379 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001380 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001381 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),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001385 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001386 },
1387 }
1388 .no_gc()
1389 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001390 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001391 }
1392
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001393 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001394 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1395 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001396 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1397 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001398 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001399 {
David Drysdale115c4722024-04-15 14:11:52 +01001400 self.with_transaction_timeout(behavior, MAX_DB_BUSY_RETRY_PERIOD, f)
1401 }
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();
David Drysdale7b9ca232024-05-23 18:19:46 +01001412 let name = behavior.name();
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001414 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001415 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01001416 .transaction_with_behavior(behavior.into())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001417 .context(ks_err!())
David Drysdale7b9ca232024-05-23 18:19:46 +01001418 .and_then(|tx| {
1419 let _wp = name.map(wd::watch);
1420 f(&tx).map(|result| (result, tx))
1421 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001422 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001423 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001425 });
1426 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001427 Ok(result) => break Ok(result),
1428 Err(e) => {
1429 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001430 check_lock_timeout(&start, timeout)?;
1431 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001432 continue;
1433 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001434 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001435 }
1436 }
1437 }
1438 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001439 .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 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001447 }
1448
1449 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001450 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 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001455 }
1456
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001457 fn create_key_entry_internal(
1458 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001459 domain: &Domain,
1460 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001461 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001462 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001463 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001465 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001466 _ => {
1467 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001468 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001469 }
1470 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001471 Ok(KEY_ID_LOCK.get(
1472 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001473 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001474 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001475 (id, key_type, domain, namespace, alias, state, km_uuid)
1476 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001477 params![
1478 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001479 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001480 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001481 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001482 KeyLifeCycle::Existing,
1483 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001484 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001485 )
1486 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001487 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001488 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001489 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001490
Janis Danisevskis377d1002021-01-27 19:07:48 -08001491 /// Set a new blob and associates it with the given key id. Each blob
1492 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001493 /// 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
Janis Danisevskis377d1002021-01-27 19:07:48 -08001495 /// will get garbage collected.
1496 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1497 /// removed by setting blob to None.
1498 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001499 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001500 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001501 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001502 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001503 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001504 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001505 let _wp = wd::watch("KeystoreDB::set_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001506
David Drysdale7b9ca232024-05-23 18:19:46 +01001507 self.with_transaction(Immediate("TX_set_blob"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001508 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001509 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001510 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001511 }
1512
Janis Danisevskiseed69842021-02-18 20:04:10 -08001513 /// 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.
1517 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001518 let _wp = wd::watch("KeystoreDB::set_deleted_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001519
David Drysdale7b9ca232024-05-23 18:19:46 +01001520 self.with_transaction(Immediate("TX_set_deleted_blob"), |tx| {
Janis Danisevskiseed69842021-02-18 20:04:10 -08001521 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001522 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001523 Self::UNASSIGNED_KEY_ID,
1524 SubComponentType::KEY_BLOB,
1525 Some(blob),
1526 Some(blob_metadata),
1527 )
1528 .need_gc()
1529 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001530 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001531 }
1532
Janis Danisevskis377d1002021-01-27 19:07:48 -08001533 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001534 tx: &Transaction,
1535 key_id: i64,
1536 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001537 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001538 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001539 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001540 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 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001547 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001548 if let Some(blob_metadata) = blob_metadata {
1549 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001550 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001551 row.get(0)
1552 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001553 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001554 blob_metadata
1555 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001556 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001557 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001558 }
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 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001565 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001566 }
1567 (None, _) => {
1568 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001569 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001570 }
1571 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001572 Ok(())
1573 }
1574
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001575 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1576 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001577 #[cfg(test)]
1578 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001579 self.with_transaction(Immediate("TX_insert_keyparameter"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001580 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001581 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001582 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001583 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001584
Janis Danisevskis66784c42021-01-27 08:40:25 -08001585 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001586 tx: &Transaction,
1587 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001588 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001589 ) -> Result<()> {
1590 let mut stmt = tx
1591 .prepare(
1592 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1593 VALUES (?, ?, ?, ?);",
1594 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001595 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001596
Janis Danisevskis66784c42021-01-27 08:40:25 -08001597 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001598 stmt.insert(params![
1599 key_id.0,
1600 p.get_tag().0,
1601 p.key_parameter_value(),
1602 p.security_level().0
1603 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001604 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001605 }
1606 Ok(())
1607 }
1608
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001609 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001610 #[cfg(test)]
1611 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001612 self.with_transaction(Immediate("TX_insert_key_metadata"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001613 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001614 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001615 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001616 }
1617
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001618 /// 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.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001621 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1622 /// collector.
1623 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001624 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001625 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001626 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001627 domain: &Domain,
1628 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001629 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001630 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001631 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001632 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001633 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001634 return Err(KsError::sys())
1635 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001636 }
1637 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001638 let updated = tx
1639 .execute(
1640 "UPDATE persistent.keyentry
1641 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001642 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1643 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001644 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001645 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001646 let result = tx
1647 .execute(
1648 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001649 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001650 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001651 params![
1652 alias,
1653 KeyLifeCycle::Live,
1654 newid.0,
1655 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001656 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001657 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001658 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001659 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001660 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001661 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001662 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001663 return Err(KsError::sys()).context(ks_err!(
1664 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001665 result
1666 ));
1667 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001668 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001669 }
1670
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001671 /// 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`.
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<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001680 let _wp = wd::watch("KeystoreDB::migrate_key_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001681
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001682 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 '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001692 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001693
1694 let alias = destination
1695 .alias
1696 .as_ref()
1697 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001698 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001699
David Drysdale7b9ca232024-05-23 18:19:46 +01001700 self.with_transaction(Immediate("TX_migrate_key_namespace"), |tx| {
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001701 // 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 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001732 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001733 }
1734
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001735 /// 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.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001738 /// 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.
Chris Wailes3877f292021-07-26 19:24:18 -07001740 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001741 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001742 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001743 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001744 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001745 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001746 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001747 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001748 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001749 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001750 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001751 let _wp = wd::watch("KeystoreDB::store_new_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001752
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001753 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))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001760 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001761 }
1762 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001763 self.with_transaction(Immediate("TX_store_new_key"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001764 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001765 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001766 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
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001787 Self::set_blob_internal(
1788 tx,
1789 key_id.id(),
1790 SubComponentType::KEY_BLOB,
1791 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001792 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001793 )
1794 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001795 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001796 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001797 .context("Trying to insert the certificate.")?;
1798 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001799 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001800 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001801 tx,
1802 key_id.id(),
1803 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001804 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001805 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001806 )
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.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001811 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001812 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001813 .context("Trying to rebind alias.")?
1814 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001815 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001816 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001817 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001818 }
1819
Janis Danisevskis377d1002021-01-27 19:07:48 -08001820 /// 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.
Max Bires8e93d2b2021-01-14 13:17:59 -08001823 pub fn store_new_certificate(
1824 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001825 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001826 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001827 cert: &[u8],
1828 km_uuid: &Uuid,
1829 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001830 let _wp = wd::watch("KeystoreDB::store_new_certificate");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001831
Janis Danisevskis377d1002021-01-27 19:07:48 -08001832 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 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001838 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1839 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001840 }
1841 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001842 self.with_transaction(Immediate("TX_store_new_certificate"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001843 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001844 .context("Trying to create new key entry.")?;
1845
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001846 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.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001854
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
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001862 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001863 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001864 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001865 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001866 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001867 }
1868
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001869 // Helper function loading the key_id given the key descriptor
1870 // tuple comprising domain, namespace, and alias.
1871 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001872 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001873 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
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001882 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001883 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001884 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001885 AND alias = ?
1886 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001887 )
1888 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1889 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001890 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001891 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001892 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001893 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001894 .get(0)
1895 .context("Failed to unpack id.")
1896 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001897 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001898 }
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.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001903 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001904 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001905 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001906 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001907 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001908 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001909 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001910 /// `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.
1913 fn load_access_tuple(
1914 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001915 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001916 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001917 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
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001925 // Domain::APP.
1926 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001927 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001928 if access_key.domain == Domain::APP {
1929 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001930 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001931 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001932 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001933
1934 Ok((key_id, access_key, None))
1935 }
1936
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001937 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001938 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001939 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001940 let mut stmt = tx
1941 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001942 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001943 WHERE grantee = ? AND id = ? AND
1944 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001945 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001946 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001947 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001948 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001949 .context("Domain:Grant: query failed.")?;
1950 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001951 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001952 let r =
1953 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001954 Ok((
1955 r.get(0).context("Failed to unpack key_id.")?,
1956 r.get(1).context("Failed to unpack access_vector.")?,
1957 ))
1958 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001959 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001960 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001961 }
1962
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001963 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001964 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001965 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08001966 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.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001978 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001979 let r =
1980 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001981 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001982 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001983 r.get(1).context("Failed to unpack namespace.")?,
1984 ))
1985 })
Janis Danisevskis45760022021-01-19 16:34:10 -08001986 .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
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002011 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002012 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002013 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002014 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002015
Janis Danisevskis45760022021-01-19 16:34:10 -08002016 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002017 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002018 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002019 }
2020 }
2021
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002022 fn load_blob_components(
2023 key_id: i64,
2024 load_bits: KeyEntryLoadBits,
2025 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002026 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002027 let mut stmt = tx
2028 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002029 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002030 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2031 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002032 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002033
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002034 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002035
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002036 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002037 let mut cert_blob: Option<Vec<u8>> = None;
2038 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002039 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002040 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002041 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002042 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002043 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002044 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2045 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002046 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 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002050 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002051 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002052 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002053 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002054 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002055 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002056 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002057 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002058 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002059 (SubComponentType::CERT, _, _)
2060 | (SubComponentType::CERT_CHAIN, _, _)
2061 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002062 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2063 }
2064 Ok(())
2065 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002066 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002067
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002068 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)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002072 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002073 )))
2074 })?;
2075
2076 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002077 }
2078
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.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002091 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002092 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.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002094 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002095 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002096 .context("Failed to read KeyParameter.")?,
2097 );
2098 Ok(())
2099 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002100 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002101
2102 Ok(parameters)
2103 }
2104
Qi Wub9433b52020-12-01 14:52:46 +08002105 /// 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.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002109 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002110 let _wp = wd::watch("KeystoreDB::check_and_update_key_usage_count");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002111
David Drysdale7b9ca232024-05-23 18:19:46 +01002112 self.with_transaction(Immediate("TX_check_and_update_key_usage_count"), |tx| {
Qi Wub9433b52020-12-01 14:52:46 +08002113 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)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002136 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002137 .context("Trying to mark limited use key for deletion."),
2138 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002139 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002140 }
2141 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002142 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002143 }
2144
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002145 /// 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.
2150 pub fn load_key_entry(
2151 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002152 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002153 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002154 load_bits: KeyEntryLoadBits,
2155 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002156 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2157 ) -> Result<(KeyIdGuard, KeyEntry)> {
David Drysdale541846b2024-05-23 13:16:07 +01002158 let _wp = wd::watch("KeystoreDB::load_key_entry");
David Drysdale115c4722024-04-15 14:11:52 +01002159 let start = std::time::Instant::now();
Janis Danisevskis850d4862021-05-05 08:41:14 -07002160
Janis Danisevskis66784c42021-01-27 08:40:25 -08002161 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) {
David Drysdale115c4722024-04-15 14:11:52 +01002172 check_lock_timeout(&start, MAX_DB_BUSY_RETRY_PERIOD)?;
2173 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08002174 continue;
2175 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002176 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002177 }
2178 }
2179 }
2180 }
2181 }
2182
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<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002190 ) -> 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
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002199 let tx = self
2200 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002201 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002202 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002203
2204 // Load the key_id and complete the access control tuple.
2205 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002206 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002207
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.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002210 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002211
Janis Danisevskisaec14592020-11-12 09:41:49 -08002212 // 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.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002227 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002228
Janis Danisevskisaec14592020-11-12 09:41:49 -08002229 // 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.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002233 let tx = self
2234 .conn
2235 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002236 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002237
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.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002242 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002243 domain: Domain::KEY_ID,
2244 nspace: key_id,
2245 ..Default::default()
2246 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002247 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002248 caller_uid,
2249 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002250 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002251 (key_id_guard, tx)
2252 }
2253 Some(l) => (l, tx),
2254 },
2255 Some(key_id_guard) => (key_id_guard, tx),
2256 };
2257
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002258 let key_entry =
2259 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002260
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002261 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002262
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002263 Ok((key_id_guard, key_entry))
2264 }
2265
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002266 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002268 .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.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002276 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002277 }
2278
2279 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002280 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002281 pub fn unbind_key(
2282 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002283 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002284 key_type: KeyType,
2285 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002286 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002287 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002288 let _wp = wd::watch("KeystoreDB::unbind_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002289
David Drysdale7b9ca232024-05-23 18:19:46 +01002290 self.with_transaction(Immediate("TX_unbind_key"), |tx| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002291 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
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002300 Self::mark_unreferenced(tx, key_id)
2301 .map(|need_gc| (need_gc, ()))
2302 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002303 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002304 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002305 }
2306
Max Bires8e93d2b2021-01-14 13:17:59 -08002307 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 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002313 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002314 }
2315
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002316 /// 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.
2318 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002319 let _wp = wd::watch("KeystoreDB::unbind_keys_for_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002320
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002321 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002322 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002323 }
David Drysdale7b9ca232024-05-23 18:19:46 +01002324 self.with_transaction(Immediate("TX_unbind_keys_for_namespace"), |tx| {
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002325 tx.execute(
2326 "DELETE FROM persistent.keymetadata
2327 WHERE keyentryid IN (
2328 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002329 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002330 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002331 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002332 )
2333 .context("Trying to delete keymetadata.")?;
2334 tx.execute(
2335 "DELETE FROM persistent.keyparameter
2336 WHERE keyentryid IN (
2337 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002338 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002339 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002340 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002341 )
2342 .context("Trying to delete keyparameters.")?;
2343 tx.execute(
2344 "DELETE FROM persistent.grant
2345 WHERE keyentryid IN (
2346 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002347 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002348 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002349 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002350 )
2351 .context("Trying to delete grants.")?;
2352 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002353 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002354 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2355 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002356 )
2357 .context("Trying to delete keyentry.")?;
2358 Ok(()).need_gc()
2359 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002360 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002361 }
2362
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002363 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002364 let _wp = wd::watch("KeystoreDB::cleanup_unreferenced");
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002365 {
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 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002401 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002402 }
2403
Hasini Gunasingheda895552021-01-27 19:34:37 +00002404 /// 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.
2408 pub fn unbind_keys_for_user(
2409 &mut self,
2410 user_id: u32,
2411 keep_non_super_encrypted_keys: bool,
2412 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002413 let _wp = wd::watch("KeystoreDB::unbind_keys_for_user");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002414
David Drysdale7b9ca232024-05-23 18:19:46 +01002415 self.with_transaction(Immediate("TX_unbind_keys_for_user"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00002416 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 = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002427 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,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002446 KeyLifeCycle::Live
2447 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002448 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002449
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 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002456 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002457
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)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002464 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002465 {
2466 if blob_metadata.encrypted_by().is_none() {
2467 continue;
2468 }
2469 }
2470 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002471 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002472 .context("In unbind_keys_for_user.")?
2473 || notify_gc;
2474 }
2475 Ok(()).do_gc(notify_gc)
2476 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002477 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002478 }
2479
Eric Biggersb0478cf2023-10-27 03:55:29 +00002480 /// 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.
2489 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002490 let _wp = wd::watch("KeystoreDB::unbind_auth_bound_keys_for_user");
Eric Biggersb0478cf2023-10-27 03:55:29 +00002491
David Drysdale7b9ca232024-05-23 18:19:46 +01002492 self.with_transaction(Immediate("TX_unbind_auth_bound_keys_for_user"), |tx| {
Eric Biggersb0478cf2023-10-27 03:55:29 +00002493 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
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002544 fn load_key_components(
2545 tx: &Transaction,
2546 load_bits: KeyEntryLoadBits,
2547 key_id: i64,
2548 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002549 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002550
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002551 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002552 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002553
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002554 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002555 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002556
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002557 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002558 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002559
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002560 Ok(KeyEntry {
2561 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002562 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002563 cert: cert_blob,
2564 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002565 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002566 parameters,
2567 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002568 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002569 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002570 }
2571
Eran Messeri24f31972023-01-25 17:00:33 +00002572 /// 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.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002575 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002576 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002577 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002578 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002579 &mut self,
2580 domain: Domain,
2581 namespace: i64,
2582 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002583 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002584 ) -> Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002585 let _wp = wd::watch("KeystoreDB::list_past_alias");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002586
Eran Messeri24f31972023-01-25 17:00:33 +00002587 let query = format!(
2588 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002589 WHERE domain = ?
2590 AND namespace = ?
2591 AND alias IS NOT NULL
2592 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002593 AND key_type = ?
2594 {}
2595 ORDER BY alias ASC;",
2596 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2597 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002598
Eran Messeri24f31972023-01-25 17:00:33 +00002599 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 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002616
Janis Danisevskis66784c42021-01-27 08:40:25 -08002617 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 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002627 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002628 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002629 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002630 }
2631
Eran Messeri24f31972023-01-25 17:00:33 +00002632 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2633 /// Domain must be APP or SELINUX, the caller must make sure of that.
2634 pub fn count_keys(
2635 &mut self,
2636 domain: Domain,
2637 namespace: i64,
2638 key_type: KeyType,
2639 ) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01002640 let _wp = wd::watch("KeystoreDB::countKeys");
Eran Messeri24f31972023-01-25 17:00:33 +00002641
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
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002659 /// 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.
2665 pub fn grant(
2666 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002667 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002668 caller_uid: u32,
2669 grantee_uid: u32,
2670 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002671 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002672 ) -> Result<KeyDescriptor> {
David Drysdale541846b2024-05-23 13:16:07 +01002673 let _wp = wd::watch("KeystoreDB::grant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002674
David Drysdale7b9ca232024-05-23 18:19:46 +01002675 self.with_transaction(Immediate("TX_grant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002676 // 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, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002686 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002687
Janis Danisevskis66784c42021-01-27 08:40:25 -08002688 // 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)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002694 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002695
Janis Danisevskis66784c42021-01-27 08:40:25 -08002696 let grant_id = if let Some(grant_id) = tx
2697 .query_row(
2698 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002699 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002700 params![key_id, grantee_uid],
2701 |row| row.get(0),
2702 )
2703 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002704 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002705 {
2706 tx.execute(
2707 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002708 SET access_vector = ?
2709 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002710 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002711 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002712 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002713 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 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002722 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002723 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002724
Janis Danisevskis66784c42021-01-27 08:40:25 -08002725 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002726 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002727 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002728 }
2729
2730 /// This function checks permissions like `grant` and `load_key_entry`
2731 /// before removing a grant from the grant table.
2732 pub fn ungrant(
2733 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002734 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002735 caller_uid: u32,
2736 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002737 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002738 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002739 let _wp = wd::watch("KeystoreDB::ungrant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002740
David Drysdale7b9ca232024-05-23 18:19:46 +01002741 self.with_transaction(Immediate("TX_ungrant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002742 // 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, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002745 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002746
Janis Danisevskis66784c42021-01-27 08:40:25 -08002747 // 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)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002750 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002751
Janis Danisevskis66784c42021-01-27 08:40:25 -08002752 tx.execute(
2753 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002754 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002755 params![key_id, grantee_uid],
2756 )
2757 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002758
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002759 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002760 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002761 }
2762
Joel Galenson845f74b2020-09-09 14:11:55 -07002763 // 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.
2766 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2767 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002768 let newid: i64 = match random() {
2769 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2770 i => i,
2771 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002772 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) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002782 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002783 }
2784 _ => return Ok(newid),
2785 }
2786 }
2787 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002788
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002789 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2790 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002791 self.perboot
2792 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002793 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002794
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002795 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002796 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002797 where
2798 F: Fn(&AuthTokenEntry) -> bool,
2799 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002800 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002801 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002802
2803 /// Load descriptor of a key by key id
2804 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002805 let _wp = wd::watch("KeystoreDB::load_key_descriptor");
Pavel Grafovf45034a2021-05-12 22:35:45 +01002806
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 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002824 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002825 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002826
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.
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>> {
David Drysdale541846b2024-05-23 13:16:07 +01002836 let _wp = wd::watch("KeystoreDB::get_app_uids_affected_by_sid");
Eran Messeri4dc27b52024-01-09 12:43:31 +00002837
David Drysdale7b9ca232024-05-23 18:19:46 +01002838 let ids = self.with_transaction(Immediate("TX_get_app_uids_affected_by_sid"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002839 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();
David Drysdale7b9ca232024-05-23 18:19:46 +01002867 for (key_id, app_uid) in ids {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002868 // 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) =
David Drysdale7b9ca232024-05-23 18:19:46 +01002873 self.with_transaction(Immediate("TX_get_app_uids_affects_by_sid 2"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002874 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 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002895}
2896
2897#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002898pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002899
2900 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002901 use crate::key_parameter::{
2902 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2903 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2904 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002905 use crate::key_perm_set;
2906 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002907 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002908 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002909 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2910 HardwareAuthToken::HardwareAuthToken,
2911 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002912 };
2913 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002914 Timestamp::Timestamp,
2915 };
Joel Galenson0891bc12020-07-20 10:37:03 -07002916 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002917 use std::collections::BTreeMap;
2918 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002919 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002920 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002921 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002922 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002923 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002924 #[cfg(disabled)]
2925 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002926
Seth Moore7ee79f92021-12-07 11:42:49 -08002927 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002928 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002929
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002930 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
David Drysdale7b9ca232024-05-23 18:19:46 +01002931 db.with_transaction(Immediate("TX_new_test_db"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002932 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002933 })?;
2934 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002935 }
2936
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002937 fn rebind_alias(
2938 db: &mut KeystoreDB,
2939 newid: &KeyIdGuard,
2940 alias: &str,
2941 domain: Domain,
2942 namespace: i64,
2943 ) -> Result<bool> {
David Drysdale7b9ca232024-05-23 18:19:46 +01002944 db.with_transaction(Immediate("TX_rebind_alias"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002945 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002946 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002947 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002948 }
2949
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002950 #[test]
2951 fn datetime() -> Result<()> {
2952 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002953 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002954 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;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002963 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002964 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
Joel Galenson0891bc12020-07-20 10:37:03 -07002974 // Ensure that we're using the "injected" random function, not the real one.
2975 #[test]
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 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002987
Joel Galenson26f4d012020-07-17 14:57:21 -07002988 // Test that we have the correct tables.
2989 #[test]
2990 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002991 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002992 let tables = db
2993 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002994 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002995 .query_map(params![], |row| row.get(0))?
2996 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002997 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002998 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002999 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");
Joel Galenson2aab4432020-07-22 15:27:57 -07003004 Ok(())
3005 }
3006
3007 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003008 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 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003018 db.insert_auth_token(&auth_token1);
3019 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003020 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
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003033 db.insert_auth_token(&auth_token2);
3034 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003035 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
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003052 db.insert_auth_token(&auth_token3);
3053 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003054 assert_eq!(auth_tokens_returned.len(), 2);
3055
3056 Ok(())
3057 }
3058
3059 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003060 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3061 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003062 }
3063
David Drysdale8c4c4f32023-10-31 12:14:11 +00003064 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> {
David Drysdale7b9ca232024-05-23 18:19:46 +01003071 db.with_transaction(Immediate("TX_create_key_entry"), |tx| {
David Drysdale8c4c4f32023-10-31 12:14:11 +00003072 KeystoreDB::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
3073 })
3074 }
3075
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003076 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003077 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003078 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003079 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003080
David Drysdale8c4c4f32023-10-31 12:14:11 +00003081 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003082 let entries = get_keyentry(&db)?;
3083 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003084
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003085 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003086
3087 let entries_new = get_keyentry(&db)?;
3088 assert_eq!(entries, entries_new);
3089 Ok(())
3090 }
3091
3092 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003093 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003094 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3095 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003096 }
3097
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003098 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003099
David Drysdale8c4c4f32023-10-31 12:14:11 +00003100 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)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003102
3103 let entries = get_keyentry(&db)?;
3104 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003105 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3106 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003107
3108 // Test that we must pass in a valid Domain.
3109 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003110 create_key_entry(&mut db, &Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003111 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003112 );
3113 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003114 create_key_entry(&mut db, &Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003115 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003116 );
3117 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003118 create_key_entry(&mut db, &Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003119 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003120 );
3121
3122 Ok(())
3123 }
3124
Joel Galenson33c04ad2020-08-03 11:04:38 -07003125 #[test]
3126 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003127 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)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003131 }
3132
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003133 let mut db = new_test_db()?;
David Drysdale8c4c4f32023-10-31 12:14:11 +00003134 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)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003136 let entries = get_keyentry(&db)?;
3137 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003138 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 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003146
3147 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003148 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003149 let entries = get_keyentry(&db)?;
3150 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003151 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 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003159
3160 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003161 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003162 let entries = get_keyentry(&db)?;
3163 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003164 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 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003169
3170 // Test that we must pass in a valid Domain.
3171 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003172 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003173 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003174 );
3175 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003176 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003177 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003178 );
3179 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003180 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003181 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003182 );
3183
3184 // Test that we correctly handle setting an alias for something that does not exist.
3185 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003186 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003187 "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);
Max Bires8e93d2b2021-01-14 13:17:59 -08003192 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 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003197
3198 Ok(())
3199 }
3200
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003201 #[test]
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(
Max Bires8e93d2b2021-01-14 13:17:59 -08003209 "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],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003212 )?;
3213 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003214 domain: super::Domain::APP,
3215 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003216 alias: Some("key".to_string()),
3217 blob: None,
3218 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003219 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3220 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003221
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
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003227 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003228 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003229 assert_eq!(*a, PVEC1);
3230 assert_eq!(
3231 *k,
3232 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003233 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003234 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003235 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003236 alias: Some("key".to_string()),
3237 blob: None,
3238 }
3239 );
3240 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003241 })
3242 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003243
3244 assert_eq!(
3245 app_granted_key,
3246 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003247 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003248 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003249 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003250 alias: None,
3251 blob: None,
3252 }
3253 );
3254
3255 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003256 domain: super::Domain::SELINUX,
3257 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003258 alias: Some("yek".to_string()),
3259 blob: None,
3260 };
3261
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003262 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003263 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003264 assert_eq!(*a, PVEC1);
3265 assert_eq!(
3266 *k,
3267 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003268 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003269 // namespace must be the supplied SELinux
3270 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003271 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003272 alias: Some("yek".to_string()),
3273 blob: None,
3274 }
3275 );
3276 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003277 })
3278 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003279
3280 assert_eq!(
3281 selinux_granted_key,
3282 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003283 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003284 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003285 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003286 alias: None,
3287 blob: None,
3288 }
3289 );
3290
3291 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003292 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003293 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003294 assert_eq!(*a, PVEC2);
3295 assert_eq!(
3296 *k,
3297 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003298 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003299 // namespace must be the supplied SELinux
3300 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003301 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003302 alias: Some("yek".to_string()),
3303 blob: None,
3304 }
3305 );
3306 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003307 })
3308 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003309
3310 assert_eq!(
3311 selinux_granted_key,
3312 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003313 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003314 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003315 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003316 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
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003325 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003326 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 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003329
3330 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003331 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003332 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003333 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003334 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
Janis Danisevskis66784c42021-01-27 08:40:25 -08003341 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3342 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003343
3344 Ok(())
3345 }
3346
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003347 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003348 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3349 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3350
3351 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003352 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003353 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003354 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003355 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)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003365 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003366
3367 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003368 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003369 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003370 )?;
3371 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003372 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003373 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003374 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003375 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003376 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003377 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003378 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003379 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003380 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003381
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003382 drop(rows);
3383 drop(stmt);
3384
3385 assert_eq!(
David Drysdale7b9ca232024-05-23 18:19:46 +01003386 db.with_transaction(Immediate("TX_test"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003387 BlobMetaData::load_from_db(id, tx).no_gc()
3388 })
3389 .expect("Should find blob metadata."),
3390 blob_metadata
3391 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003392 Ok(())
3393 }
3394
3395 static TEST_ALIAS: &str = "my super duper key";
3396
3397 #[test]
3398 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3399 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003400 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003401 .context("test_insert_and_load_full_keyentry_domain_app")?
3402 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003403 let (_key_guard, key_entry) = db
3404 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003405 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003406 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();
Qi Wub9433b52020-12-01 14:52:46 +08003417 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003418
3419 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003420 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003421 domain: Domain::APP,
3422 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003423 alias: Some(TEST_ALIAS.to_string()),
3424 blob: None,
3425 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003426 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003427 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003428 |_, _| Ok(()),
3429 )
3430 .unwrap();
3431
3432 assert_eq!(
3433 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3434 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003435 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003436 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
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003451 Ok(())
3452 }
3453
3454 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003455 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3456 let mut db = new_test_db()?;
3457
3458 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003459 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003460 domain: Domain::APP,
3461 nspace: 1,
3462 alias: Some(TEST_ALIAS.to_string()),
3463 blob: None,
3464 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003465 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003466 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003467 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003468 )
3469 .expect("Trying to insert cert.");
3470
3471 let (_key_guard, mut key_entry) = db
3472 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003473 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003474 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(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003491 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003492 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(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003506 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003507 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]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003526 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3527 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003528 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003529 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3530 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003531 let (_key_guard, key_entry) = db
3532 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003533 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003534 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();
Qi Wub9433b52020-12-01 14:52:46 +08003545 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003546
3547 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003548 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003549 domain: Domain::SELINUX,
3550 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003551 alias: Some(TEST_ALIAS.to_string()),
3552 blob: None,
3553 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003554 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003555 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003556 |_, _| Ok(()),
3557 )
3558 .unwrap();
3559
3560 assert_eq!(
3561 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3562 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003563 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003564 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
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003579 Ok(())
3580 }
3581
3582 #[test]
3583 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3584 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003585 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003586 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3587 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003588 let (_, key_entry) = db
3589 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003590 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003591 KeyType::Client,
3592 KeyEntryLoadBits::BOTH,
3593 1,
3594 |_k, _av| Ok(()),
3595 )
3596 .unwrap();
3597
Qi Wub9433b52020-12-01 14:52:46 +08003598 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003599
3600 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003601 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003602 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003603 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003604 |_, _| Ok(()),
3605 )
3606 .unwrap();
3607
3608 assert_eq!(
3609 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3610 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003611 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003612 KeyType::Client,
3613 KeyEntryLoadBits::NONE,
3614 1,
3615 |_k, _av| Ok(()),
3616 )
3617 .unwrap_err()
3618 .root_cause()
3619 .downcast_ref::<KsError>()
3620 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003621
3622 Ok(())
3623 }
3624
3625 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003626 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(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003635 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003636 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]
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]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003674 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3675 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003676 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003677 .context("test_insert_and_load_full_keyentry_from_grant")?
3678 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003679
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003680 let granted_key = db
3681 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003682 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003683 domain: Domain::APP,
3684 nspace: 0,
3685 alias: Some(TEST_ALIAS.to_string()),
3686 blob: None,
3687 },
3688 1,
3689 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003690 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003691 |_k, _av| Ok(()),
3692 )
3693 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003694
3695 debug_dump_grant_table(&mut db)?;
3696
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003697 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003698 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3699 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003700 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003701 Ok(())
3702 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003703 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003704
Qi Wub9433b52020-12-01 14:52:46 +08003705 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003706
Janis Danisevskis66784c42021-01-27 08:40:25 -08003707 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003708
3709 assert_eq!(
3710 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3711 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003712 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003713 KeyType::Client,
3714 KeyEntryLoadBits::NONE,
3715 2,
3716 |_k, _av| Ok(()),
3717 )
3718 .unwrap_err()
3719 .root_cause()
3720 .downcast_ref::<KsError>()
3721 );
3722
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003723 Ok(())
3724 }
3725
Janis Danisevskis45760022021-01-19 16:34:10 -08003726 // 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]
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(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003739 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003740 domain: Domain::APP,
3741 nspace: 0,
3742 alias: Some(TEST_ALIAS.to_string()),
3743 blob: None,
3744 },
3745 OWNER_UID,
3746 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003747 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003748 |_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(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003759 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003760 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);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003766 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003767 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(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003776 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003777 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
Janis Danisevskis66784c42021-01-27 08:40:25 -08003791 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003792
3793 assert_eq!(
3794 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3795 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003796 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003797 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
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003810 // Creates a key migrates it to a different location and then tries to access it by the old
3811 // and new location.
3812 #[test]
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;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003817 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3818 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003819 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]
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;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003886 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3887 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003888 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);
Charisee03e00842023-01-25 01:41:23 +00003921 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003922 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]
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;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003954 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3955 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003956 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
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003985 #[test]
3986 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003987 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";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003990 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
David Drysdale7b9ca232024-05-23 18:19:46 +01004061 db.with_transaction(Immediate("TX_test"), |tx| KeystoreDB::from_0_to_1(tx).no_gc())
4062 .unwrap();
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004063
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
Janis Danisevskisaec14592020-11-12 09:41:49 -08004129 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4130
Janis Danisevskisaec14592020-11-12 09:41:49 -08004131 #[test]
4132 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4133 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004134 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4135 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004136 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004137 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004138 .context("test_insert_and_load_full_keyentry_domain_app")?
4139 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004140 let (_key_guard, key_entry) = db
4141 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004142 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004143 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();
Qi Wub9433b52020-12-01 14:52:46 +08004154 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004155 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 || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004166 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004167 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004168 assert!(db
4169 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004170 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004171 domain: Domain::APP,
4172 nspace: 0,
4173 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4174 blob: None,
4175 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004176 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004177 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
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004205 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004206 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004207 let temp_dir =
4208 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4209
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004210 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.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004212
4213 let _tx1 = db1
4214 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004215 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004216 .expect("Failed to create first transaction.");
4217
4218 let error = db2
4219 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004220 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004221 .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]
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
Janis Danisevskis66784c42021-01-27 08:40:25 -08004247 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004248 let mut db =
4249 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004250 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 || {
Seth Moore444b51a2021-06-11 09:49:49 -07004267 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4268 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004269
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 || {
Seth Moore444b51a2021-06-11 09:49:49 -07004297 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4298 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004299
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
Janis Danisevskis66784c42021-01-27 08:40:25 -08004314 // 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 }
Seth Moore444b51a2021-06-11 09:49:49 -07004325 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4326 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004327
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
Janis Danisevskis66784c42021-01-27 08:40:25 -08004345 Ok(())
4346 }
4347
4348 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004349 fn list() -> Result<()> {
4350 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004351 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004352 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)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004379 let entry =
4380 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004381 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();
Eran Messeri24f31972023-01-25 17:00:33 +00004403 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004404 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
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004411 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004412 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004413 KeyType::Client,
4414 KeyEntryLoadBits::NONE,
4415 *namespace as u32,
4416 |_, _| Ok(()),
4417 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004418 .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 }
Eran Messeri24f31972023-01-25 17:00:33 +00004433 assert_eq!(
4434 Vec::<KeyDescriptor>::new(),
4435 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4436 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004437
4438 Ok(())
4439 }
4440
Joel Galenson0891bc12020-07-20 10:37:03 -07004441 // Helpers
4442
4443 // Checks that the given result is an error containing the given string.
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
Joel Galenson2aab4432020-07-22 15:27:57 -07004457 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004458 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004459 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004460 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004461 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004462 namespace: Option<i64>,
4463 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004464 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004465 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004466 }
4467
4468 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4469 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004470 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004471 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004472 Ok(KeyEntryRow {
4473 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004474 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004475 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004476 namespace: row.get(3)?,
4477 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004478 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004479 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004480 })
4481 })?
4482 .map(|r| r.context("Could not read keyentry row."))
4483 .collect::<Result<Vec<_>>>()
4484 }
4485
Eran Messeri4dc27b52024-01-09 12:43:31 +00004486 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4487 make_test_params_with_sids(max_usage_count, &[42])
4488 }
4489
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004490 // 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.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004493 fn make_test_params_with_sids(
4494 max_usage_count: Option<i32>,
4495 user_secure_ids: &[i64],
4496 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004497 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004498 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),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004595 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(
Eran Messeri637259c2022-10-31 12:23:36 +00004672 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4673 SecurityLevel::TRUSTED_ENVIRONMENT,
4674 ),
4675 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004676 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 ),
Qi Wub9433b52020-12-01 14:52:46 +08004715 ];
4716 if let Some(value) = max_usage_count {
4717 params.push(KeyParameter::new(
4718 KeyParameterValue::UsageCountLimit(value),
4719 SecurityLevel::SOFTWARE,
4720 ));
4721 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004722
4723 for sid in user_secure_ids.iter() {
4724 params.push(KeyParameter::new(
4725 KeyParameterValue::UserSecureID(*sid),
4726 SecurityLevel::STRONGBOX,
4727 ));
4728 }
Qi Wub9433b52020-12-01 14:52:46 +08004729 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004730 }
4731
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004732 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004733 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004734 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004735 namespace: i64,
4736 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004737 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004738 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004739 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4740 }
4741
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> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004750 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004751 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)?;
Qi Wub9433b52020-12-01 14:52:46 +08004766
Eran Messeri4dc27b52024-01-09 12:43:31 +00004767 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004768 db.insert_keyparameter(&key_id, &params)?;
4769
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004770 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004771 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004772 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004773 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004774 Ok(key_id)
4775 }
4776
Qi Wub9433b52020-12-01 14:52:46 +08004777 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
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004780 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
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004787 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004788 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004789
4790 KeyEntry {
4791 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004792 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004793 cert: Some(TEST_CERT_BLOB.to_vec()),
4794 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004795 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004796 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004797 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004798 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004799 }
4800 }
4801
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004802 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004803 db: &mut KeystoreDB,
4804 domain: Domain,
4805 namespace: i64,
4806 alias: &str,
4807 logical_only: bool,
4808 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004809 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004810 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
Eric Biggersb0478cf2023-10-27 03:55:29 +00004837 // 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.
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;
David Drysdale8c4c4f32023-10-31 12:14:11 +00004849 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Eric Biggersb0478cf2023-10-27 03:55:29 +00004850
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
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004884 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
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004909 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004910 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004911 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004912 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004913 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004914 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004915 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004916 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 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004925 },
4926 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004927
4928 println!("Key entry table rows:");
4929 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004930 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004931 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004932 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4933 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004934 );
4935 }
4936 Ok(())
4937 }
4938
4939 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004940 let mut stmt = db
4941 .conn
4942 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004943 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004944 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
Joel Galenson0891bc12020-07-20 10:37:03 -07004955 // Use a custom random number generator that repeats each number once.
4956 // This allows us to test repeated elements.
4957
4958 thread_local! {
Charisee43391152024-04-02 16:16:30 +00004959 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07004960 }
4961
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004962 fn reset_random() {
4963 RANDOM_COUNTER.with(|counter| {
4964 *counter.borrow_mut() = 0;
4965 })
4966 }
4967
Joel Galenson0891bc12020-07-20 10:37:03 -07004968 pub fn random() -> i64 {
4969 RANDOM_COUNTER.with(|counter| {
4970 let result = *counter.borrow() / 2;
4971 *counter.borrow_mut() += 1;
4972 result
4973 })
4974 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004975
4976 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00004977 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
Eran Messeri24f31972023-01-25 17:00:33 +00004985 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());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004987
4988 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004989 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004990
4991 Ok(())
4992 }
4993
4994 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004995 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,
Eric Biggers6745f532023-10-27 03:55:28 +00005005 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005006 };
5007
5008 let key_name_nonenc = SuperKeyType {
5009 alias: "test_super_key_2",
5010 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005011 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005012 };
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
Eric Biggersb0478cf2023-10-27 03:55:29 +00005070 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]
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
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005135 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005136 fn test_store_super_key() -> Result<()> {
5137 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005138 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005139 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005140 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005141 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005142 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005143
5144 let (encrypted_super_key, metadata) =
5145 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005146 db.store_super_key(
5147 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005148 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005149 &encrypted_super_key,
5150 &metadata,
5151 &KeyMetaData::new(),
5152 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005153
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005154 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005155 assert!(db.key_exists(
5156 Domain::APP,
5157 1,
5158 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5159 KeyType::Super
5160 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005161
Eric Biggers673d34a2023-10-18 01:54:18 +00005162 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005163 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005164 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005165 key_entry,
5166 &pw,
5167 None,
5168 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005169
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005170 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005171 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005172
Hasini Gunasingheda895552021-01-27 19:34:37 +00005173 Ok(())
5174 }
Seth Moore78c091f2021-04-09 21:38:30 +00005175
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005176 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005177 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005178 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,
Seth Moore78c091f2021-04-09 21:38:30 +00005191 ]
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]
5197 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005198 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005199
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)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005204 // AuthToken can be less than a page since it's in a btree, not sqlite
5205 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005206 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005207 } else {
5208 assert!(stat.size >= PAGE_SIZE);
5209 }
Seth Moore78c091f2021-04-09 21:38:30 +00005210 assert!(stat.size >= stat.unused_size);
5211 }
5212
5213 Ok(())
5214 }
5215
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005216 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005217 get_valid_statsd_storage_types()
5218 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005219 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005220 .collect()
5221 }
5222
5223 fn assert_storage_increased(
5224 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005225 increased_storage_types: Vec<MetricsStorage>,
5226 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005227 ) {
5228 for storage in increased_storage_types {
5229 // Verify the expected storage increased.
5230 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005231 let old = &baseline[&storage.0];
5232 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005233 assert!(
5234 new.unused_size <= old.unused_size,
5235 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005236 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005237 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.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005243 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005244 }
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() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005251 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005252 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),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005265 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005266 );
5267 }
5268 }
5269
5270 #[test]
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
David Drysdale8c4c4f32023-10-31 12:14:11 +00005275 let key_id = create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005276 assert_storage_increased(
5277 &mut db,
5278 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005279 MetricsStorage::KEY_ENTRY,
5280 MetricsStorage::KEY_ENTRY_ID_INDEX,
5281 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005282 ],
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![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005292 MetricsStorage::BLOB_ENTRY,
5293 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5294 MetricsStorage::BLOB_METADATA,
5295 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005296 ],
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,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005304 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005305 &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,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005313 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005314 &mut working_stats,
5315 );
5316
5317 let mut sum = 0;
5318 for stat in working_stats.values() {
5319 sum += stat.size;
5320 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005321 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005322 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5323
5324 Ok(())
5325 }
5326
5327 #[test]
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(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005338 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005339 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005340 Ok(())
5341 }
5342
5343 #[test]
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,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005359 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005360 |_, _| Ok(()),
5361 )?;
5362
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005363 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005364
5365 Ok(())
5366 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005367
5368 #[test]
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
Eric Biggersb5613da2024-03-13 19:31:42 +00005400 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005401 Ok(())
5402 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005403
5404 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005405 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 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005419
5420 #[test]
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]
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 }
David Drysdale115c4722024-04-15 14:11:52 +01005526
5527 #[test]
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
David Drysdale7b9ca232024-05-23 18:19:46 +01005559 let _result =
5560 db.with_transaction_timeout(Immediate("TX_test"), Duration::from_secs(3), |_tx| {
David Drysdale115c4722024-04-15 14:11:52 +01005561 // 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()
David Drysdale7b9ca232024-05-23 18:19:46 +01005569 });
David Drysdale115c4722024-04-15 14:11:52 +01005570 });
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
David Drysdale7b9ca232024-05-23 18:19:46 +01005588 let result =
5589 db.with_transaction_timeout(Immediate("TX_test"), Duration::from_secs(3), |_tx| {
5590 Ok(()).no_gc()
5591 });
David Drysdale115c4722024-04-15 14:11:52 +01005592 // 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 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005603}