blob: dd64764b30270742d3921f80334ae7af531b46bb [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},
Andrew Walbran78abb1e2023-05-30 16:20:56 +000085 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior,
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
Joel Galenson0891bc12020-07-20 10:37:03 -070095#[cfg(test)]
96use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070097
Janis Danisevskisb42fc182020-12-15 08:41:27 -080098impl_metadata!(
99 /// A set of metadata for key entries.
100 #[derive(Debug, Default, Eq, PartialEq)]
101 pub struct KeyMetaData;
102 /// A metadata entry for key entries.
103 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
104 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800105 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800106 CreationDate(DateTime) with accessor creation_date,
107 /// Expiration date for attestation keys.
108 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700109 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
110 /// provisioning
111 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
112 /// Vector representing the raw public key so results from the server can be matched
113 /// to the right entry
114 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700115 /// SEC1 public key for ECDH encryption
116 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800117 // --- ADD NEW META DATA FIELDS HERE ---
118 // For backwards compatibility add new entries only to
119 // end of this list and above this comment.
120 };
121);
122
123impl KeyMetaData {
124 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
125 let mut stmt = tx
126 .prepare(
127 "SELECT tag, data from persistent.keymetadata
128 WHERE keyentryid = ?;",
129 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000130 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800131
132 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
133
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000134 let mut rows = stmt
135 .query(params![key_id])
136 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 db_utils::with_rows_extract_all(&mut rows, |row| {
138 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
139 metadata.insert(
140 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700141 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142 .context("Failed to read KeyMetaEntry.")?,
143 );
144 Ok(())
145 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000146 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800147
148 Ok(Self { data: metadata })
149 }
150
151 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
152 let mut stmt = tx
153 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000154 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800155 VALUES (?, ?, ?);",
156 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000157 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158
159 let iter = self.data.iter();
160 for (tag, entry) in iter {
161 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000162 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800163 })?;
164 }
165 Ok(())
166 }
167}
168
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800169impl_metadata!(
170 /// A set of metadata for key blobs.
171 #[derive(Debug, Default, Eq, PartialEq)]
172 pub struct BlobMetaData;
173 /// A metadata entry for key blobs.
174 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
175 pub enum BlobMetaEntry {
176 /// If present, indicates that the blob is encrypted with another key or a key derived
177 /// from a password.
178 EncryptedBy(EncryptedBy) with accessor encrypted_by,
179 /// If the blob is password encrypted this field is set to the
180 /// salt used for the key derivation.
181 Salt(Vec<u8>) with accessor salt,
182 /// If the blob is encrypted, this field is set to the initialization vector.
183 Iv(Vec<u8>) with accessor iv,
184 /// If the blob is encrypted, this field holds the AEAD TAG.
185 AeadTag(Vec<u8>) with accessor aead_tag,
186 /// The uuid of the owning KeyMint instance.
187 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700188 /// If the key is ECDH encrypted, this is the ephemeral public key
189 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000190 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
191 /// of that key
192 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800193 // --- ADD NEW META DATA FIELDS HERE ---
194 // For backwards compatibility add new entries only to
195 // end of this list and above this comment.
196 };
197);
198
199impl BlobMetaData {
200 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
201 let mut stmt = tx
202 .prepare(
203 "SELECT tag, data from persistent.blobmetadata
204 WHERE blobentryid = ?;",
205 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000206 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800207
208 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
209
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000210 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800211 db_utils::with_rows_extract_all(&mut rows, |row| {
212 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
213 metadata.insert(
214 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700215 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800216 .context("Failed to read BlobMetaEntry.")?,
217 );
218 Ok(())
219 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000220 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221
222 Ok(Self { data: metadata })
223 }
224
225 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
226 let mut stmt = tx
227 .prepare(
228 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
229 VALUES (?, ?, ?);",
230 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000231 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800232
233 let iter = self.data.iter();
234 for (tag, entry) in iter {
235 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000236 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800237 })?;
238 }
239 Ok(())
240 }
241}
242
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800243/// Indicates the type of the keyentry.
244#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
245pub enum KeyType {
246 /// This is a client key type. These keys are created or imported through the Keystore 2.0
247 /// AIDL interface android.system.keystore2.
248 Client,
249 /// This is a super key type. These keys are created by keystore itself and used to encrypt
250 /// other key blobs to provide LSKF binding.
251 Super,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800252}
253
254impl ToSql for KeyType {
255 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
256 Ok(ToSqlOutput::Owned(Value::Integer(match self {
257 KeyType::Client => 0,
258 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800259 })))
260 }
261}
262
263impl FromSql for KeyType {
264 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
265 match i64::column_result(value)? {
266 0 => Ok(KeyType::Client),
267 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800268 v => Err(FromSqlError::OutOfRange(v)),
269 }
270 }
271}
272
Max Bires8e93d2b2021-01-14 13:17:59 -0800273/// Uuid representation that can be stored in the database.
274/// Right now it can only be initialized from SecurityLevel.
275/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
276#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
277pub struct Uuid([u8; 16]);
278
279impl Deref for Uuid {
280 type Target = [u8; 16];
281
282 fn deref(&self) -> &Self::Target {
283 &self.0
284 }
285}
286
287impl From<SecurityLevel> for Uuid {
288 fn from(sec_level: SecurityLevel) -> Self {
289 Self((sec_level.0 as u128).to_be_bytes())
290 }
291}
292
293impl ToSql for Uuid {
294 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
295 self.0.to_sql()
296 }
297}
298
299impl FromSql for Uuid {
300 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
301 let blob = Vec::<u8>::column_result(value)?;
302 if blob.len() != 16 {
303 return Err(FromSqlError::OutOfRange(blob.len() as i64));
304 }
305 let mut arr = [0u8; 16];
306 arr.copy_from_slice(&blob);
307 Ok(Self(arr))
308 }
309}
310
311/// Key entries that are not associated with any KeyMint instance, such as pure certificate
312/// entries are associated with this UUID.
313pub static KEYSTORE_UUID: Uuid = Uuid([
314 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
315]);
316
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800317/// Indicates how the sensitive part of this key blob is encrypted.
318#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
319pub enum EncryptedBy {
320 /// The keyblob is encrypted by a user password.
321 /// In the database this variant is represented as NULL.
322 Password,
323 /// The keyblob is encrypted by another key with wrapped key id.
324 /// In the database this variant is represented as non NULL value
325 /// that is convertible to i64, typically NUMERIC.
326 KeyId(i64),
327}
328
329impl ToSql for EncryptedBy {
330 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
331 match self {
332 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
333 Self::KeyId(id) => id.to_sql(),
334 }
335 }
336}
337
338impl FromSql for EncryptedBy {
339 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
340 match value {
341 ValueRef::Null => Ok(Self::Password),
342 _ => Ok(Self::KeyId(i64::column_result(value)?)),
343 }
344 }
345}
346
347/// A database representation of wall clock time. DateTime stores unix epoch time as
348/// i64 in milliseconds.
349#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
350pub struct DateTime(i64);
351
352/// Error type returned when creating DateTime or converting it from and to
353/// SystemTime.
354#[derive(thiserror::Error, Debug)]
355pub enum DateTimeError {
356 /// This is returned when SystemTime and Duration computations fail.
357 #[error(transparent)]
358 SystemTimeError(#[from] SystemTimeError),
359
360 /// This is returned when type conversions fail.
361 #[error(transparent)]
362 TypeConversion(#[from] std::num::TryFromIntError),
363
364 /// This is returned when checked time arithmetic failed.
365 #[error("Time arithmetic failed.")]
366 TimeArithmetic,
367}
368
369impl DateTime {
370 /// Constructs a new DateTime object denoting the current time. This may fail during
371 /// conversion to unix epoch time and during conversion to the internal i64 representation.
372 pub fn now() -> Result<Self, DateTimeError> {
373 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
374 }
375
376 /// Constructs a new DateTime object from milliseconds.
377 pub fn from_millis_epoch(millis: i64) -> Self {
378 Self(millis)
379 }
380
381 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700382 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800383 self.0
384 }
385
386 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700387 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800388 self.0 / 1000
389 }
390}
391
392impl ToSql for DateTime {
393 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
394 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
395 }
396}
397
398impl FromSql for DateTime {
399 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
400 Ok(Self(i64::column_result(value)?))
401 }
402}
403
404impl TryInto<SystemTime> for DateTime {
405 type Error = DateTimeError;
406
407 fn try_into(self) -> Result<SystemTime, Self::Error> {
408 // We want to construct a SystemTime representation equivalent to self, denoting
409 // a point in time THEN, but we cannot set the time directly. We can only construct
410 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
411 // and between EPOCH and THEN. With this common reference we can construct the
412 // duration between NOW and THEN which we can add to our SystemTime representation
413 // of NOW to get a SystemTime representation of THEN.
414 // Durations can only be positive, thus the if statement below.
415 let now = SystemTime::now();
416 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
417 let then_epoch = Duration::from_millis(self.0.try_into()?);
418 Ok(if now_epoch > then_epoch {
419 // then = now - (now_epoch - then_epoch)
420 now_epoch
421 .checked_sub(then_epoch)
422 .and_then(|d| now.checked_sub(d))
423 .ok_or(DateTimeError::TimeArithmetic)?
424 } else {
425 // then = now + (then_epoch - now_epoch)
426 then_epoch
427 .checked_sub(now_epoch)
428 .and_then(|d| now.checked_add(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 })
431 }
432}
433
434impl TryFrom<SystemTime> for DateTime {
435 type Error = DateTimeError;
436
437 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
438 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
439 }
440}
441
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800442#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
443enum KeyLifeCycle {
444 /// Existing keys have a key ID but are not fully populated yet.
445 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
446 /// them to Unreferenced for garbage collection.
447 Existing,
448 /// A live key is fully populated and usable by clients.
449 Live,
450 /// An unreferenced key is scheduled for garbage collection.
451 Unreferenced,
452}
453
454impl ToSql for KeyLifeCycle {
455 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
456 match self {
457 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
458 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
459 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
460 }
461 }
462}
463
464impl FromSql for KeyLifeCycle {
465 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
466 match i64::column_result(value)? {
467 0 => Ok(KeyLifeCycle::Existing),
468 1 => Ok(KeyLifeCycle::Live),
469 2 => Ok(KeyLifeCycle::Unreferenced),
470 v => Err(FromSqlError::OutOfRange(v)),
471 }
472 }
473}
474
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700475/// Keys have a KeyMint blob component and optional public certificate and
476/// certificate chain components.
477/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
478/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800479#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700480pub struct KeyEntryLoadBits(u32);
481
482impl KeyEntryLoadBits {
483 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
484 pub const NONE: KeyEntryLoadBits = Self(0);
485 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
486 pub const KM: KeyEntryLoadBits = Self(1);
487 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
488 pub const PUBLIC: KeyEntryLoadBits = Self(2);
489 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
490 pub const BOTH: KeyEntryLoadBits = Self(3);
491
492 /// Returns true if this object indicates that the public components shall be loaded.
493 pub const fn load_public(&self) -> bool {
494 self.0 & Self::PUBLIC.0 != 0
495 }
496
497 /// Returns true if the object indicates that the KeyMint component shall be loaded.
498 pub const fn load_km(&self) -> bool {
499 self.0 & Self::KM.0 != 0
500 }
501}
502
Janis Danisevskisaec14592020-11-12 09:41:49 -0800503lazy_static! {
504 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
505}
506
507struct KeyIdLockDb {
508 locked_keys: Mutex<HashSet<i64>>,
509 cond_var: Condvar,
510}
511
512/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
513/// from the database a second time. Most functions manipulating the key blob database
514/// require a KeyIdGuard.
515#[derive(Debug)]
516pub struct KeyIdGuard(i64);
517
518impl KeyIdLockDb {
519 fn new() -> Self {
520 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
521 }
522
523 /// This function blocks until an exclusive lock for the given key entry id can
524 /// be acquired. It returns a guard object, that represents the lifecycle of the
525 /// acquired lock.
526 pub fn get(&self, key_id: i64) -> KeyIdGuard {
527 let mut locked_keys = self.locked_keys.lock().unwrap();
528 while locked_keys.contains(&key_id) {
529 locked_keys = self.cond_var.wait(locked_keys).unwrap();
530 }
531 locked_keys.insert(key_id);
532 KeyIdGuard(key_id)
533 }
534
535 /// This function attempts to acquire an exclusive lock on a given key id. If the
536 /// given key id is already taken the function returns None immediately. If a lock
537 /// can be acquired this function returns a guard object, that represents the
538 /// lifecycle of the acquired lock.
539 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
540 let mut locked_keys = self.locked_keys.lock().unwrap();
541 if locked_keys.insert(key_id) {
542 Some(KeyIdGuard(key_id))
543 } else {
544 None
545 }
546 }
547}
548
549impl KeyIdGuard {
550 /// Get the numeric key id of the locked key.
551 pub fn id(&self) -> i64 {
552 self.0
553 }
554}
555
556impl Drop for KeyIdGuard {
557 fn drop(&mut self) {
558 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
559 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800560 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800561 KEY_ID_LOCK.cond_var.notify_all();
562 }
563}
564
Max Bires8e93d2b2021-01-14 13:17:59 -0800565/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700566#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800567pub struct CertificateInfo {
568 cert: Option<Vec<u8>>,
569 cert_chain: Option<Vec<u8>>,
570}
571
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800572/// This type represents a Blob with its metadata and an optional superseded blob.
573#[derive(Debug)]
574pub struct BlobInfo<'a> {
575 blob: &'a [u8],
576 metadata: &'a BlobMetaData,
577 /// Superseded blobs are an artifact of legacy import. In some rare occasions
578 /// the key blob needs to be upgraded during import. In that case two
579 /// blob are imported, the superseded one will have to be imported first,
580 /// so that the garbage collector can reap it.
581 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
582}
583
584impl<'a> BlobInfo<'a> {
585 /// Create a new instance of blob info with blob and corresponding metadata
586 /// and no superseded blob info.
587 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
588 Self { blob, metadata, superseded_blob: None }
589 }
590
591 /// Create a new instance of blob info with blob and corresponding metadata
592 /// as well as superseded blob info.
593 pub fn new_with_superseded(
594 blob: &'a [u8],
595 metadata: &'a BlobMetaData,
596 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
597 ) -> Self {
598 Self { blob, metadata, superseded_blob }
599 }
600}
601
Max Bires8e93d2b2021-01-14 13:17:59 -0800602impl CertificateInfo {
603 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
604 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
605 Self { cert, cert_chain }
606 }
607
608 /// Take the cert
609 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
610 self.cert.take()
611 }
612
613 /// Take the cert chain
614 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
615 self.cert_chain.take()
616 }
617}
618
Max Bires2b2e6562020-09-22 11:22:36 -0700619/// This type represents a certificate chain with a private key corresponding to the leaf
620/// 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 -0700621pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800622 /// A KM key blob
623 pub private_key: ZVec,
624 /// A batch cert for private_key
625 pub batch_cert: Vec<u8>,
626 /// A full certificate chain from root signing authority to private_key, including batch_cert
627 /// for convenience.
628 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700629}
630
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631/// This type represents a Keystore 2.0 key entry.
632/// An entry has a unique `id` by which it can be found in the database.
633/// It has a security level field, key parameters, and three optional fields
634/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800635#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700636pub struct KeyEntry {
637 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800638 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700639 cert: Option<Vec<u8>>,
640 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800641 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700642 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800643 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800644 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700645}
646
647impl KeyEntry {
648 /// Returns the unique id of the Key entry.
649 pub fn id(&self) -> i64 {
650 self.id
651 }
652 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800653 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
654 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800656 /// Extracts the Optional KeyMint blob including its metadata.
657 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
658 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700659 }
660 /// Exposes the optional public certificate.
661 pub fn cert(&self) -> &Option<Vec<u8>> {
662 &self.cert
663 }
664 /// Extracts the optional public certificate.
665 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
666 self.cert.take()
667 }
668 /// Exposes the optional public certificate chain.
669 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
670 &self.cert_chain
671 }
672 /// Extracts the optional public certificate_chain.
673 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
674 self.cert_chain.take()
675 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800676 /// Returns the uuid of the owning KeyMint instance.
677 pub fn km_uuid(&self) -> &Uuid {
678 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700679 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700680 /// Exposes the key parameters of this key entry.
681 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
682 &self.parameters
683 }
684 /// Consumes this key entry and extracts the keyparameters from it.
685 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
686 self.parameters
687 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800688 /// Exposes the key metadata of this key entry.
689 pub fn metadata(&self) -> &KeyMetaData {
690 &self.metadata
691 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800692 /// This returns true if the entry is a pure certificate entry with no
693 /// private key component.
694 pub fn pure_cert(&self) -> bool {
695 self.pure_cert
696 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000697 /// Consumes this key entry and extracts the keyparameters and metadata from it.
698 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
699 (self.parameters, self.metadata)
700 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700701}
702
703/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800704#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700705pub struct SubComponentType(u32);
706impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800707 /// Persistent identifier for a key blob.
708 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700709 /// Persistent identifier for a certificate blob.
710 pub const CERT: SubComponentType = Self(1);
711 /// Persistent identifier for a certificate chain blob.
712 pub const CERT_CHAIN: SubComponentType = Self(2);
713}
714
715impl ToSql for SubComponentType {
716 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
717 self.0.to_sql()
718 }
719}
720
721impl FromSql for SubComponentType {
722 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
723 Ok(Self(u32::column_result(value)?))
724 }
725}
726
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800727/// This trait is private to the database module. It is used to convey whether or not the garbage
728/// collector shall be invoked after a database access. All closures passed to
729/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
730/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
731/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
732/// `.need_gc()`.
733trait DoGc<T> {
734 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
735
736 fn no_gc(self) -> Result<(bool, T)>;
737
738 fn need_gc(self) -> Result<(bool, T)>;
739}
740
741impl<T> DoGc<T> for Result<T> {
742 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
743 self.map(|r| (need_gc, r))
744 }
745
746 fn no_gc(self) -> Result<(bool, T)> {
747 self.do_gc(false)
748 }
749
750 fn need_gc(self) -> Result<(bool, T)> {
751 self.do_gc(true)
752 }
753}
754
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700755/// KeystoreDB wraps a connection to an SQLite database and tracks its
756/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700757pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700758 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700759 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700760 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700761}
762
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000763/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000764/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000765#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000766pub struct BootTime(i64);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000767
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000768impl BootTime {
769 /// Constructs a new BootTime
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000770 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000771 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000772 }
773
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000774 /// Returns the value of BootTime in milliseconds as i64
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000775 pub fn milliseconds(&self) -> i64 {
776 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000777 }
778
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000779 /// Returns the integer value of BootTime as i64
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000780 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000781 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000782 }
783
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800784 /// Like i64::checked_sub.
785 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
786 self.0.checked_sub(other.0).map(Self)
787 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788}
789
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000790impl ToSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000791 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
792 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
793 }
794}
795
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000796impl FromSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000797 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
798 Ok(Self(i64::column_result(value)?))
799 }
800}
801
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000802/// This struct encapsulates the information to be stored in the database about the auth tokens
803/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700804#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000805pub struct AuthTokenEntry {
806 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000807 // Time received in milliseconds
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000808 time_received: BootTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000809}
810
811impl AuthTokenEntry {
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000812 fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000813 AuthTokenEntry { auth_token, time_received }
814 }
815
816 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800817 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800819 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000820 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000821 })
822 }
823
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000824 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800825 pub fn auth_token(&self) -> &HardwareAuthToken {
826 &self.auth_token
827 }
828
829 /// Returns the auth token wrapped by the AuthTokenEntry
830 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000831 self.auth_token
832 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800833
834 /// Returns the time that this auth token was received.
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000835 pub fn time_received(&self) -> BootTime {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800836 self.time_received
837 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000838
839 /// Returns the challenge value of the auth token.
840 pub fn challenge(&self) -> i64 {
841 self.auth_token.challenge
842 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000843}
844
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800845/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
846/// This object does not allow access to the database connection. But it keeps a database
847/// connection alive in order to keep the in memory per boot database alive.
Charisee95ea3ce2024-03-27 23:45:23 +0000848#[allow(dead_code)]
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800849pub struct PerBootDbKeepAlive(Connection);
850
Joel Galenson26f4d012020-07-17 14:57:21 -0700851impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800852 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700853 const CURRENT_DB_VERSION: u32 = 1;
854 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800855
Seth Moore78c091f2021-04-09 21:38:30 +0000856 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700857 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000858
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700859 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800860 /// files persistent.sqlite and perboot.sqlite in the given directory.
861 /// It also attempts to initialize all of the tables.
862 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700863 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700864 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700865 let _wp = wd::watch_millis("KeystoreDB::new", 500);
866
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700867 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700868 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800869
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700870 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800871 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700872 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000873 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800874 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800875 })?;
876 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700877 }
878
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700879 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
880 // cryptographic binding to the boot level keys was implemented.
881 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
882 tx.execute(
883 "UPDATE persistent.keyentry SET state = ?
884 WHERE
885 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
886 AND
887 id NOT IN (
888 SELECT keyentryid FROM persistent.blobentry
889 WHERE id IN (
890 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
891 )
892 );",
893 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
894 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000895 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700896 Ok(1)
897 }
898
Janis Danisevskis66784c42021-01-27 08:40:25 -0800899 fn init_tables(tx: &Transaction) -> Result<()> {
900 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700901 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700902 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800903 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700904 domain INTEGER,
905 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800906 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800907 state INTEGER,
908 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000909 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700910 )
911 .context("Failed to initialize \"keyentry\" table.")?;
912
Janis Danisevskis66784c42021-01-27 08:40:25 -0800913 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800914 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
915 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000916 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800917 )
918 .context("Failed to create index keyentry_id_index.")?;
919
920 tx.execute(
921 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
922 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000923 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800924 )
925 .context("Failed to create index keyentry_domain_namespace_index.")?;
926
927 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700928 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
929 id INTEGER PRIMARY KEY,
930 subcomponent_type INTEGER,
931 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800932 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000933 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700934 )
935 .context("Failed to initialize \"blobentry\" table.")?;
936
Janis Danisevskis66784c42021-01-27 08:40:25 -0800937 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800938 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
939 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000940 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800941 )
942 .context("Failed to create index blobentry_keyentryid_index.")?;
943
944 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800945 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
946 id INTEGER PRIMARY KEY,
947 blobentryid INTEGER,
948 tag INTEGER,
949 data ANY,
950 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000951 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800952 )
953 .context("Failed to initialize \"blobmetadata\" table.")?;
954
955 tx.execute(
956 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
957 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000958 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800959 )
960 .context("Failed to create index blobmetadata_blobentryid_index.")?;
961
962 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700963 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000964 keyentryid INTEGER,
965 tag INTEGER,
966 data ANY,
967 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000968 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700969 )
970 .context("Failed to initialize \"keyparameter\" table.")?;
971
Janis Danisevskis66784c42021-01-27 08:40:25 -0800972 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800973 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
974 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000975 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800976 )
977 .context("Failed to create index keyparameter_keyentryid_index.")?;
978
979 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800980 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
981 keyentryid INTEGER,
982 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000983 data ANY,
984 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000985 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800986 )
987 .context("Failed to initialize \"keymetadata\" table.")?;
988
Janis Danisevskis66784c42021-01-27 08:40:25 -0800989 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800990 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
991 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000992 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800993 )
994 .context("Failed to create index keymetadata_keyentryid_index.")?;
995
996 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800997 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700998 id INTEGER UNIQUE,
999 grantee INTEGER,
1000 keyentryid INTEGER,
1001 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001002 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001003 )
1004 .context("Failed to initialize \"grant\" table.")?;
1005
Joel Galenson0891bc12020-07-20 10:37:03 -07001006 Ok(())
1007 }
1008
Seth Moore472fcbb2021-05-12 10:07:51 -07001009 fn make_persistent_path(db_root: &Path) -> Result<String> {
1010 // Build the path to the sqlite file.
1011 let mut persistent_path = db_root.to_path_buf();
1012 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1013
1014 // Now convert them to strings prefixed with "file:"
1015 let mut persistent_path_str = "file:".to_owned();
1016 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1017
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001018 // Connect to database in specific mode
1019 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1020 "?journal_mode=WAL".to_owned()
1021 } else {
1022 "?journal_mode=DELETE".to_owned()
1023 };
1024 persistent_path_str.push_str(&persistent_path_mode);
1025
Seth Moore472fcbb2021-05-12 10:07:51 -07001026 Ok(persistent_path_str)
1027 }
1028
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001029 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001030 let conn =
1031 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1032
Janis Danisevskis66784c42021-01-27 08:40:25 -08001033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1036 .context("Failed to attach database persistent.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
Matthew Maurer4fb19112021-05-06 15:40:44 -07001048 // Drop the cache size from default (2M) to 0.5M
1049 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1050 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001051
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001052 Ok(conn)
1053 }
1054
Seth Moore78c091f2021-04-09 21:38:30 +00001055 fn do_table_size_query(
1056 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001057 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001058 query: &str,
1059 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001060 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001061 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001062 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001063 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001064 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001065 })
1066 .no_gc()
1067 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001068 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001069 }
1070
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001071 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001072 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001073 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001074 "SELECT page_count * page_size, freelist_count * page_size
1075 FROM pragma_page_count('persistent'),
1076 pragma_page_size('persistent'),
1077 persistent.pragma_freelist_count();",
1078 &[],
1079 )
1080 }
1081
1082 fn get_table_size(
1083 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001084 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001085 schema: &str,
1086 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001087 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001088 self.do_table_size_query(
1089 storage_type,
1090 "SELECT pgsize,unused FROM dbstat(?1)
1091 WHERE name=?2 AND aggregate=TRUE;",
1092 &[schema, table],
1093 )
1094 }
1095
1096 /// Fetches a storage statisitics atom for a given storage type. For storage
1097 /// types that map to a table, information about the table's storage is
1098 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001099 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001100 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1101
Seth Moore78c091f2021-04-09 21:38:30 +00001102 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001103 MetricsStorage::DATABASE => self.get_total_size(),
1104 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001105 self.get_table_size(storage_type, "persistent", "keyentry")
1106 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001108 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1109 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001110 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001111 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "blobentry")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001120 self.get_table_size(storage_type, "persistent", "keyparameter")
1121 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001123 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1124 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001125 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001126 self.get_table_size(storage_type, "persistent", "keymetadata")
1127 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001128 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001129 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1130 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001131 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1132 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001133 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1134 // reportable
1135 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001137 storage_type,
1138 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001140 unused_size: 0,
1141 })
Seth Moore78c091f2021-04-09 21:38:30 +00001142 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001143 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001144 self.get_table_size(storage_type, "persistent", "blobmetadata")
1145 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001146 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001147 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1148 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001149 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001150 }
1151 }
1152
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1155 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001156 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1157 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001159 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 blob_ids_to_delete: &[i64],
1161 max_blobs: usize,
1162 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001163 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001164 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 // Delete the given blobs.
1166 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 tx.execute(
1168 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001170 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001171 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001173 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001174 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001175
1176 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1177
Janis Danisevskis3395f862021-05-06 10:54:17 -07001178 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1179 let result: Vec<(i64, Vec<u8>)> = {
1180 let mut stmt = tx
1181 .prepare(
1182 "SELECT id, blob FROM persistent.blobentry
1183 WHERE subcomponent_type = ?
1184 AND (
1185 id NOT IN (
1186 SELECT MAX(id) FROM persistent.blobentry
1187 WHERE subcomponent_type = ?
1188 GROUP BY keyentryid, subcomponent_type
1189 )
1190 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1191 ) LIMIT ?;",
1192 )
1193 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001194
Janis Danisevskis3395f862021-05-06 10:54:17 -07001195 let rows = stmt
1196 .query_map(
1197 params![
1198 SubComponentType::KEY_BLOB,
1199 SubComponentType::KEY_BLOB,
1200 max_blobs as i64,
1201 ],
1202 |row| Ok((row.get(0)?, row.get(1)?)),
1203 )
1204 .context("Trying to query superseded blob.")?;
1205
1206 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1207 .context("Trying to extract superseded blobs.")?
1208 };
1209
1210 let result = result
1211 .into_iter()
1212 .map(|(blob_id, blob)| {
1213 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1214 })
1215 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1216 .context("Trying to load blob metadata.")?;
1217 if !result.is_empty() {
1218 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001219 }
1220
1221 // We did not find any superseded key blob, so let's remove other superseded blob in
1222 // one transaction.
1223 tx.execute(
1224 "DELETE FROM persistent.blobentry
1225 WHERE NOT subcomponent_type = ?
1226 AND (
1227 id NOT IN (
1228 SELECT MAX(id) FROM persistent.blobentry
1229 WHERE NOT subcomponent_type = ?
1230 GROUP BY keyentryid, subcomponent_type
1231 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1232 );",
1233 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1234 )
1235 .context("Trying to purge superseded blobs.")?;
1236
Janis Danisevskis3395f862021-05-06 10:54:17 -07001237 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001238 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001239 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001240 }
1241
1242 /// This maintenance function should be called only once before the database is used for the
1243 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1244 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1245 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1246 /// Keystore crashed at some point during key generation. Callers may want to log such
1247 /// occurrences.
1248 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1249 /// it to `KeyLifeCycle::Live` may have grants.
1250 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001251 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1252
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1254 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001255 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1256 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1257 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001258 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001259 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001260 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001261 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001262 }
1263
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001264 /// Checks if a key exists with given key type and key descriptor properties.
1265 pub fn key_exists(
1266 &mut self,
1267 domain: Domain,
1268 nspace: i64,
1269 alias: &str,
1270 key_type: KeyType,
1271 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001272 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1273
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1275 let key_descriptor =
1276 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001277 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001278 match result {
1279 Ok(_) => Ok(true),
1280 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1281 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001282 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001283 },
1284 }
1285 .no_gc()
1286 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001287 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001288 }
1289
Hasini Gunasingheda895552021-01-27 19:34:37 +00001290 /// Stores a super key in the database.
1291 pub fn store_super_key(
1292 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001293 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001294 key_type: &SuperKeyType,
1295 blob: &[u8],
1296 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001297 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001299 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1300
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1302 let key_id = Self::insert_with_retry(|id| {
1303 tx.execute(
1304 "INSERT into persistent.keyentry
1305 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001306 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 params![
1308 id,
1309 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001310 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001311 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001312 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 KeyLifeCycle::Live,
1314 &KEYSTORE_UUID,
1315 ],
1316 )
1317 })
1318 .context("Failed to insert into keyentry table.")?;
1319
Paul Crowley8d5b2532021-03-19 10:53:07 -07001320 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1321
Hasini Gunasingheda895552021-01-27 19:34:37 +00001322 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001323 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001324 key_id,
1325 SubComponentType::KEY_BLOB,
1326 Some(blob),
1327 Some(blob_metadata),
1328 )
1329 .context("Failed to store key blob.")?;
1330
1331 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1332 .context("Trying to load key components.")
1333 .no_gc()
1334 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001335 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001336 }
1337
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001338 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001339 pub fn load_super_key(
1340 &mut self,
1341 key_type: &SuperKeyType,
1342 user_id: u32,
1343 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001344 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1345
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1347 let key_descriptor = KeyDescriptor {
1348 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001349 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001350 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001351 blob: None,
1352 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001353 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001354 match id {
1355 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001356 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001357 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001358 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1359 }
1360 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1361 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001362 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001363 },
1364 }
1365 .no_gc()
1366 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001367 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001368 }
1369
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370 /// Atomically loads a key entry and associated metadata or creates it using the
1371 /// callback create_new_key callback. The callback is called during a database
1372 /// transaction. This means that implementers should be mindful about using
1373 /// blocking operations such as IPC or grabbing mutexes.
1374 pub fn get_or_create_key_with<F>(
1375 &mut self,
1376 domain: Domain,
1377 namespace: i64,
1378 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001379 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380 create_new_key: F,
1381 ) -> Result<(KeyIdGuard, KeyEntry)>
1382 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001383 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001384 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001385 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1386
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1388 let id = {
1389 let mut stmt = tx
1390 .prepare(
1391 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001392 WHERE
1393 key_type = ?
1394 AND domain = ?
1395 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001396 AND alias = ?
1397 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001399 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 let mut rows = stmt
1401 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001402 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 db_utils::with_rows_extract_one(&mut rows, |row| {
1405 Ok(match row {
1406 Some(r) => r.get(0).context("Failed to unpack id.")?,
1407 None => None,
1408 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001409 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001410 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001411 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001412
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 let (id, entry) = match id {
1414 Some(id) => (
1415 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001416 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001418
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 None => {
1420 let id = Self::insert_with_retry(|id| {
1421 tx.execute(
1422 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001423 (id, key_type, domain, namespace, alias, state, km_uuid)
1424 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001425 params![
1426 id,
1427 KeyType::Super,
1428 domain.0,
1429 namespace,
1430 alias,
1431 KeyLifeCycle::Live,
1432 km_uuid,
1433 ],
1434 )
1435 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001436 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001437
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001438 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001439 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001440 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001441 id,
1442 SubComponentType::KEY_BLOB,
1443 Some(&blob),
1444 Some(&metadata),
1445 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001446 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001447 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001448 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001449 KeyEntry {
1450 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001451 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001452 pure_cert: false,
1453 ..Default::default()
1454 },
1455 )
1456 }
1457 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001458 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001459 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001460 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001461 }
1462
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001463 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1465 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001466 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1467 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001468 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001469 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001470 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001471 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001472 .conn
1473 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001474 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001475 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1476 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001477 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001478 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001479 });
1480 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001481 Ok(result) => break Ok(result),
1482 Err(e) => {
1483 if Self::is_locked_error(&e) {
1484 std::thread::sleep(std::time::Duration::from_micros(500));
1485 continue;
1486 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001487 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001488 }
1489 }
1490 }
1491 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001492 .map(|(need_gc, result)| {
1493 if need_gc {
1494 if let Some(ref gc) = self.gc {
1495 gc.notify_gc();
1496 }
1497 }
1498 result
1499 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001500 }
1501
1502 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001503 matches!(
1504 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1505 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1506 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1507 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001508 }
1509
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001510 /// Creates a new key entry and allocates a new randomized id for the new key.
1511 /// The key id gets associated with a domain and namespace but not with an alias.
1512 /// To complete key generation `rebind_alias` should be called after all of the
1513 /// key artifacts, i.e., blobs and parameters have been associated with the new
1514 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1515 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001516 pub fn create_key_entry(
1517 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001518 domain: &Domain,
1519 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001520 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001521 km_uuid: &Uuid,
1522 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001523 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1524
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001526 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001527 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001528 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001529 }
1530
1531 fn create_key_entry_internal(
1532 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001533 domain: &Domain,
1534 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001535 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001536 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001537 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001538 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001539 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001540 _ => {
1541 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001542 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001543 }
1544 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001545 Ok(KEY_ID_LOCK.get(
1546 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001547 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001548 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001549 (id, key_type, domain, namespace, alias, state, km_uuid)
1550 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001551 params![
1552 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001553 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001554 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001555 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001556 KeyLifeCycle::Existing,
1557 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001558 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001559 )
1560 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001561 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001562 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001563 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001564
Janis Danisevskis377d1002021-01-27 19:07:48 -08001565 /// Set a new blob and associates it with the given key id. Each blob
1566 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001567 /// Each key can have one of each sub component type associated. If more
1568 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001569 /// will get garbage collected.
1570 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1571 /// removed by setting blob to None.
1572 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001573 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001574 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001575 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001576 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001577 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001578 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001579 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1580
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001581 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001582 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001583 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001584 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001585 }
1586
Janis Danisevskiseed69842021-02-18 20:04:10 -08001587 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1588 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1589 /// We use this to insert key blobs into the database which can then be garbage collected
1590 /// lazily by the key garbage collector.
1591 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001592 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1593
Janis Danisevskiseed69842021-02-18 20:04:10 -08001594 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1595 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001596 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001597 Self::UNASSIGNED_KEY_ID,
1598 SubComponentType::KEY_BLOB,
1599 Some(blob),
1600 Some(blob_metadata),
1601 )
1602 .need_gc()
1603 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001604 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001605 }
1606
Janis Danisevskis377d1002021-01-27 19:07:48 -08001607 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001608 tx: &Transaction,
1609 key_id: i64,
1610 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001611 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001612 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001613 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001614 match (blob, sc_type) {
1615 (Some(blob), _) => {
1616 tx.execute(
1617 "INSERT INTO persistent.blobentry
1618 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1619 params![sc_type, key_id, blob],
1620 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001621 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001622 if let Some(blob_metadata) = blob_metadata {
1623 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001624 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001625 row.get(0)
1626 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001627 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001628 blob_metadata
1629 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001630 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001631 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001632 }
1633 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1634 tx.execute(
1635 "DELETE FROM persistent.blobentry
1636 WHERE subcomponent_type = ? AND keyentryid = ?;",
1637 params![sc_type, key_id],
1638 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001639 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001640 }
1641 (None, _) => {
1642 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001643 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001644 }
1645 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001646 Ok(())
1647 }
1648
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001649 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1650 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001651 #[cfg(test)]
1652 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001653 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001654 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001655 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001656 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001657 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001658
Janis Danisevskis66784c42021-01-27 08:40:25 -08001659 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001660 tx: &Transaction,
1661 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001662 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001663 ) -> Result<()> {
1664 let mut stmt = tx
1665 .prepare(
1666 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1667 VALUES (?, ?, ?, ?);",
1668 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001669 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001670
Janis Danisevskis66784c42021-01-27 08:40:25 -08001671 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001672 stmt.insert(params![
1673 key_id.0,
1674 p.get_tag().0,
1675 p.key_parameter_value(),
1676 p.security_level().0
1677 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001678 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001679 }
1680 Ok(())
1681 }
1682
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001683 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001684 #[cfg(test)]
1685 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001686 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001687 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001688 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001689 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001690 }
1691
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001692 /// Updates the alias column of the given key id `newid` with the given alias,
1693 /// and atomically, removes the alias, domain, and namespace from another row
1694 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001695 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1696 /// collector.
1697 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001698 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001699 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001700 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001701 domain: &Domain,
1702 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001703 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001704 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001705 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001706 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001707 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001708 return Err(KsError::sys())
1709 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001710 }
1711 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001712 let updated = tx
1713 .execute(
1714 "UPDATE persistent.keyentry
1715 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001716 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1717 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001718 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001719 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001720 let result = tx
1721 .execute(
1722 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001723 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001724 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001725 params![
1726 alias,
1727 KeyLifeCycle::Live,
1728 newid.0,
1729 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001730 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001731 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001732 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001734 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001735 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001736 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001737 return Err(KsError::sys()).context(ks_err!(
1738 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001739 result
1740 ));
1741 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001742 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001743 }
1744
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001745 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1746 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1747 pub fn migrate_key_namespace(
1748 &mut self,
1749 key_id_guard: KeyIdGuard,
1750 destination: &KeyDescriptor,
1751 caller_uid: u32,
1752 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1753 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001754 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1755
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001756 let destination = match destination.domain {
1757 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1758 Domain::SELINUX => (*destination).clone(),
1759 domain => {
1760 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1761 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1762 }
1763 };
1764
1765 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001766 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001767
1768 let alias = destination
1769 .alias
1770 .as_ref()
1771 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001772 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001773
1774 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1775 // Query the destination location. If there is a key, the migration request fails.
1776 if tx
1777 .query_row(
1778 "SELECT id FROM persistent.keyentry
1779 WHERE alias = ? AND domain = ? AND namespace = ?;",
1780 params![alias, destination.domain.0, destination.nspace],
1781 |_| Ok(()),
1782 )
1783 .optional()
1784 .context("Failed to query destination.")?
1785 .is_some()
1786 {
1787 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1788 .context("Target already exists.");
1789 }
1790
1791 let updated = tx
1792 .execute(
1793 "UPDATE persistent.keyentry
1794 SET alias = ?, domain = ?, namespace = ?
1795 WHERE id = ?;",
1796 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1797 )
1798 .context("Failed to update key entry.")?;
1799
1800 if updated != 1 {
1801 return Err(KsError::sys())
1802 .context(format!("Update succeeded, but {} rows were updated.", updated));
1803 }
1804 Ok(()).no_gc()
1805 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001806 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001807 }
1808
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001809 /// Store a new key in a single transaction.
1810 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1811 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001812 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1813 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001814 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001815 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001816 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001817 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001818 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001819 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001820 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001821 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001822 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001823 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001824 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001825 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1826
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001827 let (alias, domain, namespace) = match key {
1828 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1829 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1830 (alias, key.domain, nspace)
1831 }
1832 _ => {
1833 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001834 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001835 }
1836 };
1837 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001838 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001839 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001840 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1841
1842 // In some occasions the key blob is already upgraded during the import.
1843 // In order to make sure it gets properly deleted it is inserted into the
1844 // database here and then immediately replaced by the superseding blob.
1845 // The garbage collector will then subject the blob to deleteKey of the
1846 // KM back end to permanently invalidate the key.
1847 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1848 Self::set_blob_internal(
1849 tx,
1850 key_id.id(),
1851 SubComponentType::KEY_BLOB,
1852 Some(blob),
1853 Some(blob_metadata),
1854 )
1855 .context("Trying to insert superseded key blob.")?;
1856 true
1857 } else {
1858 false
1859 };
1860
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001861 Self::set_blob_internal(
1862 tx,
1863 key_id.id(),
1864 SubComponentType::KEY_BLOB,
1865 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001866 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001867 )
1868 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001869 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001870 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001871 .context("Trying to insert the certificate.")?;
1872 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001873 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001874 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001875 tx,
1876 key_id.id(),
1877 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001878 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001879 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001880 )
1881 .context("Trying to insert the certificate chain.")?;
1882 }
1883 Self::insert_keyparameter_internal(tx, &key_id, params)
1884 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001885 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001886 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001887 .context("Trying to rebind alias.")?
1888 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001889 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001890 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001891 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001892 }
1893
Janis Danisevskis377d1002021-01-27 19:07:48 -08001894 /// Store a new certificate
1895 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1896 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001897 pub fn store_new_certificate(
1898 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001899 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001900 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001901 cert: &[u8],
1902 km_uuid: &Uuid,
1903 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001904 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1905
Janis Danisevskis377d1002021-01-27 19:07:48 -08001906 let (alias, domain, namespace) = match key {
1907 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1908 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1909 (alias, key.domain, nspace)
1910 }
1911 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001912 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1913 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001914 }
1915 };
1916 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001917 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001918 .context("Trying to create new key entry.")?;
1919
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001920 Self::set_blob_internal(
1921 tx,
1922 key_id.id(),
1923 SubComponentType::CERT_CHAIN,
1924 Some(cert),
1925 None,
1926 )
1927 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001928
1929 let mut metadata = KeyMetaData::new();
1930 metadata.add(KeyMetaEntry::CreationDate(
1931 DateTime::now().context("Trying to make creation time.")?,
1932 ));
1933
1934 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1935
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001936 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001937 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001938 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001939 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001940 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001941 }
1942
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001943 // Helper function loading the key_id given the key descriptor
1944 // tuple comprising domain, namespace, and alias.
1945 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001946 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001947 let alias = key
1948 .alias
1949 .as_ref()
1950 .map_or_else(|| Err(KsError::sys()), Ok)
1951 .context("In load_key_entry_id: Alias must be specified.")?;
1952 let mut stmt = tx
1953 .prepare(
1954 "SELECT id FROM persistent.keyentry
1955 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001956 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001957 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001958 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001959 AND alias = ?
1960 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001961 )
1962 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1963 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001964 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001965 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001966 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001967 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001968 .get(0)
1969 .context("Failed to unpack id.")
1970 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001971 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001972 }
1973
1974 /// This helper function completes the access tuple of a key, which is required
1975 /// to perform access control. The strategy depends on the `domain` field in the
1976 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001977 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001978 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001979 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001980 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001981 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001982 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001983 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001984 /// `namespace`.
1985 /// In each case the information returned is sufficient to perform the access
1986 /// check and the key id can be used to load further key artifacts.
1987 fn load_access_tuple(
1988 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001989 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001990 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001991 caller_uid: u32,
1992 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1993 match key.domain {
1994 // Domain App or SELinux. In this case we load the key_id from
1995 // the keyentry database for further loading of key components.
1996 // We already have the full access tuple to perform access control.
1997 // The only distinction is that we use the caller_uid instead
1998 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001999 // Domain::APP.
2000 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002001 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002002 if access_key.domain == Domain::APP {
2003 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002004 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002005 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002006 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002007
2008 Ok((key_id, access_key, None))
2009 }
2010
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002011 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002012 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002013 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002014 let mut stmt = tx
2015 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002016 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002017 WHERE grantee = ? AND id = ? AND
2018 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002019 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002020 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002021 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002022 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002023 .context("Domain:Grant: query failed.")?;
2024 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002025 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002026 let r =
2027 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002028 Ok((
2029 r.get(0).context("Failed to unpack key_id.")?,
2030 r.get(1).context("Failed to unpack access_vector.")?,
2031 ))
2032 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002033 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002034 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002035 }
2036
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002037 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002038 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002039 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002040 let (domain, namespace): (Domain, i64) = {
2041 let mut stmt = tx
2042 .prepare(
2043 "SELECT domain, namespace FROM persistent.keyentry
2044 WHERE
2045 id = ?
2046 AND state = ?;",
2047 )
2048 .context("Domain::KEY_ID: prepare statement failed")?;
2049 let mut rows = stmt
2050 .query(params![key.nspace, KeyLifeCycle::Live])
2051 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002052 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002053 let r =
2054 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002055 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002056 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002057 r.get(1).context("Failed to unpack namespace.")?,
2058 ))
2059 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002060 .context("Domain::KEY_ID.")?
2061 };
2062
2063 // We may use a key by id after loading it by grant.
2064 // In this case we have to check if the caller has a grant for this particular
2065 // key. We can skip this if we already know that the caller is the owner.
2066 // But we cannot know this if domain is anything but App. E.g. in the case
2067 // of Domain::SELINUX we have to speculatively check for grants because we have to
2068 // consult the SEPolicy before we know if the caller is the owner.
2069 let access_vector: Option<KeyPermSet> =
2070 if domain != Domain::APP || namespace != caller_uid as i64 {
2071 let access_vector: Option<i32> = tx
2072 .query_row(
2073 "SELECT access_vector FROM persistent.grant
2074 WHERE grantee = ? AND keyentryid = ?;",
2075 params![caller_uid as i64, key.nspace],
2076 |row| row.get(0),
2077 )
2078 .optional()
2079 .context("Domain::KEY_ID: query grant failed.")?;
2080 access_vector.map(|p| p.into())
2081 } else {
2082 None
2083 };
2084
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002085 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002086 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002087 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002088 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002089
Janis Danisevskis45760022021-01-19 16:34:10 -08002090 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002091 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002092 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002093 }
2094 }
2095
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002096 fn load_blob_components(
2097 key_id: i64,
2098 load_bits: KeyEntryLoadBits,
2099 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002100 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002101 let mut stmt = tx
2102 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002103 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002104 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2105 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002106 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002107
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002108 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002109
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002110 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002111 let mut cert_blob: Option<Vec<u8>> = None;
2112 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002113 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002114 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002115 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002116 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002117 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002118 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2119 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002120 key_blob = Some((
2121 row.get(0).context("Failed to extract key blob id.")?,
2122 row.get(2).context("Failed to extract key blob.")?,
2123 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002124 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002126 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002128 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002129 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002130 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002131 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002132 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002133 (SubComponentType::CERT, _, _)
2134 | (SubComponentType::CERT_CHAIN, _, _)
2135 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002136 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2137 }
2138 Ok(())
2139 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002140 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002141
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002142 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2143 Ok(Some((
2144 blob,
2145 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002146 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002147 )))
2148 })?;
2149
2150 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002151 }
2152
2153 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2154 let mut stmt = tx
2155 .prepare(
2156 "SELECT tag, data, security_level from persistent.keyparameter
2157 WHERE keyentryid = ?;",
2158 )
2159 .context("In load_key_parameters: prepare statement failed.")?;
2160
2161 let mut parameters: Vec<KeyParameter> = Vec::new();
2162
2163 let mut rows =
2164 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002165 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002166 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2167 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002168 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002169 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002170 .context("Failed to read KeyParameter.")?,
2171 );
2172 Ok(())
2173 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002174 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002175
2176 Ok(parameters)
2177 }
2178
Qi Wub9433b52020-12-01 14:52:46 +08002179 /// Decrements the usage count of a limited use key. This function first checks whether the
2180 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2181 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2182 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002183 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002184 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2185
Qi Wub9433b52020-12-01 14:52:46 +08002186 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2187 let limit: Option<i32> = tx
2188 .query_row(
2189 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2190 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2191 |row| row.get(0),
2192 )
2193 .optional()
2194 .context("Trying to load usage count")?;
2195
2196 let limit = limit
2197 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2198 .context("The Key no longer exists. Key is exhausted.")?;
2199
2200 tx.execute(
2201 "UPDATE persistent.keyparameter
2202 SET data = data - 1
2203 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2204 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2205 )
2206 .context("Failed to update key usage count.")?;
2207
2208 match limit {
2209 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002210 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002211 .context("Trying to mark limited use key for deletion."),
2212 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002213 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002214 }
2215 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002216 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002217 }
2218
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002219 /// Load a key entry by the given key descriptor.
2220 /// It uses the `check_permission` callback to verify if the access is allowed
2221 /// given the key access tuple read from the database using `load_access_tuple`.
2222 /// With `load_bits` the caller may specify which blobs shall be loaded from
2223 /// the blob database.
2224 pub fn load_key_entry(
2225 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002226 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002227 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002228 load_bits: KeyEntryLoadBits,
2229 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002230 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2231 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002232 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2233
Janis Danisevskis66784c42021-01-27 08:40:25 -08002234 loop {
2235 match self.load_key_entry_internal(
2236 key,
2237 key_type,
2238 load_bits,
2239 caller_uid,
2240 &check_permission,
2241 ) {
2242 Ok(result) => break Ok(result),
2243 Err(e) => {
2244 if Self::is_locked_error(&e) {
2245 std::thread::sleep(std::time::Duration::from_micros(500));
2246 continue;
2247 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002248 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002249 }
2250 }
2251 }
2252 }
2253 }
2254
2255 fn load_key_entry_internal(
2256 &mut self,
2257 key: &KeyDescriptor,
2258 key_type: KeyType,
2259 load_bits: KeyEntryLoadBits,
2260 caller_uid: u32,
2261 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002262 ) -> Result<(KeyIdGuard, KeyEntry)> {
2263 // KEY ID LOCK 1/2
2264 // If we got a key descriptor with a key id we can get the lock right away.
2265 // Otherwise we have to defer it until we know the key id.
2266 let key_id_guard = match key.domain {
2267 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2268 _ => None,
2269 };
2270
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002271 let tx = self
2272 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002273 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002274 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002275
2276 // Load the key_id and complete the access control tuple.
2277 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002278 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002279
2280 // Perform access control. It is vital that we return here if the permission is denied.
2281 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002282 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002283
Janis Danisevskisaec14592020-11-12 09:41:49 -08002284 // KEY ID LOCK 2/2
2285 // If we did not get a key id lock by now, it was because we got a key descriptor
2286 // without a key id. At this point we got the key id, so we can try and get a lock.
2287 // However, we cannot block here, because we are in the middle of the transaction.
2288 // So first we try to get the lock non blocking. If that fails, we roll back the
2289 // transaction and block until we get the lock. After we successfully got the lock,
2290 // we start a new transaction and load the access tuple again.
2291 //
2292 // We don't need to perform access control again, because we already established
2293 // that the caller had access to the given key. But we need to make sure that the
2294 // key id still exists. So we have to load the key entry by key id this time.
2295 let (key_id_guard, tx) = match key_id_guard {
2296 None => match KEY_ID_LOCK.try_get(key_id) {
2297 None => {
2298 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002299 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002300
Janis Danisevskisaec14592020-11-12 09:41:49 -08002301 // Block until we have a key id lock.
2302 let key_id_guard = KEY_ID_LOCK.get(key_id);
2303
2304 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002305 let tx = self
2306 .conn
2307 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002308 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002309
2310 Self::load_access_tuple(
2311 &tx,
2312 // This time we have to load the key by the retrieved key id, because the
2313 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002314 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002315 domain: Domain::KEY_ID,
2316 nspace: key_id,
2317 ..Default::default()
2318 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002319 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002320 caller_uid,
2321 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002322 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002323 (key_id_guard, tx)
2324 }
2325 Some(l) => (l, tx),
2326 },
2327 Some(key_id_guard) => (key_id_guard, tx),
2328 };
2329
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002330 let key_entry =
2331 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002332
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002333 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002334
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002335 Ok((key_id_guard, key_entry))
2336 }
2337
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002338 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002339 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002340 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2341 .context("Trying to delete keyentry.")?;
2342 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2343 .context("Trying to delete keymetadata.")?;
2344 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2345 .context("Trying to delete keyparameters.")?;
2346 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2347 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002348 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002349 }
2350
2351 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002352 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002353 pub fn unbind_key(
2354 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002355 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002356 key_type: KeyType,
2357 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002358 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002359 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002360 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2361
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002362 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2363 let (key_id, access_key_descriptor, access_vector) =
2364 Self::load_access_tuple(tx, key, key_type, caller_uid)
2365 .context("Trying to get access tuple.")?;
2366
2367 // Perform access control. It is vital that we return here if the permission is denied.
2368 // So do not touch that '?' at the end.
2369 check_permission(&access_key_descriptor, access_vector)
2370 .context("While checking permission.")?;
2371
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002372 Self::mark_unreferenced(tx, key_id)
2373 .map(|need_gc| (need_gc, ()))
2374 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002375 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002376 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002377 }
2378
Max Bires8e93d2b2021-01-14 13:17:59 -08002379 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2380 tx.query_row(
2381 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2382 params![key_id],
2383 |row| row.get(0),
2384 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002385 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002386 }
2387
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002388 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2389 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2390 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002391 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2392
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002393 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002394 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002395 }
2396 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2397 tx.execute(
2398 "DELETE FROM persistent.keymetadata
2399 WHERE keyentryid IN (
2400 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002401 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002402 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002403 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002404 )
2405 .context("Trying to delete keymetadata.")?;
2406 tx.execute(
2407 "DELETE FROM persistent.keyparameter
2408 WHERE keyentryid IN (
2409 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002410 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002411 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002412 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002413 )
2414 .context("Trying to delete keyparameters.")?;
2415 tx.execute(
2416 "DELETE FROM persistent.grant
2417 WHERE keyentryid IN (
2418 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002419 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002420 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002421 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002422 )
2423 .context("Trying to delete grants.")?;
2424 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002425 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002426 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2427 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002428 )
2429 .context("Trying to delete keyentry.")?;
2430 Ok(()).need_gc()
2431 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002432 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002433 }
2434
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002435 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2436 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2437 {
2438 tx.execute(
2439 "DELETE FROM persistent.keymetadata
2440 WHERE keyentryid IN (
2441 SELECT id FROM persistent.keyentry
2442 WHERE state = ?
2443 );",
2444 params![KeyLifeCycle::Unreferenced],
2445 )
2446 .context("Trying to delete keymetadata.")?;
2447 tx.execute(
2448 "DELETE FROM persistent.keyparameter
2449 WHERE keyentryid IN (
2450 SELECT id FROM persistent.keyentry
2451 WHERE state = ?
2452 );",
2453 params![KeyLifeCycle::Unreferenced],
2454 )
2455 .context("Trying to delete keyparameters.")?;
2456 tx.execute(
2457 "DELETE FROM persistent.grant
2458 WHERE keyentryid IN (
2459 SELECT id FROM persistent.keyentry
2460 WHERE state = ?
2461 );",
2462 params![KeyLifeCycle::Unreferenced],
2463 )
2464 .context("Trying to delete grants.")?;
2465 tx.execute(
2466 "DELETE FROM persistent.keyentry
2467 WHERE state = ?;",
2468 params![KeyLifeCycle::Unreferenced],
2469 )
2470 .context("Trying to delete keyentry.")?;
2471 Result::<()>::Ok(())
2472 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002473 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002474 }
2475
Hasini Gunasingheda895552021-01-27 19:34:37 +00002476 /// Delete the keys created on behalf of the user, denoted by the user id.
2477 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2478 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2479 /// The caller of this function should notify the gc if the returned value is true.
2480 pub fn unbind_keys_for_user(
2481 &mut self,
2482 user_id: u32,
2483 keep_non_super_encrypted_keys: bool,
2484 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002485 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2486
Hasini Gunasingheda895552021-01-27 19:34:37 +00002487 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2488 let mut stmt = tx
2489 .prepare(&format!(
2490 "SELECT id from persistent.keyentry
2491 WHERE (
2492 key_type = ?
2493 AND domain = ?
2494 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2495 AND state = ?
2496 ) OR (
2497 key_type = ?
2498 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002499 AND state = ?
2500 );",
2501 aid_user_offset = AID_USER_OFFSET
2502 ))
2503 .context(concat!(
2504 "In unbind_keys_for_user. ",
2505 "Failed to prepare the query to find the keys created by apps."
2506 ))?;
2507
2508 let mut rows = stmt
2509 .query(params![
2510 // WHERE client key:
2511 KeyType::Client,
2512 Domain::APP.0 as u32,
2513 user_id,
2514 KeyLifeCycle::Live,
2515 // OR super key:
2516 KeyType::Super,
2517 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002518 KeyLifeCycle::Live
2519 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002520 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002521
2522 let mut key_ids: Vec<i64> = Vec::new();
2523 db_utils::with_rows_extract_all(&mut rows, |row| {
2524 key_ids
2525 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2526 Ok(())
2527 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002528 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002529
2530 let mut notify_gc = false;
2531 for key_id in key_ids {
2532 if keep_non_super_encrypted_keys {
2533 // Load metadata and filter out non-super-encrypted keys.
2534 if let (_, Some((_, blob_metadata)), _, _) =
2535 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002536 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002537 {
2538 if blob_metadata.encrypted_by().is_none() {
2539 continue;
2540 }
2541 }
2542 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002543 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002544 .context("In unbind_keys_for_user.")?
2545 || notify_gc;
2546 }
2547 Ok(()).do_gc(notify_gc)
2548 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002549 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002550 }
2551
Eric Biggersb0478cf2023-10-27 03:55:29 +00002552 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2553 /// This runs when the user's lock screen is being changed to Swipe or None.
2554 ///
2555 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2556 /// such keys also require user authentication. Keystore's concept of user authentication is
2557 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2558 /// authentication is no longer possible. In contrast, keys that just require that the device
2559 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2560 /// is always considered "unlocked" in that case.
2561 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2562 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2563
2564 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2565 let mut stmt = tx
2566 .prepare(&format!(
2567 "SELECT id from persistent.keyentry
2568 WHERE key_type = ?
2569 AND domain = ?
2570 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2571 AND state = ?;",
2572 aid_user_offset = AID_USER_OFFSET
2573 ))
2574 .context(concat!(
2575 "In unbind_auth_bound_keys_for_user. ",
2576 "Failed to prepare the query to find the keys created by apps."
2577 ))?;
2578
2579 let mut rows = stmt
2580 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2581 .context(ks_err!("Failed to query the keys created by apps."))?;
2582
2583 let mut key_ids: Vec<i64> = Vec::new();
2584 db_utils::with_rows_extract_all(&mut rows, |row| {
2585 key_ids
2586 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2587 Ok(())
2588 })
2589 .context(ks_err!())?;
2590
2591 let mut notify_gc = false;
2592 let mut num_unbound = 0;
2593 for key_id in key_ids {
2594 // Load the key parameters and filter out non-auth-bound keys. To identify
2595 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2596 // could also be used, but UserSecureID is what Keystore treats as authoritative
2597 // when actually enforcing the key parameters (it might not matter, though).
2598 let params = Self::load_key_parameters(key_id, tx)
2599 .context("Failed to load key parameters.")?;
2600 let is_auth_bound_key = params.iter().any(|kp| {
2601 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2602 });
2603 if is_auth_bound_key {
2604 notify_gc = Self::mark_unreferenced(tx, key_id)
2605 .context("In unbind_auth_bound_keys_for_user.")?
2606 || notify_gc;
2607 num_unbound += 1;
2608 }
2609 }
2610 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2611 Ok(()).do_gc(notify_gc)
2612 })
2613 .context(ks_err!())
2614 }
2615
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002616 fn load_key_components(
2617 tx: &Transaction,
2618 load_bits: KeyEntryLoadBits,
2619 key_id: i64,
2620 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002621 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002622
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002623 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002624 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002625
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002626 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002627 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002628
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002629 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002630 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002631
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002632 Ok(KeyEntry {
2633 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002634 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002635 cert: cert_blob,
2636 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002637 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002638 parameters,
2639 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002640 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002641 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002642 }
2643
Eran Messeri24f31972023-01-25 17:00:33 +00002644 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2645 /// aliases are greater than the specified 'start_past_alias'. If no value
2646 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002647 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002648 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002649 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002650 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002651 &mut self,
2652 domain: Domain,
2653 namespace: i64,
2654 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002655 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002656 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002657 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002658
Eran Messeri24f31972023-01-25 17:00:33 +00002659 let query = format!(
2660 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002661 WHERE domain = ?
2662 AND namespace = ?
2663 AND alias IS NOT NULL
2664 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002665 AND key_type = ?
2666 {}
2667 ORDER BY alias ASC;",
2668 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2669 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002670
Eran Messeri24f31972023-01-25 17:00:33 +00002671 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2672 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2673
2674 let mut rows = match start_past_alias {
2675 Some(past_alias) => stmt
2676 .query(params![
2677 domain.0 as u32,
2678 namespace,
2679 KeyLifeCycle::Live,
2680 key_type,
2681 past_alias
2682 ])
2683 .context(ks_err!("Failed to query."))?,
2684 None => stmt
2685 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2686 .context(ks_err!("Failed to query."))?,
2687 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002688
Janis Danisevskis66784c42021-01-27 08:40:25 -08002689 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2690 db_utils::with_rows_extract_all(&mut rows, |row| {
2691 descriptors.push(KeyDescriptor {
2692 domain,
2693 nspace: namespace,
2694 alias: Some(row.get(0).context("Trying to extract alias.")?),
2695 blob: None,
2696 });
2697 Ok(())
2698 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002699 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002700 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002701 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002702 }
2703
Eran Messeri24f31972023-01-25 17:00:33 +00002704 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2705 /// Domain must be APP or SELINUX, the caller must make sure of that.
2706 pub fn count_keys(
2707 &mut self,
2708 domain: Domain,
2709 namespace: i64,
2710 key_type: KeyType,
2711 ) -> Result<usize> {
2712 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2713
2714 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2715 tx.query_row(
2716 "SELECT COUNT(alias) FROM persistent.keyentry
2717 WHERE domain = ?
2718 AND namespace = ?
2719 AND alias IS NOT NULL
2720 AND state = ?
2721 AND key_type = ?;",
2722 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2723 |row| row.get(0),
2724 )
2725 .context(ks_err!("Failed to count number of keys."))
2726 .no_gc()
2727 })?;
2728 Ok(num_keys)
2729 }
2730
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002731 /// Adds a grant to the grant table.
2732 /// Like `load_key_entry` this function loads the access tuple before
2733 /// it uses the callback for a permission check. Upon success,
2734 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2735 /// grant table. The new row will have a randomized id, which is used as
2736 /// grant id in the namespace field of the resulting KeyDescriptor.
2737 pub fn grant(
2738 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002739 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002740 caller_uid: u32,
2741 grantee_uid: u32,
2742 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002743 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002744 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002745 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2746
Janis Danisevskis66784c42021-01-27 08:40:25 -08002747 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2748 // Load the key_id and complete the access control tuple.
2749 // We ignore the access vector here because grants cannot be granted.
2750 // The access vector returned here expresses the permissions the
2751 // grantee has if key.domain == Domain::GRANT. But this vector
2752 // cannot include the grant permission by design, so there is no way the
2753 // subsequent permission check can pass.
2754 // We could check key.domain == Domain::GRANT and fail early.
2755 // But even if we load the access tuple by grant here, the permission
2756 // check denies the attempt to create a grant by grant descriptor.
2757 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002758 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002759
Janis Danisevskis66784c42021-01-27 08:40:25 -08002760 // Perform access control. It is vital that we return here if the permission
2761 // was denied. So do not touch that '?' at the end of the line.
2762 // This permission check checks if the caller has the grant permission
2763 // for the given key and in addition to all of the permissions
2764 // expressed in `access_vector`.
2765 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002766 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002767
Janis Danisevskis66784c42021-01-27 08:40:25 -08002768 let grant_id = if let Some(grant_id) = tx
2769 .query_row(
2770 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002771 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002772 params![key_id, grantee_uid],
2773 |row| row.get(0),
2774 )
2775 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002776 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002777 {
2778 tx.execute(
2779 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002780 SET access_vector = ?
2781 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002782 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002783 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002784 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002785 grant_id
2786 } else {
2787 Self::insert_with_retry(|id| {
2788 tx.execute(
2789 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2790 VALUES (?, ?, ?, ?);",
2791 params![id, grantee_uid, key_id, i32::from(access_vector)],
2792 )
2793 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002794 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002795 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002796
Janis Danisevskis66784c42021-01-27 08:40:25 -08002797 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002798 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002799 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002800 }
2801
2802 /// This function checks permissions like `grant` and `load_key_entry`
2803 /// before removing a grant from the grant table.
2804 pub fn ungrant(
2805 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002806 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002807 caller_uid: u32,
2808 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002809 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002810 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002811 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2812
Janis Danisevskis66784c42021-01-27 08:40:25 -08002813 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2814 // Load the key_id and complete the access control tuple.
2815 // We ignore the access vector here because grants cannot be granted.
2816 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002817 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002818
Janis Danisevskis66784c42021-01-27 08:40:25 -08002819 // Perform access control. We must return here if the permission
2820 // was denied. So do not touch the '?' at the end of this line.
2821 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002822 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002823
Janis Danisevskis66784c42021-01-27 08:40:25 -08002824 tx.execute(
2825 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002826 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002827 params![key_id, grantee_uid],
2828 )
2829 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002830
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002831 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002832 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002833 }
2834
Joel Galenson845f74b2020-09-09 14:11:55 -07002835 // Generates a random id and passes it to the given function, which will
2836 // try to insert it into a database. If that insertion fails, retry;
2837 // otherwise return the id.
2838 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2839 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002840 let newid: i64 = match random() {
2841 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2842 i => i,
2843 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002844 match inserter(newid) {
2845 // If the id already existed, try again.
2846 Err(rusqlite::Error::SqliteFailure(
2847 libsqlite3_sys::Error {
2848 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2849 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2850 },
2851 _,
2852 )) => (),
2853 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002854 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002855 }
2856 _ => return Ok(newid),
2857 }
2858 }
2859 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002860
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002861 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2862 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002863 self.perboot
2864 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002865 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002866
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002867 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002868 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002869 where
2870 F: Fn(&AuthTokenEntry) -> bool,
2871 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002872 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002873 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002874
2875 /// Load descriptor of a key by key id
2876 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2877 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2878
2879 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2880 tx.query_row(
2881 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2882 params![key_id],
2883 |row| {
2884 Ok(KeyDescriptor {
2885 domain: Domain(row.get(0)?),
2886 nspace: row.get(1)?,
2887 alias: row.get(2)?,
2888 blob: None,
2889 })
2890 },
2891 )
2892 .optional()
2893 .context("Trying to load key descriptor")
2894 .no_gc()
2895 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002896 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002897 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002898
2899 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2900 /// (for the given user_id).
2901 /// This is helpful for finding out which apps will have their keys invalidated when
2902 /// the user changes biometrics enrollment or removes their LSKF.
2903 pub fn get_app_uids_affected_by_sid(
2904 &mut self,
2905 user_id: i32,
2906 secure_user_id: i64,
2907 ) -> Result<Vec<i64>> {
2908 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2909
2910 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2911 let mut stmt = tx
2912 .prepare(&format!(
2913 "SELECT id, namespace from persistent.keyentry
2914 WHERE key_type = ?
2915 AND domain = ?
2916 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2917 AND state = ?;",
2918 ))
2919 .context(concat!(
2920 "In get_app_uids_affected_by_sid, ",
2921 "failed to prepare the query to find the keys created by apps."
2922 ))?;
2923
2924 let mut rows = stmt
2925 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2926 .context(ks_err!("Failed to query the keys created by apps."))?;
2927
2928 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2929 db_utils::with_rows_extract_all(&mut rows, |row| {
2930 key_ids_and_app_uids.insert(
2931 row.get(0).context("Failed to read key id of a key created by an app.")?,
2932 row.get(1).context("Failed to read the app uid")?,
2933 );
2934 Ok(())
2935 })?;
2936 Ok(key_ids_and_app_uids).no_gc()
2937 })?;
2938 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2939 for (key_id, app_uid) in key_ids_and_app_uids {
2940 // Read the key parameters for each key in its own transaction. It is OK to ignore
2941 // an error to get the properties of a particular key since it might have been deleted
2942 // under our feet after the previous transaction concluded. If the key was deleted
2943 // then it is no longer applicable if it was auth-bound or not.
2944 if let Ok(is_key_bound_to_sid) =
2945 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2946 let params = Self::load_key_parameters(key_id, tx)
2947 .context("Failed to load key parameters.")?;
2948 // Check if the key is bound to this secure user ID.
2949 let is_key_bound_to_sid = params.iter().any(|kp| {
2950 matches!(
2951 kp.key_parameter_value(),
2952 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2953 )
2954 });
2955 Ok(is_key_bound_to_sid).no_gc()
2956 })
2957 {
2958 if is_key_bound_to_sid {
2959 app_uids_affected_by_sid.insert(app_uid);
2960 }
2961 }
2962 }
2963
2964 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2965 Ok(app_uids_vec)
2966 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002967}
2968
2969#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002970pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002971
2972 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002973 use crate::key_parameter::{
2974 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2975 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2976 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002977 use crate::key_perm_set;
2978 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002979 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002980 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002981 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2982 HardwareAuthToken::HardwareAuthToken,
2983 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002984 };
2985 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002986 Timestamp::Timestamp,
2987 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002988 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07002989 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002990 use std::collections::BTreeMap;
2991 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002992 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002993 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002994 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002995 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002996 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002997 #[cfg(disabled)]
2998 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002999
Seth Moore7ee79f92021-12-07 11:42:49 -08003000 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003001 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003002
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003003 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003004 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003005 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003006 })?;
3007 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003008 }
3009
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003010 fn rebind_alias(
3011 db: &mut KeystoreDB,
3012 newid: &KeyIdGuard,
3013 alias: &str,
3014 domain: Domain,
3015 namespace: i64,
3016 ) -> Result<bool> {
3017 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003018 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003019 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003020 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003021 }
3022
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003023 #[test]
3024 fn datetime() -> Result<()> {
3025 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003026 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003027 let now = SystemTime::now();
3028 let duration = Duration::from_secs(1000);
3029 let then = now.checked_sub(duration).unwrap();
3030 let soon = now.checked_add(duration).unwrap();
3031 conn.execute(
3032 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3033 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3034 )?;
3035 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003036 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003037 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3038 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3039 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3040 assert!(rows.next()?.is_none());
3041 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3042 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3043 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3044 Ok(())
3045 }
3046
Joel Galenson0891bc12020-07-20 10:37:03 -07003047 // Ensure that we're using the "injected" random function, not the real one.
3048 #[test]
3049 fn test_mocked_random() {
3050 let rand1 = random();
3051 let rand2 = random();
3052 let rand3 = random();
3053 if rand1 == rand2 {
3054 assert_eq!(rand2 + 1, rand3);
3055 } else {
3056 assert_eq!(rand1 + 1, rand2);
3057 assert_eq!(rand2, rand3);
3058 }
3059 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003060
Joel Galenson26f4d012020-07-17 14:57:21 -07003061 // Test that we have the correct tables.
3062 #[test]
3063 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003064 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003065 let tables = db
3066 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003067 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003068 .query_map(params![], |row| row.get(0))?
3069 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003070 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003071 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003072 assert_eq!(tables[1], "blobmetadata");
3073 assert_eq!(tables[2], "grant");
3074 assert_eq!(tables[3], "keyentry");
3075 assert_eq!(tables[4], "keymetadata");
3076 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003077 Ok(())
3078 }
3079
3080 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003081 fn test_auth_token_table_invariant() -> Result<()> {
3082 let mut db = new_test_db()?;
3083 let auth_token1 = HardwareAuthToken {
3084 challenge: i64::MAX,
3085 userId: 200,
3086 authenticatorId: 200,
3087 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3088 timestamp: Timestamp { milliSeconds: 500 },
3089 mac: String::from("mac").into_bytes(),
3090 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003091 db.insert_auth_token(&auth_token1);
3092 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003093 assert_eq!(auth_tokens_returned.len(), 1);
3094
3095 // insert another auth token with the same values for the columns in the UNIQUE constraint
3096 // of the auth token table and different value for timestamp
3097 let auth_token2 = HardwareAuthToken {
3098 challenge: i64::MAX,
3099 userId: 200,
3100 authenticatorId: 200,
3101 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3102 timestamp: Timestamp { milliSeconds: 600 },
3103 mac: String::from("mac").into_bytes(),
3104 };
3105
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003106 db.insert_auth_token(&auth_token2);
3107 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003108 assert_eq!(auth_tokens_returned.len(), 1);
3109
3110 if let Some(auth_token) = auth_tokens_returned.pop() {
3111 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3112 }
3113
3114 // insert another auth token with the different values for the columns in the UNIQUE
3115 // constraint of the auth token table
3116 let auth_token3 = HardwareAuthToken {
3117 challenge: i64::MAX,
3118 userId: 201,
3119 authenticatorId: 200,
3120 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3121 timestamp: Timestamp { milliSeconds: 600 },
3122 mac: String::from("mac").into_bytes(),
3123 };
3124
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003125 db.insert_auth_token(&auth_token3);
3126 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003127 assert_eq!(auth_tokens_returned.len(), 2);
3128
3129 Ok(())
3130 }
3131
3132 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003133 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3134 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003135 }
3136
3137 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003138 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003139 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003140 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003141
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003142 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003143 let entries = get_keyentry(&db)?;
3144 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003145
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003146 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003147
3148 let entries_new = get_keyentry(&db)?;
3149 assert_eq!(entries, entries_new);
3150 Ok(())
3151 }
3152
3153 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003154 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003155 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3156 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003157 }
3158
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003159 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003160
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003161 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3162 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003163
3164 let entries = get_keyentry(&db)?;
3165 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003166 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3167 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003168
3169 // Test that we must pass in a valid Domain.
3170 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003171 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003172 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003173 );
3174 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003175 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003176 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003177 );
3178 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003179 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003180 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003181 );
3182
3183 Ok(())
3184 }
3185
Joel Galenson33c04ad2020-08-03 11:04:38 -07003186 #[test]
3187 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003188 fn extractor(
3189 ke: &KeyEntryRow,
3190 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3191 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003192 }
3193
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003194 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003195 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3196 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003197 let entries = get_keyentry(&db)?;
3198 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003199 assert_eq!(
3200 extractor(&entries[0]),
3201 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3202 );
3203 assert_eq!(
3204 extractor(&entries[1]),
3205 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3206 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003207
3208 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003209 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003210 let entries = get_keyentry(&db)?;
3211 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003212 assert_eq!(
3213 extractor(&entries[0]),
3214 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3215 );
3216 assert_eq!(
3217 extractor(&entries[1]),
3218 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3219 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003220
3221 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003222 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003223 let entries = get_keyentry(&db)?;
3224 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003225 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3226 assert_eq!(
3227 extractor(&entries[1]),
3228 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3229 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003230
3231 // Test that we must pass in a valid Domain.
3232 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003233 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003234 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003235 );
3236 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003237 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003238 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003239 );
3240 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003241 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003242 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003243 );
3244
3245 // Test that we correctly handle setting an alias for something that does not exist.
3246 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003247 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003248 "Expected to update a single entry but instead updated 0",
3249 );
3250 // Test that we correctly abort the transaction in this case.
3251 let entries = get_keyentry(&db)?;
3252 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003253 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3254 assert_eq!(
3255 extractor(&entries[1]),
3256 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3257 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003258
3259 Ok(())
3260 }
3261
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003262 #[test]
3263 fn test_grant_ungrant() -> Result<()> {
3264 const CALLER_UID: u32 = 15;
3265 const GRANTEE_UID: u32 = 12;
3266 const SELINUX_NAMESPACE: i64 = 7;
3267
3268 let mut db = new_test_db()?;
3269 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003270 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3271 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3272 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003273 )?;
3274 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003275 domain: super::Domain::APP,
3276 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003277 alias: Some("key".to_string()),
3278 blob: None,
3279 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003280 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3281 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003282
3283 // Reset totally predictable random number generator in case we
3284 // are not the first test running on this thread.
3285 reset_random();
3286 let next_random = 0i64;
3287
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003288 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003289 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003290 assert_eq!(*a, PVEC1);
3291 assert_eq!(
3292 *k,
3293 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003294 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003295 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003296 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003297 alias: Some("key".to_string()),
3298 blob: None,
3299 }
3300 );
3301 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003302 })
3303 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003304
3305 assert_eq!(
3306 app_granted_key,
3307 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003308 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003309 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003310 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003311 alias: None,
3312 blob: None,
3313 }
3314 );
3315
3316 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003317 domain: super::Domain::SELINUX,
3318 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003319 alias: Some("yek".to_string()),
3320 blob: None,
3321 };
3322
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003323 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003324 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003325 assert_eq!(*a, PVEC1);
3326 assert_eq!(
3327 *k,
3328 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003329 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003330 // namespace must be the supplied SELinux
3331 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003332 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003333 alias: Some("yek".to_string()),
3334 blob: None,
3335 }
3336 );
3337 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003338 })
3339 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003340
3341 assert_eq!(
3342 selinux_granted_key,
3343 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003344 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003345 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003346 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003347 alias: None,
3348 blob: None,
3349 }
3350 );
3351
3352 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003353 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003354 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003355 assert_eq!(*a, PVEC2);
3356 assert_eq!(
3357 *k,
3358 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003359 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003360 // namespace must be the supplied SELinux
3361 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003362 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003363 alias: Some("yek".to_string()),
3364 blob: None,
3365 }
3366 );
3367 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003368 })
3369 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003370
3371 assert_eq!(
3372 selinux_granted_key,
3373 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003374 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003375 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003376 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003377 alias: None,
3378 blob: None,
3379 }
3380 );
3381
3382 {
3383 // Limiting scope of stmt, because it borrows db.
3384 let mut stmt = db
3385 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003386 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003387 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3388 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3389 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003390
3391 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003392 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003393 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003394 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003395 assert!(rows.next().is_none());
3396 }
3397
3398 debug_dump_keyentry_table(&mut db)?;
3399 println!("app_key {:?}", app_key);
3400 println!("selinux_key {:?}", selinux_key);
3401
Janis Danisevskis66784c42021-01-27 08:40:25 -08003402 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3403 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003404
3405 Ok(())
3406 }
3407
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003408 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003409 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3410 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3411
3412 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003413 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003414 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003415 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003416 let mut blob_metadata = BlobMetaData::new();
3417 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3418 db.set_blob(
3419 &key_id,
3420 SubComponentType::KEY_BLOB,
3421 Some(TEST_KEY_BLOB),
3422 Some(&blob_metadata),
3423 )?;
3424 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3425 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003426 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003427
3428 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003429 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003430 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003431 )?;
3432 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003433 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003434 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003435 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003436 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003437 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003438 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003439 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003440 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003441 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003442
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003443 drop(rows);
3444 drop(stmt);
3445
3446 assert_eq!(
3447 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3448 BlobMetaData::load_from_db(id, tx).no_gc()
3449 })
3450 .expect("Should find blob metadata."),
3451 blob_metadata
3452 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003453 Ok(())
3454 }
3455
3456 static TEST_ALIAS: &str = "my super duper key";
3457
3458 #[test]
3459 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3460 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003461 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003462 .context("test_insert_and_load_full_keyentry_domain_app")?
3463 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003464 let (_key_guard, key_entry) = db
3465 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003466 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003467 domain: Domain::APP,
3468 nspace: 0,
3469 alias: Some(TEST_ALIAS.to_string()),
3470 blob: None,
3471 },
3472 KeyType::Client,
3473 KeyEntryLoadBits::BOTH,
3474 1,
3475 |_k, _av| Ok(()),
3476 )
3477 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003478 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003479
3480 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003481 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003482 domain: Domain::APP,
3483 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003484 alias: Some(TEST_ALIAS.to_string()),
3485 blob: None,
3486 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003487 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003488 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003489 |_, _| Ok(()),
3490 )
3491 .unwrap();
3492
3493 assert_eq!(
3494 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3495 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003496 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003497 domain: Domain::APP,
3498 nspace: 0,
3499 alias: Some(TEST_ALIAS.to_string()),
3500 blob: None,
3501 },
3502 KeyType::Client,
3503 KeyEntryLoadBits::NONE,
3504 1,
3505 |_k, _av| Ok(()),
3506 )
3507 .unwrap_err()
3508 .root_cause()
3509 .downcast_ref::<KsError>()
3510 );
3511
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003512 Ok(())
3513 }
3514
3515 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003516 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3517 let mut db = new_test_db()?;
3518
3519 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003520 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003521 domain: Domain::APP,
3522 nspace: 1,
3523 alias: Some(TEST_ALIAS.to_string()),
3524 blob: None,
3525 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003526 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003527 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003528 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003529 )
3530 .expect("Trying to insert cert.");
3531
3532 let (_key_guard, mut key_entry) = db
3533 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003534 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003535 domain: Domain::APP,
3536 nspace: 1,
3537 alias: Some(TEST_ALIAS.to_string()),
3538 blob: None,
3539 },
3540 KeyType::Client,
3541 KeyEntryLoadBits::PUBLIC,
3542 1,
3543 |_k, _av| Ok(()),
3544 )
3545 .expect("Trying to read certificate entry.");
3546
3547 assert!(key_entry.pure_cert());
3548 assert!(key_entry.cert().is_none());
3549 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3550
3551 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003552 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003553 domain: Domain::APP,
3554 nspace: 1,
3555 alias: Some(TEST_ALIAS.to_string()),
3556 blob: None,
3557 },
3558 KeyType::Client,
3559 1,
3560 |_, _| Ok(()),
3561 )
3562 .unwrap();
3563
3564 assert_eq!(
3565 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3566 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003567 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003568 domain: Domain::APP,
3569 nspace: 1,
3570 alias: Some(TEST_ALIAS.to_string()),
3571 blob: None,
3572 },
3573 KeyType::Client,
3574 KeyEntryLoadBits::NONE,
3575 1,
3576 |_k, _av| Ok(()),
3577 )
3578 .unwrap_err()
3579 .root_cause()
3580 .downcast_ref::<KsError>()
3581 );
3582
3583 Ok(())
3584 }
3585
3586 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003587 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3588 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003589 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003590 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3591 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003592 let (_key_guard, key_entry) = db
3593 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003594 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003595 domain: Domain::SELINUX,
3596 nspace: 1,
3597 alias: Some(TEST_ALIAS.to_string()),
3598 blob: None,
3599 },
3600 KeyType::Client,
3601 KeyEntryLoadBits::BOTH,
3602 1,
3603 |_k, _av| Ok(()),
3604 )
3605 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003606 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003607
3608 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003609 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003610 domain: Domain::SELINUX,
3611 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003612 alias: Some(TEST_ALIAS.to_string()),
3613 blob: None,
3614 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003615 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003616 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003617 |_, _| Ok(()),
3618 )
3619 .unwrap();
3620
3621 assert_eq!(
3622 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3623 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003624 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003625 domain: Domain::SELINUX,
3626 nspace: 1,
3627 alias: Some(TEST_ALIAS.to_string()),
3628 blob: None,
3629 },
3630 KeyType::Client,
3631 KeyEntryLoadBits::NONE,
3632 1,
3633 |_k, _av| Ok(()),
3634 )
3635 .unwrap_err()
3636 .root_cause()
3637 .downcast_ref::<KsError>()
3638 );
3639
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003640 Ok(())
3641 }
3642
3643 #[test]
3644 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3645 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003646 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003647 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3648 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003649 let (_, key_entry) = db
3650 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003651 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003652 KeyType::Client,
3653 KeyEntryLoadBits::BOTH,
3654 1,
3655 |_k, _av| Ok(()),
3656 )
3657 .unwrap();
3658
Qi Wub9433b52020-12-01 14:52:46 +08003659 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003660
3661 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003662 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003663 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003664 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003665 |_, _| Ok(()),
3666 )
3667 .unwrap();
3668
3669 assert_eq!(
3670 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3671 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003672 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003673 KeyType::Client,
3674 KeyEntryLoadBits::NONE,
3675 1,
3676 |_k, _av| Ok(()),
3677 )
3678 .unwrap_err()
3679 .root_cause()
3680 .downcast_ref::<KsError>()
3681 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003682
3683 Ok(())
3684 }
3685
3686 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003687 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3688 let mut db = new_test_db()?;
3689 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3690 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3691 .0;
3692 // Update the usage count of the limited use key.
3693 db.check_and_update_key_usage_count(key_id)?;
3694
3695 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003696 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003697 KeyType::Client,
3698 KeyEntryLoadBits::BOTH,
3699 1,
3700 |_k, _av| Ok(()),
3701 )?;
3702
3703 // The usage count is decremented now.
3704 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3705
3706 Ok(())
3707 }
3708
3709 #[test]
3710 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3711 let mut db = new_test_db()?;
3712 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3713 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3714 .0;
3715 // Update the usage count of the limited use key.
3716 db.check_and_update_key_usage_count(key_id).expect(concat!(
3717 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3718 "This should succeed."
3719 ));
3720
3721 // Try to update the exhausted limited use key.
3722 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3723 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3724 "This should fail."
3725 ));
3726 assert_eq!(
3727 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3728 e.root_cause().downcast_ref::<KsError>().unwrap()
3729 );
3730
3731 Ok(())
3732 }
3733
3734 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003735 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3736 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003737 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003738 .context("test_insert_and_load_full_keyentry_from_grant")?
3739 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003741 let granted_key = db
3742 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003743 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003744 domain: Domain::APP,
3745 nspace: 0,
3746 alias: Some(TEST_ALIAS.to_string()),
3747 blob: None,
3748 },
3749 1,
3750 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003751 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003752 |_k, _av| Ok(()),
3753 )
3754 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755
3756 debug_dump_grant_table(&mut db)?;
3757
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003758 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003759 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3760 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003761 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003762 Ok(())
3763 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003764 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003765
Qi Wub9433b52020-12-01 14:52:46 +08003766 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003767
Janis Danisevskis66784c42021-01-27 08:40:25 -08003768 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003769
3770 assert_eq!(
3771 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3772 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003773 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003774 KeyType::Client,
3775 KeyEntryLoadBits::NONE,
3776 2,
3777 |_k, _av| Ok(()),
3778 )
3779 .unwrap_err()
3780 .root_cause()
3781 .downcast_ref::<KsError>()
3782 );
3783
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003784 Ok(())
3785 }
3786
Janis Danisevskis45760022021-01-19 16:34:10 -08003787 // This test attempts to load a key by key id while the caller is not the owner
3788 // but a grant exists for the given key and the caller.
3789 #[test]
3790 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3791 let mut db = new_test_db()?;
3792 const OWNER_UID: u32 = 1u32;
3793 const GRANTEE_UID: u32 = 2u32;
3794 const SOMEONE_ELSE_UID: u32 = 3u32;
3795 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3796 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3797 .0;
3798
3799 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003800 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003801 domain: Domain::APP,
3802 nspace: 0,
3803 alias: Some(TEST_ALIAS.to_string()),
3804 blob: None,
3805 },
3806 OWNER_UID,
3807 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003808 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003809 |_k, _av| Ok(()),
3810 )
3811 .unwrap();
3812
3813 debug_dump_grant_table(&mut db)?;
3814
3815 let id_descriptor =
3816 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3817
3818 let (_, key_entry) = db
3819 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003820 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003821 KeyType::Client,
3822 KeyEntryLoadBits::BOTH,
3823 GRANTEE_UID,
3824 |k, av| {
3825 assert_eq!(Domain::APP, k.domain);
3826 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003827 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003828 Ok(())
3829 },
3830 )
3831 .unwrap();
3832
3833 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3834
3835 let (_, key_entry) = db
3836 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003837 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003838 KeyType::Client,
3839 KeyEntryLoadBits::BOTH,
3840 SOMEONE_ELSE_UID,
3841 |k, av| {
3842 assert_eq!(Domain::APP, k.domain);
3843 assert_eq!(OWNER_UID as i64, k.nspace);
3844 assert!(av.is_none());
3845 Ok(())
3846 },
3847 )
3848 .unwrap();
3849
3850 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3851
Janis Danisevskis66784c42021-01-27 08:40:25 -08003852 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003853
3854 assert_eq!(
3855 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3856 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003857 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003858 KeyType::Client,
3859 KeyEntryLoadBits::NONE,
3860 GRANTEE_UID,
3861 |_k, _av| Ok(()),
3862 )
3863 .unwrap_err()
3864 .root_cause()
3865 .downcast_ref::<KsError>()
3866 );
3867
3868 Ok(())
3869 }
3870
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003871 // Creates a key migrates it to a different location and then tries to access it by the old
3872 // and new location.
3873 #[test]
3874 fn test_migrate_key_app_to_app() -> Result<()> {
3875 let mut db = new_test_db()?;
3876 const SOURCE_UID: u32 = 1u32;
3877 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003878 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3879 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003880 let key_id_guard =
3881 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3882 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3883
3884 let source_descriptor: KeyDescriptor = KeyDescriptor {
3885 domain: Domain::APP,
3886 nspace: -1,
3887 alias: Some(SOURCE_ALIAS.to_string()),
3888 blob: None,
3889 };
3890
3891 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3892 domain: Domain::APP,
3893 nspace: -1,
3894 alias: Some(DESTINATION_ALIAS.to_string()),
3895 blob: None,
3896 };
3897
3898 let key_id = key_id_guard.id();
3899
3900 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3901 Ok(())
3902 })
3903 .unwrap();
3904
3905 let (_, key_entry) = db
3906 .load_key_entry(
3907 &destination_descriptor,
3908 KeyType::Client,
3909 KeyEntryLoadBits::BOTH,
3910 DESTINATION_UID,
3911 |k, av| {
3912 assert_eq!(Domain::APP, k.domain);
3913 assert_eq!(DESTINATION_UID as i64, k.nspace);
3914 assert!(av.is_none());
3915 Ok(())
3916 },
3917 )
3918 .unwrap();
3919
3920 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3921
3922 assert_eq!(
3923 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3924 db.load_key_entry(
3925 &source_descriptor,
3926 KeyType::Client,
3927 KeyEntryLoadBits::NONE,
3928 SOURCE_UID,
3929 |_k, _av| Ok(()),
3930 )
3931 .unwrap_err()
3932 .root_cause()
3933 .downcast_ref::<KsError>()
3934 );
3935
3936 Ok(())
3937 }
3938
3939 // Creates a key migrates it to a different location and then tries to access it by the old
3940 // and new location.
3941 #[test]
3942 fn test_migrate_key_app_to_selinux() -> Result<()> {
3943 let mut db = new_test_db()?;
3944 const SOURCE_UID: u32 = 1u32;
3945 const DESTINATION_UID: u32 = 2u32;
3946 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003947 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3948 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003949 let key_id_guard =
3950 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3951 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3952
3953 let source_descriptor: KeyDescriptor = KeyDescriptor {
3954 domain: Domain::APP,
3955 nspace: -1,
3956 alias: Some(SOURCE_ALIAS.to_string()),
3957 blob: None,
3958 };
3959
3960 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3961 domain: Domain::SELINUX,
3962 nspace: DESTINATION_NAMESPACE,
3963 alias: Some(DESTINATION_ALIAS.to_string()),
3964 blob: None,
3965 };
3966
3967 let key_id = key_id_guard.id();
3968
3969 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3970 Ok(())
3971 })
3972 .unwrap();
3973
3974 let (_, key_entry) = db
3975 .load_key_entry(
3976 &destination_descriptor,
3977 KeyType::Client,
3978 KeyEntryLoadBits::BOTH,
3979 DESTINATION_UID,
3980 |k, av| {
3981 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003982 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003983 assert!(av.is_none());
3984 Ok(())
3985 },
3986 )
3987 .unwrap();
3988
3989 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3990
3991 assert_eq!(
3992 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3993 db.load_key_entry(
3994 &source_descriptor,
3995 KeyType::Client,
3996 KeyEntryLoadBits::NONE,
3997 SOURCE_UID,
3998 |_k, _av| Ok(()),
3999 )
4000 .unwrap_err()
4001 .root_cause()
4002 .downcast_ref::<KsError>()
4003 );
4004
4005 Ok(())
4006 }
4007
4008 // Creates two keys and tries to migrate the first to the location of the second which
4009 // is expected to fail.
4010 #[test]
4011 fn test_migrate_key_destination_occupied() -> Result<()> {
4012 let mut db = new_test_db()?;
4013 const SOURCE_UID: u32 = 1u32;
4014 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004015 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4016 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004017 let key_id_guard =
4018 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4019 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4020 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4021 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4022
4023 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4024 domain: Domain::APP,
4025 nspace: -1,
4026 alias: Some(DESTINATION_ALIAS.to_string()),
4027 blob: None,
4028 };
4029
4030 assert_eq!(
4031 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4032 db.migrate_key_namespace(
4033 key_id_guard,
4034 &destination_descriptor,
4035 DESTINATION_UID,
4036 |_k| Ok(())
4037 )
4038 .unwrap_err()
4039 .root_cause()
4040 .downcast_ref::<KsError>()
4041 );
4042
4043 Ok(())
4044 }
4045
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004046 #[test]
4047 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004048 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4049 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4050 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004051 const UID: u32 = 33;
4052 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4053 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4054 let key_id_untouched1 =
4055 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4056 let key_id_untouched2 =
4057 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4058 let key_id_deleted =
4059 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4060
4061 let (_, key_entry) = db
4062 .load_key_entry(
4063 &KeyDescriptor {
4064 domain: Domain::APP,
4065 nspace: -1,
4066 alias: Some(ALIAS1.to_string()),
4067 blob: None,
4068 },
4069 KeyType::Client,
4070 KeyEntryLoadBits::BOTH,
4071 UID,
4072 |k, av| {
4073 assert_eq!(Domain::APP, k.domain);
4074 assert_eq!(UID as i64, k.nspace);
4075 assert!(av.is_none());
4076 Ok(())
4077 },
4078 )
4079 .unwrap();
4080 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4081 let (_, key_entry) = db
4082 .load_key_entry(
4083 &KeyDescriptor {
4084 domain: Domain::APP,
4085 nspace: -1,
4086 alias: Some(ALIAS2.to_string()),
4087 blob: None,
4088 },
4089 KeyType::Client,
4090 KeyEntryLoadBits::BOTH,
4091 UID,
4092 |k, av| {
4093 assert_eq!(Domain::APP, k.domain);
4094 assert_eq!(UID as i64, k.nspace);
4095 assert!(av.is_none());
4096 Ok(())
4097 },
4098 )
4099 .unwrap();
4100 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4101 let (_, key_entry) = db
4102 .load_key_entry(
4103 &KeyDescriptor {
4104 domain: Domain::APP,
4105 nspace: -1,
4106 alias: Some(ALIAS3.to_string()),
4107 blob: None,
4108 },
4109 KeyType::Client,
4110 KeyEntryLoadBits::BOTH,
4111 UID,
4112 |k, av| {
4113 assert_eq!(Domain::APP, k.domain);
4114 assert_eq!(UID as i64, k.nspace);
4115 assert!(av.is_none());
4116 Ok(())
4117 },
4118 )
4119 .unwrap();
4120 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4121
4122 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4123 KeystoreDB::from_0_to_1(tx).no_gc()
4124 })
4125 .unwrap();
4126
4127 let (_, key_entry) = db
4128 .load_key_entry(
4129 &KeyDescriptor {
4130 domain: Domain::APP,
4131 nspace: -1,
4132 alias: Some(ALIAS1.to_string()),
4133 blob: None,
4134 },
4135 KeyType::Client,
4136 KeyEntryLoadBits::BOTH,
4137 UID,
4138 |k, av| {
4139 assert_eq!(Domain::APP, k.domain);
4140 assert_eq!(UID as i64, k.nspace);
4141 assert!(av.is_none());
4142 Ok(())
4143 },
4144 )
4145 .unwrap();
4146 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4147 let (_, key_entry) = db
4148 .load_key_entry(
4149 &KeyDescriptor {
4150 domain: Domain::APP,
4151 nspace: -1,
4152 alias: Some(ALIAS2.to_string()),
4153 blob: None,
4154 },
4155 KeyType::Client,
4156 KeyEntryLoadBits::BOTH,
4157 UID,
4158 |k, av| {
4159 assert_eq!(Domain::APP, k.domain);
4160 assert_eq!(UID as i64, k.nspace);
4161 assert!(av.is_none());
4162 Ok(())
4163 },
4164 )
4165 .unwrap();
4166 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4167 assert_eq!(
4168 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4169 db.load_key_entry(
4170 &KeyDescriptor {
4171 domain: Domain::APP,
4172 nspace: -1,
4173 alias: Some(ALIAS3.to_string()),
4174 blob: None,
4175 },
4176 KeyType::Client,
4177 KeyEntryLoadBits::BOTH,
4178 UID,
4179 |k, av| {
4180 assert_eq!(Domain::APP, k.domain);
4181 assert_eq!(UID as i64, k.nspace);
4182 assert!(av.is_none());
4183 Ok(())
4184 },
4185 )
4186 .unwrap_err()
4187 .root_cause()
4188 .downcast_ref::<KsError>()
4189 );
4190 }
4191
Janis Danisevskisaec14592020-11-12 09:41:49 -08004192 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4193
Janis Danisevskisaec14592020-11-12 09:41:49 -08004194 #[test]
4195 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4196 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004197 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4198 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004199 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004200 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004201 .context("test_insert_and_load_full_keyentry_domain_app")?
4202 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004203 let (_key_guard, key_entry) = db
4204 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004205 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004206 domain: Domain::APP,
4207 nspace: 0,
4208 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4209 blob: None,
4210 },
4211 KeyType::Client,
4212 KeyEntryLoadBits::BOTH,
4213 33,
4214 |_k, _av| Ok(()),
4215 )
4216 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004217 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004218 let state = Arc::new(AtomicU8::new(1));
4219 let state2 = state.clone();
4220
4221 // Spawning a second thread that attempts to acquire the key id lock
4222 // for the same key as the primary thread. The primary thread then
4223 // waits, thereby forcing the secondary thread into the second stage
4224 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4225 // The test succeeds if the secondary thread observes the transition
4226 // of `state` from 1 to 2, despite having a whole second to overtake
4227 // the primary thread.
4228 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004229 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004230 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004231 assert!(db
4232 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004233 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004234 domain: Domain::APP,
4235 nspace: 0,
4236 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4237 blob: None,
4238 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004239 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004240 KeyEntryLoadBits::BOTH,
4241 33,
4242 |_k, _av| Ok(()),
4243 )
4244 .is_ok());
4245 // We should only see a 2 here because we can only return
4246 // from load_key_entry when the `_key_guard` expires,
4247 // which happens at the end of the scope.
4248 assert_eq!(2, state2.load(Ordering::Relaxed));
4249 });
4250
4251 thread::sleep(std::time::Duration::from_millis(1000));
4252
4253 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4254
4255 // Return the handle from this scope so we can join with the
4256 // secondary thread after the key id lock has expired.
4257 handle
4258 // This is where the `_key_guard` goes out of scope,
4259 // which is the reason for concurrent load_key_entry on the same key
4260 // to unblock.
4261 };
4262 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4263 // main test thread. We will not see failing asserts in secondary threads otherwise.
4264 handle.join().unwrap();
4265 Ok(())
4266 }
4267
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004268 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004269 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004270 let temp_dir =
4271 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4272
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004273 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4274 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004275
4276 let _tx1 = db1
4277 .conn
4278 .transaction_with_behavior(TransactionBehavior::Immediate)
4279 .expect("Failed to create first transaction.");
4280
4281 let error = db2
4282 .conn
4283 .transaction_with_behavior(TransactionBehavior::Immediate)
4284 .context("Transaction begin failed.")
4285 .expect_err("This should fail.");
4286 let root_cause = error.root_cause();
4287 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4288 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4289 {
4290 return;
4291 }
4292 panic!(
4293 "Unexpected error {:?} \n{:?} \n{:?}",
4294 error,
4295 root_cause,
4296 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4297 )
4298 }
4299
4300 #[cfg(disabled)]
4301 #[test]
4302 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4303 let temp_dir = Arc::new(
4304 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4305 .expect("Failed to create temp dir."),
4306 );
4307
4308 let test_begin = Instant::now();
4309
Janis Danisevskis66784c42021-01-27 08:40:25 -08004310 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004311 let mut db =
4312 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004313 const OPEN_DB_COUNT: u32 = 50u32;
4314
4315 let mut actual_key_count = KEY_COUNT;
4316 // First insert KEY_COUNT keys.
4317 for count in 0..KEY_COUNT {
4318 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4319 actual_key_count = count;
4320 break;
4321 }
4322 let alias = format!("test_alias_{}", count);
4323 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4324 .expect("Failed to make key entry.");
4325 }
4326
4327 // Insert more keys from a different thread and into a different namespace.
4328 let temp_dir1 = temp_dir.clone();
4329 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004330 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4331 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004332
4333 for count in 0..actual_key_count {
4334 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4335 return;
4336 }
4337 let alias = format!("test_alias_{}", count);
4338 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4339 .expect("Failed to make key entry.");
4340 }
4341
4342 // then unbind them again.
4343 for count in 0..actual_key_count {
4344 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4345 return;
4346 }
4347 let key = KeyDescriptor {
4348 domain: Domain::APP,
4349 nspace: -1,
4350 alias: Some(format!("test_alias_{}", count)),
4351 blob: None,
4352 };
4353 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4354 }
4355 });
4356
4357 // And start unbinding the first set of keys.
4358 let temp_dir2 = temp_dir.clone();
4359 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004360 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4361 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004362
4363 for count in 0..actual_key_count {
4364 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4365 return;
4366 }
4367 let key = KeyDescriptor {
4368 domain: Domain::APP,
4369 nspace: -1,
4370 alias: Some(format!("test_alias_{}", count)),
4371 blob: None,
4372 };
4373 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4374 }
4375 });
4376
Janis Danisevskis66784c42021-01-27 08:40:25 -08004377 // While a lot of inserting and deleting is going on we have to open database connections
4378 // successfully and use them.
4379 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4380 // out of scope.
4381 #[allow(clippy::redundant_clone)]
4382 let temp_dir4 = temp_dir.clone();
4383 let handle4 = thread::spawn(move || {
4384 for count in 0..OPEN_DB_COUNT {
4385 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4386 return;
4387 }
Seth Moore444b51a2021-06-11 09:49:49 -07004388 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4389 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004390
4391 let alias = format!("test_alias_{}", count);
4392 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4393 .expect("Failed to make key entry.");
4394 let key = KeyDescriptor {
4395 domain: Domain::APP,
4396 nspace: -1,
4397 alias: Some(alias),
4398 blob: None,
4399 };
4400 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4401 }
4402 });
4403
4404 handle1.join().expect("Thread 1 panicked.");
4405 handle2.join().expect("Thread 2 panicked.");
4406 handle4.join().expect("Thread 4 panicked.");
4407
Janis Danisevskis66784c42021-01-27 08:40:25 -08004408 Ok(())
4409 }
4410
4411 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004412 fn list() -> Result<()> {
4413 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004414 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004415 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4416 (Domain::APP, 1, "test1"),
4417 (Domain::APP, 1, "test2"),
4418 (Domain::APP, 1, "test3"),
4419 (Domain::APP, 1, "test4"),
4420 (Domain::APP, 1, "test5"),
4421 (Domain::APP, 1, "test6"),
4422 (Domain::APP, 1, "test7"),
4423 (Domain::APP, 2, "test1"),
4424 (Domain::APP, 2, "test2"),
4425 (Domain::APP, 2, "test3"),
4426 (Domain::APP, 2, "test4"),
4427 (Domain::APP, 2, "test5"),
4428 (Domain::APP, 2, "test6"),
4429 (Domain::APP, 2, "test8"),
4430 (Domain::SELINUX, 100, "test1"),
4431 (Domain::SELINUX, 100, "test2"),
4432 (Domain::SELINUX, 100, "test3"),
4433 (Domain::SELINUX, 100, "test4"),
4434 (Domain::SELINUX, 100, "test5"),
4435 (Domain::SELINUX, 100, "test6"),
4436 (Domain::SELINUX, 100, "test9"),
4437 ];
4438
4439 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4440 .iter()
4441 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004442 let entry =
4443 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004444 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4445 });
4446 (entry.id(), *ns)
4447 })
4448 .collect();
4449
4450 for (domain, namespace) in
4451 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4452 {
4453 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4454 .iter()
4455 .filter_map(|(domain, ns, alias)| match ns {
4456 ns if *ns == *namespace => Some(KeyDescriptor {
4457 domain: *domain,
4458 nspace: *ns,
4459 alias: Some(alias.to_string()),
4460 blob: None,
4461 }),
4462 _ => None,
4463 })
4464 .collect();
4465 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004466 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004467 list_result.sort();
4468 assert_eq!(list_o_descriptors, list_result);
4469
4470 let mut list_o_ids: Vec<i64> = list_o_descriptors
4471 .into_iter()
4472 .map(|d| {
4473 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004474 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004475 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004476 KeyType::Client,
4477 KeyEntryLoadBits::NONE,
4478 *namespace as u32,
4479 |_, _| Ok(()),
4480 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004481 .unwrap();
4482 entry.id()
4483 })
4484 .collect();
4485 list_o_ids.sort_unstable();
4486 let mut loaded_entries: Vec<i64> = list_o_keys
4487 .iter()
4488 .filter_map(|(id, ns)| match ns {
4489 ns if *ns == *namespace => Some(*id),
4490 _ => None,
4491 })
4492 .collect();
4493 loaded_entries.sort_unstable();
4494 assert_eq!(list_o_ids, loaded_entries);
4495 }
Eran Messeri24f31972023-01-25 17:00:33 +00004496 assert_eq!(
4497 Vec::<KeyDescriptor>::new(),
4498 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4499 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004500
4501 Ok(())
4502 }
4503
Joel Galenson0891bc12020-07-20 10:37:03 -07004504 // Helpers
4505
4506 // Checks that the given result is an error containing the given string.
4507 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4508 let error_str = format!(
4509 "{:#?}",
4510 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4511 );
4512 assert!(
4513 error_str.contains(target),
4514 "The string \"{}\" should contain \"{}\"",
4515 error_str,
4516 target
4517 );
4518 }
4519
Joel Galenson2aab4432020-07-22 15:27:57 -07004520 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004521 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004522 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004523 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004524 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004525 namespace: Option<i64>,
4526 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004527 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004528 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004529 }
4530
4531 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4532 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004533 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004534 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004535 Ok(KeyEntryRow {
4536 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004537 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004538 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004539 namespace: row.get(3)?,
4540 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004541 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004542 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004543 })
4544 })?
4545 .map(|r| r.context("Could not read keyentry row."))
4546 .collect::<Result<Vec<_>>>()
4547 }
4548
Eran Messeri4dc27b52024-01-09 12:43:31 +00004549 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4550 make_test_params_with_sids(max_usage_count, &[42])
4551 }
4552
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004553 // Note: The parameters and SecurityLevel associations are nonsensical. This
4554 // collection is only used to check if the parameters are preserved as expected by the
4555 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004556 fn make_test_params_with_sids(
4557 max_usage_count: Option<i32>,
4558 user_secure_ids: &[i64],
4559 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004560 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004561 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4562 KeyParameter::new(
4563 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4564 SecurityLevel::TRUSTED_ENVIRONMENT,
4565 ),
4566 KeyParameter::new(
4567 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4568 SecurityLevel::TRUSTED_ENVIRONMENT,
4569 ),
4570 KeyParameter::new(
4571 KeyParameterValue::Algorithm(Algorithm::RSA),
4572 SecurityLevel::TRUSTED_ENVIRONMENT,
4573 ),
4574 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4575 KeyParameter::new(
4576 KeyParameterValue::BlockMode(BlockMode::ECB),
4577 SecurityLevel::TRUSTED_ENVIRONMENT,
4578 ),
4579 KeyParameter::new(
4580 KeyParameterValue::BlockMode(BlockMode::GCM),
4581 SecurityLevel::TRUSTED_ENVIRONMENT,
4582 ),
4583 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4584 KeyParameter::new(
4585 KeyParameterValue::Digest(Digest::MD5),
4586 SecurityLevel::TRUSTED_ENVIRONMENT,
4587 ),
4588 KeyParameter::new(
4589 KeyParameterValue::Digest(Digest::SHA_2_224),
4590 SecurityLevel::TRUSTED_ENVIRONMENT,
4591 ),
4592 KeyParameter::new(
4593 KeyParameterValue::Digest(Digest::SHA_2_256),
4594 SecurityLevel::STRONGBOX,
4595 ),
4596 KeyParameter::new(
4597 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4598 SecurityLevel::TRUSTED_ENVIRONMENT,
4599 ),
4600 KeyParameter::new(
4601 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4602 SecurityLevel::TRUSTED_ENVIRONMENT,
4603 ),
4604 KeyParameter::new(
4605 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4606 SecurityLevel::STRONGBOX,
4607 ),
4608 KeyParameter::new(
4609 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4610 SecurityLevel::TRUSTED_ENVIRONMENT,
4611 ),
4612 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4613 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4614 KeyParameter::new(
4615 KeyParameterValue::EcCurve(EcCurve::P_224),
4616 SecurityLevel::TRUSTED_ENVIRONMENT,
4617 ),
4618 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4619 KeyParameter::new(
4620 KeyParameterValue::EcCurve(EcCurve::P_384),
4621 SecurityLevel::TRUSTED_ENVIRONMENT,
4622 ),
4623 KeyParameter::new(
4624 KeyParameterValue::EcCurve(EcCurve::P_521),
4625 SecurityLevel::TRUSTED_ENVIRONMENT,
4626 ),
4627 KeyParameter::new(
4628 KeyParameterValue::RSAPublicExponent(3),
4629 SecurityLevel::TRUSTED_ENVIRONMENT,
4630 ),
4631 KeyParameter::new(
4632 KeyParameterValue::IncludeUniqueID,
4633 SecurityLevel::TRUSTED_ENVIRONMENT,
4634 ),
4635 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4636 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4637 KeyParameter::new(
4638 KeyParameterValue::ActiveDateTime(1234567890),
4639 SecurityLevel::STRONGBOX,
4640 ),
4641 KeyParameter::new(
4642 KeyParameterValue::OriginationExpireDateTime(1234567890),
4643 SecurityLevel::TRUSTED_ENVIRONMENT,
4644 ),
4645 KeyParameter::new(
4646 KeyParameterValue::UsageExpireDateTime(1234567890),
4647 SecurityLevel::TRUSTED_ENVIRONMENT,
4648 ),
4649 KeyParameter::new(
4650 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4651 SecurityLevel::TRUSTED_ENVIRONMENT,
4652 ),
4653 KeyParameter::new(
4654 KeyParameterValue::MaxUsesPerBoot(1234567890),
4655 SecurityLevel::TRUSTED_ENVIRONMENT,
4656 ),
4657 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004658 KeyParameter::new(
4659 KeyParameterValue::NoAuthRequired,
4660 SecurityLevel::TRUSTED_ENVIRONMENT,
4661 ),
4662 KeyParameter::new(
4663 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4664 SecurityLevel::TRUSTED_ENVIRONMENT,
4665 ),
4666 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4667 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4668 KeyParameter::new(
4669 KeyParameterValue::TrustedUserPresenceRequired,
4670 SecurityLevel::TRUSTED_ENVIRONMENT,
4671 ),
4672 KeyParameter::new(
4673 KeyParameterValue::TrustedConfirmationRequired,
4674 SecurityLevel::TRUSTED_ENVIRONMENT,
4675 ),
4676 KeyParameter::new(
4677 KeyParameterValue::UnlockedDeviceRequired,
4678 SecurityLevel::TRUSTED_ENVIRONMENT,
4679 ),
4680 KeyParameter::new(
4681 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4682 SecurityLevel::SOFTWARE,
4683 ),
4684 KeyParameter::new(
4685 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4686 SecurityLevel::SOFTWARE,
4687 ),
4688 KeyParameter::new(
4689 KeyParameterValue::CreationDateTime(12345677890),
4690 SecurityLevel::SOFTWARE,
4691 ),
4692 KeyParameter::new(
4693 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4694 SecurityLevel::TRUSTED_ENVIRONMENT,
4695 ),
4696 KeyParameter::new(
4697 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4698 SecurityLevel::TRUSTED_ENVIRONMENT,
4699 ),
4700 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4701 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4702 KeyParameter::new(
4703 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4704 SecurityLevel::SOFTWARE,
4705 ),
4706 KeyParameter::new(
4707 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4708 SecurityLevel::TRUSTED_ENVIRONMENT,
4709 ),
4710 KeyParameter::new(
4711 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4712 SecurityLevel::TRUSTED_ENVIRONMENT,
4713 ),
4714 KeyParameter::new(
4715 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4716 SecurityLevel::TRUSTED_ENVIRONMENT,
4717 ),
4718 KeyParameter::new(
4719 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4720 SecurityLevel::TRUSTED_ENVIRONMENT,
4721 ),
4722 KeyParameter::new(
4723 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4724 SecurityLevel::TRUSTED_ENVIRONMENT,
4725 ),
4726 KeyParameter::new(
4727 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4728 SecurityLevel::TRUSTED_ENVIRONMENT,
4729 ),
4730 KeyParameter::new(
4731 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4732 SecurityLevel::TRUSTED_ENVIRONMENT,
4733 ),
4734 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004735 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4736 SecurityLevel::TRUSTED_ENVIRONMENT,
4737 ),
4738 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004739 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4740 SecurityLevel::TRUSTED_ENVIRONMENT,
4741 ),
4742 KeyParameter::new(
4743 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4744 SecurityLevel::TRUSTED_ENVIRONMENT,
4745 ),
4746 KeyParameter::new(
4747 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4748 SecurityLevel::TRUSTED_ENVIRONMENT,
4749 ),
4750 KeyParameter::new(
4751 KeyParameterValue::VendorPatchLevel(3),
4752 SecurityLevel::TRUSTED_ENVIRONMENT,
4753 ),
4754 KeyParameter::new(
4755 KeyParameterValue::BootPatchLevel(4),
4756 SecurityLevel::TRUSTED_ENVIRONMENT,
4757 ),
4758 KeyParameter::new(
4759 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4760 SecurityLevel::TRUSTED_ENVIRONMENT,
4761 ),
4762 KeyParameter::new(
4763 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4764 SecurityLevel::TRUSTED_ENVIRONMENT,
4765 ),
4766 KeyParameter::new(
4767 KeyParameterValue::MacLength(256),
4768 SecurityLevel::TRUSTED_ENVIRONMENT,
4769 ),
4770 KeyParameter::new(
4771 KeyParameterValue::ResetSinceIdRotation,
4772 SecurityLevel::TRUSTED_ENVIRONMENT,
4773 ),
4774 KeyParameter::new(
4775 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4776 SecurityLevel::TRUSTED_ENVIRONMENT,
4777 ),
Qi Wub9433b52020-12-01 14:52:46 +08004778 ];
4779 if let Some(value) = max_usage_count {
4780 params.push(KeyParameter::new(
4781 KeyParameterValue::UsageCountLimit(value),
4782 SecurityLevel::SOFTWARE,
4783 ));
4784 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004785
4786 for sid in user_secure_ids.iter() {
4787 params.push(KeyParameter::new(
4788 KeyParameterValue::UserSecureID(*sid),
4789 SecurityLevel::STRONGBOX,
4790 ));
4791 }
Qi Wub9433b52020-12-01 14:52:46 +08004792 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004793 }
4794
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004795 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004796 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004797 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004798 namespace: i64,
4799 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004800 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004801 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004802 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4803 }
4804
4805 pub fn make_test_key_entry_with_sids(
4806 db: &mut KeystoreDB,
4807 domain: Domain,
4808 namespace: i64,
4809 alias: &str,
4810 max_usage_count: Option<i32>,
4811 sids: &[i64],
4812 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004813 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004814 let mut blob_metadata = BlobMetaData::new();
4815 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4816 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4817 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4818 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4819 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4820
4821 db.set_blob(
4822 &key_id,
4823 SubComponentType::KEY_BLOB,
4824 Some(TEST_KEY_BLOB),
4825 Some(&blob_metadata),
4826 )?;
4827 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4828 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004829
Eran Messeri4dc27b52024-01-09 12:43:31 +00004830 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004831 db.insert_keyparameter(&key_id, &params)?;
4832
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004833 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004834 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004835 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004836 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004837 Ok(key_id)
4838 }
4839
Qi Wub9433b52020-12-01 14:52:46 +08004840 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4841 let params = make_test_params(max_usage_count);
4842
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004843 let mut blob_metadata = BlobMetaData::new();
4844 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4845 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4846 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4847 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4848 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4849
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004850 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004851 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004852
4853 KeyEntry {
4854 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004855 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004856 cert: Some(TEST_CERT_BLOB.to_vec()),
4857 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004858 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004859 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004860 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004861 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004862 }
4863 }
4864
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004865 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004866 db: &mut KeystoreDB,
4867 domain: Domain,
4868 namespace: i64,
4869 alias: &str,
4870 logical_only: bool,
4871 ) -> Result<KeyIdGuard> {
4872 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4873 let mut blob_metadata = BlobMetaData::new();
4874 if !logical_only {
4875 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4876 }
4877 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4878
4879 db.set_blob(
4880 &key_id,
4881 SubComponentType::KEY_BLOB,
4882 Some(TEST_KEY_BLOB),
4883 Some(&blob_metadata),
4884 )?;
4885 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4886 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4887
4888 let mut params = make_test_params(None);
4889 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4890
4891 db.insert_keyparameter(&key_id, &params)?;
4892
4893 let mut metadata = KeyMetaData::new();
4894 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4895 db.insert_key_metadata(&key_id, &metadata)?;
4896 rebind_alias(db, &key_id, alias, domain, namespace)?;
4897 Ok(key_id)
4898 }
4899
Eric Biggersb0478cf2023-10-27 03:55:29 +00004900 // Creates an app key that is marked as being superencrypted by the given
4901 // super key ID and that has the given authentication and unlocked device
4902 // parameters. This does not actually superencrypt the key blob.
4903 fn make_superencrypted_key_entry(
4904 db: &mut KeystoreDB,
4905 namespace: i64,
4906 alias: &str,
4907 requires_authentication: bool,
4908 requires_unlocked_device: bool,
4909 super_key_id: i64,
4910 ) -> Result<KeyIdGuard> {
4911 let domain = Domain::APP;
4912 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4913
4914 let mut blob_metadata = BlobMetaData::new();
4915 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4916 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4917 db.set_blob(
4918 &key_id,
4919 SubComponentType::KEY_BLOB,
4920 Some(TEST_KEY_BLOB),
4921 Some(&blob_metadata),
4922 )?;
4923
4924 let mut params = vec![];
4925 if requires_unlocked_device {
4926 params.push(KeyParameter::new(
4927 KeyParameterValue::UnlockedDeviceRequired,
4928 SecurityLevel::TRUSTED_ENVIRONMENT,
4929 ));
4930 }
4931 if requires_authentication {
4932 params.push(KeyParameter::new(
4933 KeyParameterValue::UserSecureID(42),
4934 SecurityLevel::TRUSTED_ENVIRONMENT,
4935 ));
4936 }
4937 db.insert_keyparameter(&key_id, &params)?;
4938
4939 let mut metadata = KeyMetaData::new();
4940 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4941 db.insert_key_metadata(&key_id, &metadata)?;
4942
4943 rebind_alias(db, &key_id, alias, domain, namespace)?;
4944 Ok(key_id)
4945 }
4946
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004947 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4948 let mut params = make_test_params(None);
4949 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4950
4951 let mut blob_metadata = BlobMetaData::new();
4952 if !logical_only {
4953 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4954 }
4955 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4956
4957 let mut metadata = KeyMetaData::new();
4958 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4959
4960 KeyEntry {
4961 id: key_id,
4962 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4963 cert: Some(TEST_CERT_BLOB.to_vec()),
4964 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4965 km_uuid: KEYSTORE_UUID,
4966 parameters: params,
4967 metadata,
4968 pure_cert: false,
4969 }
4970 }
4971
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004972 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004973 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004974 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004975 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004976 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004977 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004978 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004979 Ok((
4980 row.get(0)?,
4981 row.get(1)?,
4982 row.get(2)?,
4983 row.get(3)?,
4984 row.get(4)?,
4985 row.get(5)?,
4986 row.get(6)?,
4987 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004988 },
4989 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004990
4991 println!("Key entry table rows:");
4992 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004993 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004994 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004995 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4996 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004997 );
4998 }
4999 Ok(())
5000 }
5001
5002 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005003 let mut stmt = db
5004 .conn
5005 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005006 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005007 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5008 })?;
5009
5010 println!("Grant table rows:");
5011 for r in rows {
5012 let (id, gt, ki, av) = r.unwrap();
5013 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5014 }
5015 Ok(())
5016 }
5017
Joel Galenson0891bc12020-07-20 10:37:03 -07005018 // Use a custom random number generator that repeats each number once.
5019 // This allows us to test repeated elements.
5020
5021 thread_local! {
Charisee43391152024-04-02 16:16:30 +00005022 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07005023 }
5024
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005025 fn reset_random() {
5026 RANDOM_COUNTER.with(|counter| {
5027 *counter.borrow_mut() = 0;
5028 })
5029 }
5030
Joel Galenson0891bc12020-07-20 10:37:03 -07005031 pub fn random() -> i64 {
5032 RANDOM_COUNTER.with(|counter| {
5033 let result = *counter.borrow() / 2;
5034 *counter.borrow_mut() += 1;
5035 result
5036 })
5037 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005038
5039 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005040 fn test_unbind_keys_for_user() -> Result<()> {
5041 let mut db = new_test_db()?;
5042 db.unbind_keys_for_user(1, false)?;
5043
5044 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5045 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5046 db.unbind_keys_for_user(2, false)?;
5047
Eran Messeri24f31972023-01-25 17:00:33 +00005048 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
5049 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005050
5051 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00005052 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005053
5054 Ok(())
5055 }
5056
5057 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005058 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5059 let mut db = new_test_db()?;
5060 let super_key = keystore2_crypto::generate_aes256_key()?;
5061 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5062 let (encrypted_super_key, metadata) =
5063 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5064
5065 let key_name_enc = SuperKeyType {
5066 alias: "test_super_key_1",
5067 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005068 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005069 };
5070
5071 let key_name_nonenc = SuperKeyType {
5072 alias: "test_super_key_2",
5073 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005074 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005075 };
5076
5077 // Install two super keys.
5078 db.store_super_key(
5079 1,
5080 &key_name_nonenc,
5081 &super_key,
5082 &BlobMetaData::new(),
5083 &KeyMetaData::new(),
5084 )?;
5085 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5086
5087 // Check that both can be found in the database.
5088 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5089 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5090
5091 // Install the same keys for a different user.
5092 db.store_super_key(
5093 2,
5094 &key_name_nonenc,
5095 &super_key,
5096 &BlobMetaData::new(),
5097 &KeyMetaData::new(),
5098 )?;
5099 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5100
5101 // Check that the second pair of keys can be found in the database.
5102 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5103 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5104
5105 // Delete only encrypted keys.
5106 db.unbind_keys_for_user(1, true)?;
5107
5108 // The encrypted superkey should be gone now.
5109 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5110 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5111
5112 // Reinsert the encrypted key.
5113 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5114
5115 // Check that both can be found in the database, again..
5116 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5117 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5118
5119 // Delete all even unencrypted keys.
5120 db.unbind_keys_for_user(1, false)?;
5121
5122 // Both should be gone now.
5123 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5124 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5125
5126 // Check that the second pair of keys was untouched.
5127 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5128 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5129
5130 Ok(())
5131 }
5132
Eric Biggersb0478cf2023-10-27 03:55:29 +00005133 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5134 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5135 }
5136
5137 // Tests the unbind_auth_bound_keys_for_user() function.
5138 #[test]
5139 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5140 let mut db = new_test_db()?;
5141 let user_id = 1;
5142 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5143 let other_user_id = 2;
5144 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5145 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5146
5147 // Create a superencryption key.
5148 let super_key = keystore2_crypto::generate_aes256_key()?;
5149 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5150 let (encrypted_super_key, blob_metadata) =
5151 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5152 db.store_super_key(
5153 user_id,
5154 super_key_type,
5155 &encrypted_super_key,
5156 &blob_metadata,
5157 &KeyMetaData::new(),
5158 )?;
5159 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5160
5161 // Store 4 superencrypted app keys, one for each possible combination of
5162 // (authentication required, unlocked device required).
5163 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5164 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5165 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5166 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5167 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5168 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5169 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5170 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5171
5172 // Also store a key for a different user that requires authentication.
5173 make_superencrypted_key_entry(
5174 &mut db,
5175 other_user_nspace,
5176 "auth_ud",
5177 true,
5178 true,
5179 super_key_id,
5180 )?;
5181
5182 db.unbind_auth_bound_keys_for_user(user_id)?;
5183
5184 // Verify that only the user's app keys that require authentication were
5185 // deleted. Keys that require an unlocked device but not authentication
5186 // should *not* have been deleted, nor should the super key have been
5187 // deleted, nor should other users' keys have been deleted.
5188 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5189 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5190 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5191 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5192 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5193 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5194
5195 Ok(())
5196 }
5197
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005198 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005199 fn test_store_super_key() -> Result<()> {
5200 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005201 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005202 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005203 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005204 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005205 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005206
5207 let (encrypted_super_key, metadata) =
5208 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005209 db.store_super_key(
5210 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005211 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005212 &encrypted_super_key,
5213 &metadata,
5214 &KeyMetaData::new(),
5215 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005216
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005217 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005218 assert!(db.key_exists(
5219 Domain::APP,
5220 1,
5221 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5222 KeyType::Super
5223 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005224
Eric Biggers673d34a2023-10-18 01:54:18 +00005225 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005226 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005227 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005228 key_entry,
5229 &pw,
5230 None,
5231 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005232
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005233 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005234 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005235
Hasini Gunasingheda895552021-01-27 19:34:37 +00005236 Ok(())
5237 }
Seth Moore78c091f2021-04-09 21:38:30 +00005238
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005239 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005240 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005241 MetricsStorage::KEY_ENTRY,
5242 MetricsStorage::KEY_ENTRY_ID_INDEX,
5243 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5244 MetricsStorage::BLOB_ENTRY,
5245 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5246 MetricsStorage::KEY_PARAMETER,
5247 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5248 MetricsStorage::KEY_METADATA,
5249 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5250 MetricsStorage::GRANT,
5251 MetricsStorage::AUTH_TOKEN,
5252 MetricsStorage::BLOB_METADATA,
5253 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005254 ]
5255 }
5256
5257 /// Perform a simple check to ensure that we can query all the storage types
5258 /// that are supported by the DB. Check for reasonable values.
5259 #[test]
5260 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005261 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005262
5263 let mut db = new_test_db()?;
5264
5265 for t in get_valid_statsd_storage_types() {
5266 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005267 // AuthToken can be less than a page since it's in a btree, not sqlite
5268 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005269 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005270 } else {
5271 assert!(stat.size >= PAGE_SIZE);
5272 }
Seth Moore78c091f2021-04-09 21:38:30 +00005273 assert!(stat.size >= stat.unused_size);
5274 }
5275
5276 Ok(())
5277 }
5278
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005279 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005280 get_valid_statsd_storage_types()
5281 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005282 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005283 .collect()
5284 }
5285
5286 fn assert_storage_increased(
5287 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005288 increased_storage_types: Vec<MetricsStorage>,
5289 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005290 ) {
5291 for storage in increased_storage_types {
5292 // Verify the expected storage increased.
5293 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005294 let old = &baseline[&storage.0];
5295 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005296 assert!(
5297 new.unused_size <= old.unused_size,
5298 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005299 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005300 new.unused_size,
5301 old.unused_size
5302 );
5303
5304 // Update the baseline with the new value so that it succeeds in the
5305 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005306 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005307 }
5308
5309 // Get an updated map of the storage and verify there were no unexpected changes.
5310 let updated_stats = get_storage_stats_map(db);
5311 assert_eq!(updated_stats.len(), baseline.len());
5312
5313 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005314 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005315 let mut s = String::new();
5316 for &k in map.keys() {
5317 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5318 .expect("string concat failed");
5319 }
5320 s
5321 };
5322
5323 assert!(
5324 updated_stats[&k].size == baseline[&k].size
5325 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5326 "updated_stats:\n{}\nbaseline:\n{}",
5327 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005328 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005329 );
5330 }
5331 }
5332
5333 #[test]
5334 fn test_verify_key_table_size_reporting() -> Result<()> {
5335 let mut db = new_test_db()?;
5336 let mut working_stats = get_storage_stats_map(&mut db);
5337
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005338 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005339 assert_storage_increased(
5340 &mut db,
5341 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005342 MetricsStorage::KEY_ENTRY,
5343 MetricsStorage::KEY_ENTRY_ID_INDEX,
5344 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005345 ],
5346 &mut working_stats,
5347 );
5348
5349 let mut blob_metadata = BlobMetaData::new();
5350 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5351 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5352 assert_storage_increased(
5353 &mut db,
5354 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005355 MetricsStorage::BLOB_ENTRY,
5356 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5357 MetricsStorage::BLOB_METADATA,
5358 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005359 ],
5360 &mut working_stats,
5361 );
5362
5363 let params = make_test_params(None);
5364 db.insert_keyparameter(&key_id, &params)?;
5365 assert_storage_increased(
5366 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005367 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005368 &mut working_stats,
5369 );
5370
5371 let mut metadata = KeyMetaData::new();
5372 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5373 db.insert_key_metadata(&key_id, &metadata)?;
5374 assert_storage_increased(
5375 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005376 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005377 &mut working_stats,
5378 );
5379
5380 let mut sum = 0;
5381 for stat in working_stats.values() {
5382 sum += stat.size;
5383 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005384 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005385 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5386
5387 Ok(())
5388 }
5389
5390 #[test]
5391 fn test_verify_auth_table_size_reporting() -> Result<()> {
5392 let mut db = new_test_db()?;
5393 let mut working_stats = get_storage_stats_map(&mut db);
5394 db.insert_auth_token(&HardwareAuthToken {
5395 challenge: 123,
5396 userId: 456,
5397 authenticatorId: 789,
5398 authenticatorType: kmhw_authenticator_type::ANY,
5399 timestamp: Timestamp { milliSeconds: 10 },
5400 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005401 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005402 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005403 Ok(())
5404 }
5405
5406 #[test]
5407 fn test_verify_grant_table_size_reporting() -> Result<()> {
5408 const OWNER: i64 = 1;
5409 let mut db = new_test_db()?;
5410 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5411
5412 let mut working_stats = get_storage_stats_map(&mut db);
5413 db.grant(
5414 &KeyDescriptor {
5415 domain: Domain::APP,
5416 nspace: 0,
5417 alias: Some(TEST_ALIAS.to_string()),
5418 blob: None,
5419 },
5420 OWNER as u32,
5421 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005422 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005423 |_, _| Ok(()),
5424 )?;
5425
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005426 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005427
5428 Ok(())
5429 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005430
5431 #[test]
5432 fn find_auth_token_entry_returns_latest() -> Result<()> {
5433 let mut db = new_test_db()?;
5434 db.insert_auth_token(&HardwareAuthToken {
5435 challenge: 123,
5436 userId: 456,
5437 authenticatorId: 789,
5438 authenticatorType: kmhw_authenticator_type::ANY,
5439 timestamp: Timestamp { milliSeconds: 10 },
5440 mac: b"mac0".to_vec(),
5441 });
5442 std::thread::sleep(std::time::Duration::from_millis(1));
5443 db.insert_auth_token(&HardwareAuthToken {
5444 challenge: 123,
5445 userId: 457,
5446 authenticatorId: 789,
5447 authenticatorType: kmhw_authenticator_type::ANY,
5448 timestamp: Timestamp { milliSeconds: 12 },
5449 mac: b"mac1".to_vec(),
5450 });
5451 std::thread::sleep(std::time::Duration::from_millis(1));
5452 db.insert_auth_token(&HardwareAuthToken {
5453 challenge: 123,
5454 userId: 458,
5455 authenticatorId: 789,
5456 authenticatorType: kmhw_authenticator_type::ANY,
5457 timestamp: Timestamp { milliSeconds: 3 },
5458 mac: b"mac2".to_vec(),
5459 });
5460 // All three entries are in the database
5461 assert_eq!(db.perboot.auth_tokens_len(), 3);
5462 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005463 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005464 Ok(())
5465 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005466
5467 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005468 fn test_load_key_descriptor() -> Result<()> {
5469 let mut db = new_test_db()?;
5470 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5471
5472 let key = db.load_key_descriptor(key_id)?.unwrap();
5473
5474 assert_eq!(key.domain, Domain::APP);
5475 assert_eq!(key.nspace, 1);
5476 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5477
5478 // No such id
5479 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5480 Ok(())
5481 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005482
5483 #[test]
5484 fn test_get_list_app_uids_for_sid() -> Result<()> {
5485 let uid: i32 = 1;
5486 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5487 let first_sid = 667;
5488 let second_sid = 669;
5489 let first_app_id: i64 = 123 + uid_offset;
5490 let second_app_id: i64 = 456 + uid_offset;
5491 let third_app_id: i64 = 789 + uid_offset;
5492 let unrelated_app_id: i64 = 1011 + uid_offset;
5493 let mut db = new_test_db()?;
5494 make_test_key_entry_with_sids(
5495 &mut db,
5496 Domain::APP,
5497 first_app_id,
5498 TEST_ALIAS,
5499 None,
5500 &[first_sid],
5501 )
5502 .context("test_get_list_app_uids_for_sid")?;
5503 make_test_key_entry_with_sids(
5504 &mut db,
5505 Domain::APP,
5506 second_app_id,
5507 "alias2",
5508 None,
5509 &[first_sid],
5510 )
5511 .context("test_get_list_app_uids_for_sid")?;
5512 make_test_key_entry_with_sids(
5513 &mut db,
5514 Domain::APP,
5515 second_app_id,
5516 TEST_ALIAS,
5517 None,
5518 &[second_sid],
5519 )
5520 .context("test_get_list_app_uids_for_sid")?;
5521 make_test_key_entry_with_sids(
5522 &mut db,
5523 Domain::APP,
5524 third_app_id,
5525 "alias3",
5526 None,
5527 &[second_sid],
5528 )
5529 .context("test_get_list_app_uids_for_sid")?;
5530 make_test_key_entry_with_sids(
5531 &mut db,
5532 Domain::APP,
5533 unrelated_app_id,
5534 TEST_ALIAS,
5535 None,
5536 &[],
5537 )
5538 .context("test_get_list_app_uids_for_sid")?;
5539
5540 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5541 first_sid_apps.sort();
5542 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5543 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5544 second_sid_apps.sort();
5545 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5546 Ok(())
5547 }
5548
5549 #[test]
5550 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5551 let uid: i32 = 1;
5552 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5553 let first_sid = 667;
5554 let second_sid = 669;
5555 let third_sid = 772;
5556 let first_app_id: i64 = 123 + uid_offset;
5557 let second_app_id: i64 = 456 + uid_offset;
5558 let mut db = new_test_db()?;
5559 make_test_key_entry_with_sids(
5560 &mut db,
5561 Domain::APP,
5562 first_app_id,
5563 TEST_ALIAS,
5564 None,
5565 &[first_sid, second_sid],
5566 )
5567 .context("test_get_list_app_uids_for_sid")?;
5568 make_test_key_entry_with_sids(
5569 &mut db,
5570 Domain::APP,
5571 second_app_id,
5572 "alias2",
5573 None,
5574 &[second_sid, third_sid],
5575 )
5576 .context("test_get_list_app_uids_for_sid")?;
5577
5578 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5579 assert_eq!(first_sid_apps, vec![first_app_id]);
5580
5581 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5582 second_sid_apps.sort();
5583 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5584
5585 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5586 assert_eq!(third_sid_apps, vec![second_app_id]);
5587 Ok(())
5588 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005589}