blob: b526daace63e569c92ce525312a3f30322ce9649 [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.
848pub struct PerBootDbKeepAlive(Connection);
849
Joel Galenson26f4d012020-07-17 14:57:21 -0700850impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800851 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700852 const CURRENT_DB_VERSION: u32 = 1;
853 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854
Seth Moore78c091f2021-04-09 21:38:30 +0000855 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700856 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000857
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700858 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800859 /// files persistent.sqlite and perboot.sqlite in the given directory.
860 /// It also attempts to initialize all of the tables.
861 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700862 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700863 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700864 let _wp = wd::watch_millis("KeystoreDB::new", 500);
865
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700866 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700867 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700869 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700871 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000872 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800873 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 })?;
875 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700876 }
877
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700878 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
879 // cryptographic binding to the boot level keys was implemented.
880 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
881 tx.execute(
882 "UPDATE persistent.keyentry SET state = ?
883 WHERE
884 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
885 AND
886 id NOT IN (
887 SELECT keyentryid FROM persistent.blobentry
888 WHERE id IN (
889 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
890 )
891 );",
892 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
893 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000894 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700895 Ok(1)
896 }
897
Janis Danisevskis66784c42021-01-27 08:40:25 -0800898 fn init_tables(tx: &Transaction) -> Result<()> {
899 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700900 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700901 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800902 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700903 domain INTEGER,
904 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800905 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800906 state INTEGER,
907 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000908 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 )
910 .context("Failed to initialize \"keyentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
914 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000915 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800916 )
917 .context("Failed to create index keyentry_id_index.")?;
918
919 tx.execute(
920 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
921 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000922 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800923 )
924 .context("Failed to create index keyentry_domain_namespace_index.")?;
925
926 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700927 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
928 id INTEGER PRIMARY KEY,
929 subcomponent_type INTEGER,
930 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800931 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000932 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700933 )
934 .context("Failed to initialize \"blobentry\" table.")?;
935
Janis Danisevskis66784c42021-01-27 08:40:25 -0800936 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800937 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
938 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000939 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800940 )
941 .context("Failed to create index blobentry_keyentryid_index.")?;
942
943 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800944 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
945 id INTEGER PRIMARY KEY,
946 blobentryid INTEGER,
947 tag INTEGER,
948 data ANY,
949 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000950 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800951 )
952 .context("Failed to initialize \"blobmetadata\" table.")?;
953
954 tx.execute(
955 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
956 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000957 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800958 )
959 .context("Failed to create index blobmetadata_blobentryid_index.")?;
960
961 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700962 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000963 keyentryid INTEGER,
964 tag INTEGER,
965 data ANY,
966 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000967 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700968 )
969 .context("Failed to initialize \"keyparameter\" table.")?;
970
Janis Danisevskis66784c42021-01-27 08:40:25 -0800971 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800972 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
973 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000974 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800975 )
976 .context("Failed to create index keyparameter_keyentryid_index.")?;
977
978 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800979 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
980 keyentryid INTEGER,
981 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000982 data ANY,
983 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000984 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800985 )
986 .context("Failed to initialize \"keymetadata\" table.")?;
987
Janis Danisevskis66784c42021-01-27 08:40:25 -0800988 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800989 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
990 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000991 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800992 )
993 .context("Failed to create index keymetadata_keyentryid_index.")?;
994
995 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800996 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700997 id INTEGER UNIQUE,
998 grantee INTEGER,
999 keyentryid INTEGER,
1000 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001001 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001002 )
1003 .context("Failed to initialize \"grant\" table.")?;
1004
Joel Galenson0891bc12020-07-20 10:37:03 -07001005 Ok(())
1006 }
1007
Seth Moore472fcbb2021-05-12 10:07:51 -07001008 fn make_persistent_path(db_root: &Path) -> Result<String> {
1009 // Build the path to the sqlite file.
1010 let mut persistent_path = db_root.to_path_buf();
1011 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1012
1013 // Now convert them to strings prefixed with "file:"
1014 let mut persistent_path_str = "file:".to_owned();
1015 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1016
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001017 // Connect to database in specific mode
1018 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1019 "?journal_mode=WAL".to_owned()
1020 } else {
1021 "?journal_mode=DELETE".to_owned()
1022 };
1023 persistent_path_str.push_str(&persistent_path_mode);
1024
Seth Moore472fcbb2021-05-12 10:07:51 -07001025 Ok(persistent_path_str)
1026 }
1027
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001028 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001029 let conn =
1030 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1031
Janis Danisevskis66784c42021-01-27 08:40:25 -08001032 loop {
1033 if let Err(e) = conn
1034 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1035 .context("Failed to attach database persistent.")
1036 {
1037 if Self::is_locked_error(&e) {
1038 std::thread::sleep(std::time::Duration::from_micros(500));
1039 continue;
1040 } else {
1041 return Err(e);
1042 }
1043 }
1044 break;
1045 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001046
Matthew Maurer4fb19112021-05-06 15:40:44 -07001047 // Drop the cache size from default (2M) to 0.5M
1048 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1049 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001050
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001051 Ok(conn)
1052 }
1053
Seth Moore78c091f2021-04-09 21:38:30 +00001054 fn do_table_size_query(
1055 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001056 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001057 query: &str,
1058 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001059 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001060 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001061 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001062 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001063 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001064 })
1065 .no_gc()
1066 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001067 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001068 }
1069
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001070 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001071 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001072 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001073 "SELECT page_count * page_size, freelist_count * page_size
1074 FROM pragma_page_count('persistent'),
1075 pragma_page_size('persistent'),
1076 persistent.pragma_freelist_count();",
1077 &[],
1078 )
1079 }
1080
1081 fn get_table_size(
1082 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001083 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001084 schema: &str,
1085 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001086 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001087 self.do_table_size_query(
1088 storage_type,
1089 "SELECT pgsize,unused FROM dbstat(?1)
1090 WHERE name=?2 AND aggregate=TRUE;",
1091 &[schema, table],
1092 )
1093 }
1094
1095 /// Fetches a storage statisitics atom for a given storage type. For storage
1096 /// types that map to a table, information about the table's storage is
1097 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001098 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001099 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1100
Seth Moore78c091f2021-04-09 21:38:30 +00001101 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001102 MetricsStorage::DATABASE => self.get_total_size(),
1103 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001104 self.get_table_size(storage_type, "persistent", "keyentry")
1105 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001106 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001107 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1108 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001109 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001110 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1111 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001112 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001113 self.get_table_size(storage_type, "persistent", "blobentry")
1114 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001115 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001116 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1117 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001118 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001119 self.get_table_size(storage_type, "persistent", "keyparameter")
1120 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001121 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001122 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1123 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001124 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001125 self.get_table_size(storage_type, "persistent", "keymetadata")
1126 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001128 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1129 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1131 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001132 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1133 // reportable
1134 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001135 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001136 storage_type,
1137 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001138 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001139 unused_size: 0,
1140 })
Seth Moore78c091f2021-04-09 21:38:30 +00001141 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001142 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001143 self.get_table_size(storage_type, "persistent", "blobmetadata")
1144 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001145 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001146 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1147 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001148 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001149 }
1150 }
1151
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001152 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001153 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1154 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001155 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1156 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001157 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001158 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001159 blob_ids_to_delete: &[i64],
1160 max_blobs: usize,
1161 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001162 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001163 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001164 // Delete the given blobs.
1165 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001166 tx.execute(
1167 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001168 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001169 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001170 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001171 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001172 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001173 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001174
1175 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1176
Janis Danisevskis3395f862021-05-06 10:54:17 -07001177 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1178 let result: Vec<(i64, Vec<u8>)> = {
1179 let mut stmt = tx
1180 .prepare(
1181 "SELECT id, blob FROM persistent.blobentry
1182 WHERE subcomponent_type = ?
1183 AND (
1184 id NOT IN (
1185 SELECT MAX(id) FROM persistent.blobentry
1186 WHERE subcomponent_type = ?
1187 GROUP BY keyentryid, subcomponent_type
1188 )
1189 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1190 ) LIMIT ?;",
1191 )
1192 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001193
Janis Danisevskis3395f862021-05-06 10:54:17 -07001194 let rows = stmt
1195 .query_map(
1196 params![
1197 SubComponentType::KEY_BLOB,
1198 SubComponentType::KEY_BLOB,
1199 max_blobs as i64,
1200 ],
1201 |row| Ok((row.get(0)?, row.get(1)?)),
1202 )
1203 .context("Trying to query superseded blob.")?;
1204
1205 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1206 .context("Trying to extract superseded blobs.")?
1207 };
1208
1209 let result = result
1210 .into_iter()
1211 .map(|(blob_id, blob)| {
1212 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1213 })
1214 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1215 .context("Trying to load blob metadata.")?;
1216 if !result.is_empty() {
1217 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001218 }
1219
1220 // We did not find any superseded key blob, so let's remove other superseded blob in
1221 // one transaction.
1222 tx.execute(
1223 "DELETE FROM persistent.blobentry
1224 WHERE NOT subcomponent_type = ?
1225 AND (
1226 id NOT IN (
1227 SELECT MAX(id) FROM persistent.blobentry
1228 WHERE NOT subcomponent_type = ?
1229 GROUP BY keyentryid, subcomponent_type
1230 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1231 );",
1232 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1233 )
1234 .context("Trying to purge superseded blobs.")?;
1235
Janis Danisevskis3395f862021-05-06 10:54:17 -07001236 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001237 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001238 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001239 }
1240
1241 /// This maintenance function should be called only once before the database is used for the
1242 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1243 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1244 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1245 /// Keystore crashed at some point during key generation. Callers may want to log such
1246 /// occurrences.
1247 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1248 /// it to `KeyLifeCycle::Live` may have grants.
1249 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001250 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1251
Janis Danisevskis66784c42021-01-27 08:40:25 -08001252 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1253 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001254 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1255 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1256 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001257 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001258 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001259 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001260 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001261 }
1262
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001263 /// Checks if a key exists with given key type and key descriptor properties.
1264 pub fn key_exists(
1265 &mut self,
1266 domain: Domain,
1267 nspace: i64,
1268 alias: &str,
1269 key_type: KeyType,
1270 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001271 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1272
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001273 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1274 let key_descriptor =
1275 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001276 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001277 match result {
1278 Ok(_) => Ok(true),
1279 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1280 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001281 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001282 },
1283 }
1284 .no_gc()
1285 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001286 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001287 }
1288
Hasini Gunasingheda895552021-01-27 19:34:37 +00001289 /// Stores a super key in the database.
1290 pub fn store_super_key(
1291 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001292 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001293 key_type: &SuperKeyType,
1294 blob: &[u8],
1295 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001296 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001297 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001298 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1299
Hasini Gunasingheda895552021-01-27 19:34:37 +00001300 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1301 let key_id = Self::insert_with_retry(|id| {
1302 tx.execute(
1303 "INSERT into persistent.keyentry
1304 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001305 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001306 params![
1307 id,
1308 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001309 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001310 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001311 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001312 KeyLifeCycle::Live,
1313 &KEYSTORE_UUID,
1314 ],
1315 )
1316 })
1317 .context("Failed to insert into keyentry table.")?;
1318
Paul Crowley8d5b2532021-03-19 10:53:07 -07001319 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1320
Hasini Gunasingheda895552021-01-27 19:34:37 +00001321 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001322 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001323 key_id,
1324 SubComponentType::KEY_BLOB,
1325 Some(blob),
1326 Some(blob_metadata),
1327 )
1328 .context("Failed to store key blob.")?;
1329
1330 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1331 .context("Trying to load key components.")
1332 .no_gc()
1333 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001334 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001335 }
1336
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001337 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001338 pub fn load_super_key(
1339 &mut self,
1340 key_type: &SuperKeyType,
1341 user_id: u32,
1342 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001343 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1344
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001345 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1346 let key_descriptor = KeyDescriptor {
1347 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001348 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001349 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001350 blob: None,
1351 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001352 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001353 match id {
1354 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001355 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001356 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001357 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1358 }
1359 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1360 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001361 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001362 },
1363 }
1364 .no_gc()
1365 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001366 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001367 }
1368
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001369 /// Atomically loads a key entry and associated metadata or creates it using the
1370 /// callback create_new_key callback. The callback is called during a database
1371 /// transaction. This means that implementers should be mindful about using
1372 /// blocking operations such as IPC or grabbing mutexes.
1373 pub fn get_or_create_key_with<F>(
1374 &mut self,
1375 domain: Domain,
1376 namespace: i64,
1377 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001378 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001379 create_new_key: F,
1380 ) -> Result<(KeyIdGuard, KeyEntry)>
1381 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001382 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001383 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001384 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1385
Janis Danisevskis66784c42021-01-27 08:40:25 -08001386 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1387 let id = {
1388 let mut stmt = tx
1389 .prepare(
1390 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001391 WHERE
1392 key_type = ?
1393 AND domain = ?
1394 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001395 AND alias = ?
1396 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001398 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001399 let mut rows = stmt
1400 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001401 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001402
Janis Danisevskis66784c42021-01-27 08:40:25 -08001403 db_utils::with_rows_extract_one(&mut rows, |row| {
1404 Ok(match row {
1405 Some(r) => r.get(0).context("Failed to unpack id.")?,
1406 None => None,
1407 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001408 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001409 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001410 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001411
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 let (id, entry) = match id {
1413 Some(id) => (
1414 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001415 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001417
Janis Danisevskis66784c42021-01-27 08:40:25 -08001418 None => {
1419 let id = Self::insert_with_retry(|id| {
1420 tx.execute(
1421 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001422 (id, key_type, domain, namespace, alias, state, km_uuid)
1423 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 params![
1425 id,
1426 KeyType::Super,
1427 domain.0,
1428 namespace,
1429 alias,
1430 KeyLifeCycle::Live,
1431 km_uuid,
1432 ],
1433 )
1434 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001435 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001436
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001437 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001438 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001439 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001440 id,
1441 SubComponentType::KEY_BLOB,
1442 Some(&blob),
1443 Some(&metadata),
1444 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001445 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001446 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001447 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001448 KeyEntry {
1449 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001450 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001451 pure_cert: false,
1452 ..Default::default()
1453 },
1454 )
1455 }
1456 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001457 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001458 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001459 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001460 }
1461
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001462 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001463 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1464 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001465 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1466 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001467 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001468 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001469 loop {
1470 match self
1471 .conn
1472 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001473 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001474 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1475 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001476 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001477 Ok(result)
1478 }) {
1479 Ok(result) => break Ok(result),
1480 Err(e) => {
1481 if Self::is_locked_error(&e) {
1482 std::thread::sleep(std::time::Duration::from_micros(500));
1483 continue;
1484 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001485 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001486 }
1487 }
1488 }
1489 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001490 .map(|(need_gc, result)| {
1491 if need_gc {
1492 if let Some(ref gc) = self.gc {
1493 gc.notify_gc();
1494 }
1495 }
1496 result
1497 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001498 }
1499
1500 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001501 matches!(
1502 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1503 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1504 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1505 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001506 }
1507
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001508 /// Creates a new key entry and allocates a new randomized id for the new key.
1509 /// The key id gets associated with a domain and namespace but not with an alias.
1510 /// To complete key generation `rebind_alias` should be called after all of the
1511 /// key artifacts, i.e., blobs and parameters have been associated with the new
1512 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1513 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001514 pub fn create_key_entry(
1515 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001516 domain: &Domain,
1517 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001518 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001519 km_uuid: &Uuid,
1520 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001521 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1522
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001523 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001524 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001526 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001527 }
1528
1529 fn create_key_entry_internal(
1530 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001531 domain: &Domain,
1532 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001533 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001534 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001535 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001536 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001537 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001538 _ => {
1539 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001540 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001541 }
1542 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001543 Ok(KEY_ID_LOCK.get(
1544 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001545 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001546 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001547 (id, key_type, domain, namespace, alias, state, km_uuid)
1548 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 params![
1550 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001551 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001553 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001554 KeyLifeCycle::Existing,
1555 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001556 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001557 )
1558 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001559 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001560 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001561 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001562
Janis Danisevskis377d1002021-01-27 19:07:48 -08001563 /// Set a new blob and associates it with the given key id. Each blob
1564 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001565 /// Each key can have one of each sub component type associated. If more
1566 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001567 /// will get garbage collected.
1568 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1569 /// removed by setting blob to None.
1570 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001571 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001572 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001573 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001574 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001575 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001576 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001577 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1578
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001579 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001580 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001581 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001582 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001583 }
1584
Janis Danisevskiseed69842021-02-18 20:04:10 -08001585 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1586 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1587 /// We use this to insert key blobs into the database which can then be garbage collected
1588 /// lazily by the key garbage collector.
1589 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001590 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1591
Janis Danisevskiseed69842021-02-18 20:04:10 -08001592 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1593 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001594 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001595 Self::UNASSIGNED_KEY_ID,
1596 SubComponentType::KEY_BLOB,
1597 Some(blob),
1598 Some(blob_metadata),
1599 )
1600 .need_gc()
1601 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001602 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001603 }
1604
Janis Danisevskis377d1002021-01-27 19:07:48 -08001605 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001606 tx: &Transaction,
1607 key_id: i64,
1608 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001609 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001610 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001611 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001612 match (blob, sc_type) {
1613 (Some(blob), _) => {
1614 tx.execute(
1615 "INSERT INTO persistent.blobentry
1616 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1617 params![sc_type, key_id, blob],
1618 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001619 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001620 if let Some(blob_metadata) = blob_metadata {
1621 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001622 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001623 row.get(0)
1624 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001625 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 blob_metadata
1627 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001628 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001629 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001630 }
1631 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1632 tx.execute(
1633 "DELETE FROM persistent.blobentry
1634 WHERE subcomponent_type = ? AND keyentryid = ?;",
1635 params![sc_type, key_id],
1636 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001637 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001638 }
1639 (None, _) => {
1640 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001641 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001642 }
1643 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001644 Ok(())
1645 }
1646
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001647 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1648 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001649 #[cfg(test)]
1650 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001651 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001652 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001653 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001654 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001655 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001656
Janis Danisevskis66784c42021-01-27 08:40:25 -08001657 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001658 tx: &Transaction,
1659 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001660 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001661 ) -> Result<()> {
1662 let mut stmt = tx
1663 .prepare(
1664 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1665 VALUES (?, ?, ?, ?);",
1666 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001667 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001668
Janis Danisevskis66784c42021-01-27 08:40:25 -08001669 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001670 stmt.insert(params![
1671 key_id.0,
1672 p.get_tag().0,
1673 p.key_parameter_value(),
1674 p.security_level().0
1675 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001676 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001677 }
1678 Ok(())
1679 }
1680
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001681 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001682 #[cfg(test)]
1683 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001684 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001685 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001686 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001687 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001688 }
1689
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001690 /// Updates the alias column of the given key id `newid` with the given alias,
1691 /// and atomically, removes the alias, domain, and namespace from another row
1692 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001693 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1694 /// collector.
1695 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001696 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001697 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001698 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001699 domain: &Domain,
1700 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001701 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001702 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001703 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001704 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001705 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001706 return Err(KsError::sys())
1707 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001708 }
1709 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001710 let updated = tx
1711 .execute(
1712 "UPDATE persistent.keyentry
1713 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001714 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1715 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001716 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001717 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001718 let result = tx
1719 .execute(
1720 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001721 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001722 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001723 params![
1724 alias,
1725 KeyLifeCycle::Live,
1726 newid.0,
1727 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001728 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001729 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001730 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001731 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001732 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001733 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001734 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001735 return Err(KsError::sys()).context(ks_err!(
1736 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001737 result
1738 ));
1739 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001740 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001741 }
1742
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001743 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1744 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1745 pub fn migrate_key_namespace(
1746 &mut self,
1747 key_id_guard: KeyIdGuard,
1748 destination: &KeyDescriptor,
1749 caller_uid: u32,
1750 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1751 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001752 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1753
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001754 let destination = match destination.domain {
1755 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1756 Domain::SELINUX => (*destination).clone(),
1757 domain => {
1758 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1759 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1760 }
1761 };
1762
1763 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001764 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001765
1766 let alias = destination
1767 .alias
1768 .as_ref()
1769 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001770 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001771
1772 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1773 // Query the destination location. If there is a key, the migration request fails.
1774 if tx
1775 .query_row(
1776 "SELECT id FROM persistent.keyentry
1777 WHERE alias = ? AND domain = ? AND namespace = ?;",
1778 params![alias, destination.domain.0, destination.nspace],
1779 |_| Ok(()),
1780 )
1781 .optional()
1782 .context("Failed to query destination.")?
1783 .is_some()
1784 {
1785 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1786 .context("Target already exists.");
1787 }
1788
1789 let updated = tx
1790 .execute(
1791 "UPDATE persistent.keyentry
1792 SET alias = ?, domain = ?, namespace = ?
1793 WHERE id = ?;",
1794 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1795 )
1796 .context("Failed to update key entry.")?;
1797
1798 if updated != 1 {
1799 return Err(KsError::sys())
1800 .context(format!("Update succeeded, but {} rows were updated.", updated));
1801 }
1802 Ok(()).no_gc()
1803 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001804 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001805 }
1806
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001807 /// Store a new key in a single transaction.
1808 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1809 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001810 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1811 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001812 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001813 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001814 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001815 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001816 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001817 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001818 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001819 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001820 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001821 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001822 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001823 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1824
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001825 let (alias, domain, namespace) = match key {
1826 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1827 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1828 (alias, key.domain, nspace)
1829 }
1830 _ => {
1831 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001832 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001833 }
1834 };
1835 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001836 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001837 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001838 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1839
1840 // In some occasions the key blob is already upgraded during the import.
1841 // In order to make sure it gets properly deleted it is inserted into the
1842 // database here and then immediately replaced by the superseding blob.
1843 // The garbage collector will then subject the blob to deleteKey of the
1844 // KM back end to permanently invalidate the key.
1845 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1846 Self::set_blob_internal(
1847 tx,
1848 key_id.id(),
1849 SubComponentType::KEY_BLOB,
1850 Some(blob),
1851 Some(blob_metadata),
1852 )
1853 .context("Trying to insert superseded key blob.")?;
1854 true
1855 } else {
1856 false
1857 };
1858
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001859 Self::set_blob_internal(
1860 tx,
1861 key_id.id(),
1862 SubComponentType::KEY_BLOB,
1863 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001864 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001865 )
1866 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001867 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001868 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001869 .context("Trying to insert the certificate.")?;
1870 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001871 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001872 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001873 tx,
1874 key_id.id(),
1875 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001876 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001877 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001878 )
1879 .context("Trying to insert the certificate chain.")?;
1880 }
1881 Self::insert_keyparameter_internal(tx, &key_id, params)
1882 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001883 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001884 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001885 .context("Trying to rebind alias.")?
1886 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001887 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001888 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001889 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001890 }
1891
Janis Danisevskis377d1002021-01-27 19:07:48 -08001892 /// Store a new certificate
1893 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1894 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001895 pub fn store_new_certificate(
1896 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001897 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001898 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001899 cert: &[u8],
1900 km_uuid: &Uuid,
1901 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001902 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1903
Janis Danisevskis377d1002021-01-27 19:07:48 -08001904 let (alias, domain, namespace) = match key {
1905 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1906 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1907 (alias, key.domain, nspace)
1908 }
1909 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001910 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1911 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001912 }
1913 };
1914 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001915 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001916 .context("Trying to create new key entry.")?;
1917
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001918 Self::set_blob_internal(
1919 tx,
1920 key_id.id(),
1921 SubComponentType::CERT_CHAIN,
1922 Some(cert),
1923 None,
1924 )
1925 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001926
1927 let mut metadata = KeyMetaData::new();
1928 metadata.add(KeyMetaEntry::CreationDate(
1929 DateTime::now().context("Trying to make creation time.")?,
1930 ));
1931
1932 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1933
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001934 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001935 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001936 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001937 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001938 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001939 }
1940
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001941 // Helper function loading the key_id given the key descriptor
1942 // tuple comprising domain, namespace, and alias.
1943 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001944 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001945 let alias = key
1946 .alias
1947 .as_ref()
1948 .map_or_else(|| Err(KsError::sys()), Ok)
1949 .context("In load_key_entry_id: Alias must be specified.")?;
1950 let mut stmt = tx
1951 .prepare(
1952 "SELECT id FROM persistent.keyentry
1953 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001954 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001955 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001956 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001957 AND alias = ?
1958 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001959 )
1960 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1961 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001962 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001963 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001964 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001965 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001966 .get(0)
1967 .context("Failed to unpack id.")
1968 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001969 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001970 }
1971
1972 /// This helper function completes the access tuple of a key, which is required
1973 /// to perform access control. The strategy depends on the `domain` field in the
1974 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001975 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001976 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001977 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001978 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001979 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001980 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001981 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001982 /// `namespace`.
1983 /// In each case the information returned is sufficient to perform the access
1984 /// check and the key id can be used to load further key artifacts.
1985 fn load_access_tuple(
1986 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001987 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001988 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001989 caller_uid: u32,
1990 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1991 match key.domain {
1992 // Domain App or SELinux. In this case we load the key_id from
1993 // the keyentry database for further loading of key components.
1994 // We already have the full access tuple to perform access control.
1995 // The only distinction is that we use the caller_uid instead
1996 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001997 // Domain::APP.
1998 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001999 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002000 if access_key.domain == Domain::APP {
2001 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002002 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002003 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002004 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002005
2006 Ok((key_id, access_key, None))
2007 }
2008
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002009 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002010 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002011 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002012 let mut stmt = tx
2013 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002014 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002015 WHERE grantee = ? AND id = ? AND
2016 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002017 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002018 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002019 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002020 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002021 .context("Domain:Grant: query failed.")?;
2022 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002023 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002024 let r =
2025 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002026 Ok((
2027 r.get(0).context("Failed to unpack key_id.")?,
2028 r.get(1).context("Failed to unpack access_vector.")?,
2029 ))
2030 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002031 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002032 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002033 }
2034
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002035 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002036 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002037 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002038 let (domain, namespace): (Domain, i64) = {
2039 let mut stmt = tx
2040 .prepare(
2041 "SELECT domain, namespace FROM persistent.keyentry
2042 WHERE
2043 id = ?
2044 AND state = ?;",
2045 )
2046 .context("Domain::KEY_ID: prepare statement failed")?;
2047 let mut rows = stmt
2048 .query(params![key.nspace, KeyLifeCycle::Live])
2049 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002050 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002051 let r =
2052 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002053 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002054 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002055 r.get(1).context("Failed to unpack namespace.")?,
2056 ))
2057 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002058 .context("Domain::KEY_ID.")?
2059 };
2060
2061 // We may use a key by id after loading it by grant.
2062 // In this case we have to check if the caller has a grant for this particular
2063 // key. We can skip this if we already know that the caller is the owner.
2064 // But we cannot know this if domain is anything but App. E.g. in the case
2065 // of Domain::SELINUX we have to speculatively check for grants because we have to
2066 // consult the SEPolicy before we know if the caller is the owner.
2067 let access_vector: Option<KeyPermSet> =
2068 if domain != Domain::APP || namespace != caller_uid as i64 {
2069 let access_vector: Option<i32> = tx
2070 .query_row(
2071 "SELECT access_vector FROM persistent.grant
2072 WHERE grantee = ? AND keyentryid = ?;",
2073 params![caller_uid as i64, key.nspace],
2074 |row| row.get(0),
2075 )
2076 .optional()
2077 .context("Domain::KEY_ID: query grant failed.")?;
2078 access_vector.map(|p| p.into())
2079 } else {
2080 None
2081 };
2082
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002083 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002084 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002085 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002086 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002087
Janis Danisevskis45760022021-01-19 16:34:10 -08002088 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002089 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002090 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002091 }
2092 }
2093
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002094 fn load_blob_components(
2095 key_id: i64,
2096 load_bits: KeyEntryLoadBits,
2097 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002098 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002099 let mut stmt = tx
2100 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002102 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2103 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002104 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002105
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002106 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002107
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002108 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002109 let mut cert_blob: Option<Vec<u8>> = None;
2110 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002111 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002112 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002113 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002114 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002115 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002116 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2117 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002118 key_blob = Some((
2119 row.get(0).context("Failed to extract key blob id.")?,
2120 row.get(2).context("Failed to extract key blob.")?,
2121 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002122 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002123 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002124 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002126 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002128 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002129 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002130 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002131 (SubComponentType::CERT, _, _)
2132 | (SubComponentType::CERT_CHAIN, _, _)
2133 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002134 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2135 }
2136 Ok(())
2137 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002138 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002139
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002140 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2141 Ok(Some((
2142 blob,
2143 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002144 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002145 )))
2146 })?;
2147
2148 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002149 }
2150
2151 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2152 let mut stmt = tx
2153 .prepare(
2154 "SELECT tag, data, security_level from persistent.keyparameter
2155 WHERE keyentryid = ?;",
2156 )
2157 .context("In load_key_parameters: prepare statement failed.")?;
2158
2159 let mut parameters: Vec<KeyParameter> = Vec::new();
2160
2161 let mut rows =
2162 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002163 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002164 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2165 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002166 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002167 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002168 .context("Failed to read KeyParameter.")?,
2169 );
2170 Ok(())
2171 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002172 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002173
2174 Ok(parameters)
2175 }
2176
Qi Wub9433b52020-12-01 14:52:46 +08002177 /// Decrements the usage count of a limited use key. This function first checks whether the
2178 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2179 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2180 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002181 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002182 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2183
Qi Wub9433b52020-12-01 14:52:46 +08002184 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2185 let limit: Option<i32> = tx
2186 .query_row(
2187 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2188 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2189 |row| row.get(0),
2190 )
2191 .optional()
2192 .context("Trying to load usage count")?;
2193
2194 let limit = limit
2195 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2196 .context("The Key no longer exists. Key is exhausted.")?;
2197
2198 tx.execute(
2199 "UPDATE persistent.keyparameter
2200 SET data = data - 1
2201 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2202 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2203 )
2204 .context("Failed to update key usage count.")?;
2205
2206 match limit {
2207 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002208 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002209 .context("Trying to mark limited use key for deletion."),
2210 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002211 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002212 }
2213 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002214 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002215 }
2216
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002217 /// Load a key entry by the given key descriptor.
2218 /// It uses the `check_permission` callback to verify if the access is allowed
2219 /// given the key access tuple read from the database using `load_access_tuple`.
2220 /// With `load_bits` the caller may specify which blobs shall be loaded from
2221 /// the blob database.
2222 pub fn load_key_entry(
2223 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002224 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002225 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002226 load_bits: KeyEntryLoadBits,
2227 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002228 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2229 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002230 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2231
Janis Danisevskis66784c42021-01-27 08:40:25 -08002232 loop {
2233 match self.load_key_entry_internal(
2234 key,
2235 key_type,
2236 load_bits,
2237 caller_uid,
2238 &check_permission,
2239 ) {
2240 Ok(result) => break Ok(result),
2241 Err(e) => {
2242 if Self::is_locked_error(&e) {
2243 std::thread::sleep(std::time::Duration::from_micros(500));
2244 continue;
2245 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002246 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002247 }
2248 }
2249 }
2250 }
2251 }
2252
2253 fn load_key_entry_internal(
2254 &mut self,
2255 key: &KeyDescriptor,
2256 key_type: KeyType,
2257 load_bits: KeyEntryLoadBits,
2258 caller_uid: u32,
2259 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002260 ) -> Result<(KeyIdGuard, KeyEntry)> {
2261 // KEY ID LOCK 1/2
2262 // If we got a key descriptor with a key id we can get the lock right away.
2263 // Otherwise we have to defer it until we know the key id.
2264 let key_id_guard = match key.domain {
2265 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2266 _ => None,
2267 };
2268
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002269 let tx = self
2270 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002271 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002272 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273
2274 // Load the key_id and complete the access control tuple.
2275 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002276 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002277
2278 // Perform access control. It is vital that we return here if the permission is denied.
2279 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002280 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002281
Janis Danisevskisaec14592020-11-12 09:41:49 -08002282 // KEY ID LOCK 2/2
2283 // If we did not get a key id lock by now, it was because we got a key descriptor
2284 // without a key id. At this point we got the key id, so we can try and get a lock.
2285 // However, we cannot block here, because we are in the middle of the transaction.
2286 // So first we try to get the lock non blocking. If that fails, we roll back the
2287 // transaction and block until we get the lock. After we successfully got the lock,
2288 // we start a new transaction and load the access tuple again.
2289 //
2290 // We don't need to perform access control again, because we already established
2291 // that the caller had access to the given key. But we need to make sure that the
2292 // key id still exists. So we have to load the key entry by key id this time.
2293 let (key_id_guard, tx) = match key_id_guard {
2294 None => match KEY_ID_LOCK.try_get(key_id) {
2295 None => {
2296 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002297 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002298
Janis Danisevskisaec14592020-11-12 09:41:49 -08002299 // Block until we have a key id lock.
2300 let key_id_guard = KEY_ID_LOCK.get(key_id);
2301
2302 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002303 let tx = self
2304 .conn
2305 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002306 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002307
2308 Self::load_access_tuple(
2309 &tx,
2310 // This time we have to load the key by the retrieved key id, because the
2311 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002312 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002313 domain: Domain::KEY_ID,
2314 nspace: key_id,
2315 ..Default::default()
2316 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002317 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002318 caller_uid,
2319 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002320 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002321 (key_id_guard, tx)
2322 }
2323 Some(l) => (l, tx),
2324 },
2325 Some(key_id_guard) => (key_id_guard, tx),
2326 };
2327
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002328 let key_entry =
2329 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002330
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002331 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002332
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002333 Ok((key_id_guard, key_entry))
2334 }
2335
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002336 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002337 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002338 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2339 .context("Trying to delete keyentry.")?;
2340 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2341 .context("Trying to delete keymetadata.")?;
2342 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2343 .context("Trying to delete keyparameters.")?;
2344 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2345 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002346 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002347 }
2348
2349 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002350 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002351 pub fn unbind_key(
2352 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002353 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002354 key_type: KeyType,
2355 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002356 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002357 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002358 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2359
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002360 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2361 let (key_id, access_key_descriptor, access_vector) =
2362 Self::load_access_tuple(tx, key, key_type, caller_uid)
2363 .context("Trying to get access tuple.")?;
2364
2365 // Perform access control. It is vital that we return here if the permission is denied.
2366 // So do not touch that '?' at the end.
2367 check_permission(&access_key_descriptor, access_vector)
2368 .context("While checking permission.")?;
2369
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002370 Self::mark_unreferenced(tx, key_id)
2371 .map(|need_gc| (need_gc, ()))
2372 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002373 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002374 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002375 }
2376
Max Bires8e93d2b2021-01-14 13:17:59 -08002377 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2378 tx.query_row(
2379 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2380 params![key_id],
2381 |row| row.get(0),
2382 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002383 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002384 }
2385
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002386 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2387 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2388 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002389 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2390
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002391 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002392 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002393 }
2394 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2395 tx.execute(
2396 "DELETE FROM persistent.keymetadata
2397 WHERE keyentryid IN (
2398 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002399 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002400 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002401 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002402 )
2403 .context("Trying to delete keymetadata.")?;
2404 tx.execute(
2405 "DELETE FROM persistent.keyparameter
2406 WHERE keyentryid IN (
2407 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002408 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002409 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002410 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002411 )
2412 .context("Trying to delete keyparameters.")?;
2413 tx.execute(
2414 "DELETE FROM persistent.grant
2415 WHERE keyentryid IN (
2416 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002417 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002418 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002419 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002420 )
2421 .context("Trying to delete grants.")?;
2422 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002423 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002424 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2425 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002426 )
2427 .context("Trying to delete keyentry.")?;
2428 Ok(()).need_gc()
2429 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002430 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002431 }
2432
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002433 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2434 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2435 {
2436 tx.execute(
2437 "DELETE FROM persistent.keymetadata
2438 WHERE keyentryid IN (
2439 SELECT id FROM persistent.keyentry
2440 WHERE state = ?
2441 );",
2442 params![KeyLifeCycle::Unreferenced],
2443 )
2444 .context("Trying to delete keymetadata.")?;
2445 tx.execute(
2446 "DELETE FROM persistent.keyparameter
2447 WHERE keyentryid IN (
2448 SELECT id FROM persistent.keyentry
2449 WHERE state = ?
2450 );",
2451 params![KeyLifeCycle::Unreferenced],
2452 )
2453 .context("Trying to delete keyparameters.")?;
2454 tx.execute(
2455 "DELETE FROM persistent.grant
2456 WHERE keyentryid IN (
2457 SELECT id FROM persistent.keyentry
2458 WHERE state = ?
2459 );",
2460 params![KeyLifeCycle::Unreferenced],
2461 )
2462 .context("Trying to delete grants.")?;
2463 tx.execute(
2464 "DELETE FROM persistent.keyentry
2465 WHERE state = ?;",
2466 params![KeyLifeCycle::Unreferenced],
2467 )
2468 .context("Trying to delete keyentry.")?;
2469 Result::<()>::Ok(())
2470 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002471 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002472 }
2473
Hasini Gunasingheda895552021-01-27 19:34:37 +00002474 /// Delete the keys created on behalf of the user, denoted by the user id.
2475 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2476 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2477 /// The caller of this function should notify the gc if the returned value is true.
2478 pub fn unbind_keys_for_user(
2479 &mut self,
2480 user_id: u32,
2481 keep_non_super_encrypted_keys: bool,
2482 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002483 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2484
Hasini Gunasingheda895552021-01-27 19:34:37 +00002485 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2486 let mut stmt = tx
2487 .prepare(&format!(
2488 "SELECT id from persistent.keyentry
2489 WHERE (
2490 key_type = ?
2491 AND domain = ?
2492 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2493 AND state = ?
2494 ) OR (
2495 key_type = ?
2496 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002497 AND state = ?
2498 );",
2499 aid_user_offset = AID_USER_OFFSET
2500 ))
2501 .context(concat!(
2502 "In unbind_keys_for_user. ",
2503 "Failed to prepare the query to find the keys created by apps."
2504 ))?;
2505
2506 let mut rows = stmt
2507 .query(params![
2508 // WHERE client key:
2509 KeyType::Client,
2510 Domain::APP.0 as u32,
2511 user_id,
2512 KeyLifeCycle::Live,
2513 // OR super key:
2514 KeyType::Super,
2515 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002516 KeyLifeCycle::Live
2517 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002518 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002519
2520 let mut key_ids: Vec<i64> = Vec::new();
2521 db_utils::with_rows_extract_all(&mut rows, |row| {
2522 key_ids
2523 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2524 Ok(())
2525 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002526 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002527
2528 let mut notify_gc = false;
2529 for key_id in key_ids {
2530 if keep_non_super_encrypted_keys {
2531 // Load metadata and filter out non-super-encrypted keys.
2532 if let (_, Some((_, blob_metadata)), _, _) =
2533 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002534 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002535 {
2536 if blob_metadata.encrypted_by().is_none() {
2537 continue;
2538 }
2539 }
2540 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002541 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002542 .context("In unbind_keys_for_user.")?
2543 || notify_gc;
2544 }
2545 Ok(()).do_gc(notify_gc)
2546 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002547 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002548 }
2549
Eric Biggersb0478cf2023-10-27 03:55:29 +00002550 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2551 /// This runs when the user's lock screen is being changed to Swipe or None.
2552 ///
2553 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2554 /// such keys also require user authentication. Keystore's concept of user authentication is
2555 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2556 /// authentication is no longer possible. In contrast, keys that just require that the device
2557 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2558 /// is always considered "unlocked" in that case.
2559 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2560 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2561
2562 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2563 let mut stmt = tx
2564 .prepare(&format!(
2565 "SELECT id from persistent.keyentry
2566 WHERE key_type = ?
2567 AND domain = ?
2568 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2569 AND state = ?;",
2570 aid_user_offset = AID_USER_OFFSET
2571 ))
2572 .context(concat!(
2573 "In unbind_auth_bound_keys_for_user. ",
2574 "Failed to prepare the query to find the keys created by apps."
2575 ))?;
2576
2577 let mut rows = stmt
2578 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2579 .context(ks_err!("Failed to query the keys created by apps."))?;
2580
2581 let mut key_ids: Vec<i64> = Vec::new();
2582 db_utils::with_rows_extract_all(&mut rows, |row| {
2583 key_ids
2584 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2585 Ok(())
2586 })
2587 .context(ks_err!())?;
2588
2589 let mut notify_gc = false;
2590 let mut num_unbound = 0;
2591 for key_id in key_ids {
2592 // Load the key parameters and filter out non-auth-bound keys. To identify
2593 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2594 // could also be used, but UserSecureID is what Keystore treats as authoritative
2595 // when actually enforcing the key parameters (it might not matter, though).
2596 let params = Self::load_key_parameters(key_id, tx)
2597 .context("Failed to load key parameters.")?;
2598 let is_auth_bound_key = params.iter().any(|kp| {
2599 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2600 });
2601 if is_auth_bound_key {
2602 notify_gc = Self::mark_unreferenced(tx, key_id)
2603 .context("In unbind_auth_bound_keys_for_user.")?
2604 || notify_gc;
2605 num_unbound += 1;
2606 }
2607 }
2608 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2609 Ok(()).do_gc(notify_gc)
2610 })
2611 .context(ks_err!())
2612 }
2613
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002614 fn load_key_components(
2615 tx: &Transaction,
2616 load_bits: KeyEntryLoadBits,
2617 key_id: i64,
2618 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002619 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002620
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002621 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002622 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002623
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002624 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002625 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002626
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002627 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002628 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002629
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002630 Ok(KeyEntry {
2631 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002632 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002633 cert: cert_blob,
2634 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002635 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002636 parameters,
2637 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002638 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002639 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002640 }
2641
Eran Messeri24f31972023-01-25 17:00:33 +00002642 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2643 /// aliases are greater than the specified 'start_past_alias'. If no value
2644 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002645 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002646 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002647 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002648 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002649 &mut self,
2650 domain: Domain,
2651 namespace: i64,
2652 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002653 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002654 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002655 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002656
Eran Messeri24f31972023-01-25 17:00:33 +00002657 let query = format!(
2658 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002659 WHERE domain = ?
2660 AND namespace = ?
2661 AND alias IS NOT NULL
2662 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002663 AND key_type = ?
2664 {}
2665 ORDER BY alias ASC;",
2666 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2667 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002668
Eran Messeri24f31972023-01-25 17:00:33 +00002669 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2670 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2671
2672 let mut rows = match start_past_alias {
2673 Some(past_alias) => stmt
2674 .query(params![
2675 domain.0 as u32,
2676 namespace,
2677 KeyLifeCycle::Live,
2678 key_type,
2679 past_alias
2680 ])
2681 .context(ks_err!("Failed to query."))?,
2682 None => stmt
2683 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2684 .context(ks_err!("Failed to query."))?,
2685 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002686
Janis Danisevskis66784c42021-01-27 08:40:25 -08002687 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2688 db_utils::with_rows_extract_all(&mut rows, |row| {
2689 descriptors.push(KeyDescriptor {
2690 domain,
2691 nspace: namespace,
2692 alias: Some(row.get(0).context("Trying to extract alias.")?),
2693 blob: None,
2694 });
2695 Ok(())
2696 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002697 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002698 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002699 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002700 }
2701
Eran Messeri24f31972023-01-25 17:00:33 +00002702 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2703 /// Domain must be APP or SELINUX, the caller must make sure of that.
2704 pub fn count_keys(
2705 &mut self,
2706 domain: Domain,
2707 namespace: i64,
2708 key_type: KeyType,
2709 ) -> Result<usize> {
2710 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2711
2712 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2713 tx.query_row(
2714 "SELECT COUNT(alias) FROM persistent.keyentry
2715 WHERE domain = ?
2716 AND namespace = ?
2717 AND alias IS NOT NULL
2718 AND state = ?
2719 AND key_type = ?;",
2720 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2721 |row| row.get(0),
2722 )
2723 .context(ks_err!("Failed to count number of keys."))
2724 .no_gc()
2725 })?;
2726 Ok(num_keys)
2727 }
2728
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002729 /// Adds a grant to the grant table.
2730 /// Like `load_key_entry` this function loads the access tuple before
2731 /// it uses the callback for a permission check. Upon success,
2732 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2733 /// grant table. The new row will have a randomized id, which is used as
2734 /// grant id in the namespace field of the resulting KeyDescriptor.
2735 pub fn grant(
2736 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002737 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002738 caller_uid: u32,
2739 grantee_uid: u32,
2740 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002741 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002742 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002743 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2744
Janis Danisevskis66784c42021-01-27 08:40:25 -08002745 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2746 // Load the key_id and complete the access control tuple.
2747 // We ignore the access vector here because grants cannot be granted.
2748 // The access vector returned here expresses the permissions the
2749 // grantee has if key.domain == Domain::GRANT. But this vector
2750 // cannot include the grant permission by design, so there is no way the
2751 // subsequent permission check can pass.
2752 // We could check key.domain == Domain::GRANT and fail early.
2753 // But even if we load the access tuple by grant here, the permission
2754 // check denies the attempt to create a grant by grant descriptor.
2755 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002756 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002757
Janis Danisevskis66784c42021-01-27 08:40:25 -08002758 // Perform access control. It is vital that we return here if the permission
2759 // was denied. So do not touch that '?' at the end of the line.
2760 // This permission check checks if the caller has the grant permission
2761 // for the given key and in addition to all of the permissions
2762 // expressed in `access_vector`.
2763 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002764 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002765
Janis Danisevskis66784c42021-01-27 08:40:25 -08002766 let grant_id = if let Some(grant_id) = tx
2767 .query_row(
2768 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002769 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002770 params![key_id, grantee_uid],
2771 |row| row.get(0),
2772 )
2773 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002774 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002775 {
2776 tx.execute(
2777 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002778 SET access_vector = ?
2779 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002780 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002781 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002782 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002783 grant_id
2784 } else {
2785 Self::insert_with_retry(|id| {
2786 tx.execute(
2787 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2788 VALUES (?, ?, ?, ?);",
2789 params![id, grantee_uid, key_id, i32::from(access_vector)],
2790 )
2791 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002792 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002793 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002794
Janis Danisevskis66784c42021-01-27 08:40:25 -08002795 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002796 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002797 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002798 }
2799
2800 /// This function checks permissions like `grant` and `load_key_entry`
2801 /// before removing a grant from the grant table.
2802 pub fn ungrant(
2803 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002804 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002805 caller_uid: u32,
2806 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002807 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002808 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002809 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2810
Janis Danisevskis66784c42021-01-27 08:40:25 -08002811 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2812 // Load the key_id and complete the access control tuple.
2813 // We ignore the access vector here because grants cannot be granted.
2814 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002815 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002816
Janis Danisevskis66784c42021-01-27 08:40:25 -08002817 // Perform access control. We must return here if the permission
2818 // was denied. So do not touch the '?' at the end of this line.
2819 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002820 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002821
Janis Danisevskis66784c42021-01-27 08:40:25 -08002822 tx.execute(
2823 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002824 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002825 params![key_id, grantee_uid],
2826 )
2827 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002828
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002829 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002830 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002831 }
2832
Joel Galenson845f74b2020-09-09 14:11:55 -07002833 // Generates a random id and passes it to the given function, which will
2834 // try to insert it into a database. If that insertion fails, retry;
2835 // otherwise return the id.
2836 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2837 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002838 let newid: i64 = match random() {
2839 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2840 i => i,
2841 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002842 match inserter(newid) {
2843 // If the id already existed, try again.
2844 Err(rusqlite::Error::SqliteFailure(
2845 libsqlite3_sys::Error {
2846 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2847 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2848 },
2849 _,
2850 )) => (),
2851 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002852 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002853 }
2854 _ => return Ok(newid),
2855 }
2856 }
2857 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002858
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002859 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2860 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002861 self.perboot
2862 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002863 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002864
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002865 /// Find the newest auth token matching the given predicate.
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002866 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, BootTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002867 where
2868 F: Fn(&AuthTokenEntry) -> bool,
2869 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002870 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002871 }
2872
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002873 /// Insert last_off_body into the metadata table at the initialization of auth token table
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002874 pub fn insert_last_off_body(&self, last_off_body: BootTime) {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002875 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002876 }
2877
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002878 /// Update last_off_body when on_device_off_body is called
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002879 pub fn update_last_off_body(&self, last_off_body: BootTime) {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002880 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002881 }
2882
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002883 /// Get last_off_body time when finding auth tokens
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002884 fn get_last_off_body(&self) -> BootTime {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002885 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002886 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002887
2888 /// Load descriptor of a key by key id
2889 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2890 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2891
2892 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2893 tx.query_row(
2894 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2895 params![key_id],
2896 |row| {
2897 Ok(KeyDescriptor {
2898 domain: Domain(row.get(0)?),
2899 nspace: row.get(1)?,
2900 alias: row.get(2)?,
2901 blob: None,
2902 })
2903 },
2904 )
2905 .optional()
2906 .context("Trying to load key descriptor")
2907 .no_gc()
2908 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002909 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002910 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002911
2912 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2913 /// (for the given user_id).
2914 /// This is helpful for finding out which apps will have their keys invalidated when
2915 /// the user changes biometrics enrollment or removes their LSKF.
2916 pub fn get_app_uids_affected_by_sid(
2917 &mut self,
2918 user_id: i32,
2919 secure_user_id: i64,
2920 ) -> Result<Vec<i64>> {
2921 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2922
2923 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2924 let mut stmt = tx
2925 .prepare(&format!(
2926 "SELECT id, namespace from persistent.keyentry
2927 WHERE key_type = ?
2928 AND domain = ?
2929 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2930 AND state = ?;",
2931 ))
2932 .context(concat!(
2933 "In get_app_uids_affected_by_sid, ",
2934 "failed to prepare the query to find the keys created by apps."
2935 ))?;
2936
2937 let mut rows = stmt
2938 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2939 .context(ks_err!("Failed to query the keys created by apps."))?;
2940
2941 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2942 db_utils::with_rows_extract_all(&mut rows, |row| {
2943 key_ids_and_app_uids.insert(
2944 row.get(0).context("Failed to read key id of a key created by an app.")?,
2945 row.get(1).context("Failed to read the app uid")?,
2946 );
2947 Ok(())
2948 })?;
2949 Ok(key_ids_and_app_uids).no_gc()
2950 })?;
2951 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2952 for (key_id, app_uid) in key_ids_and_app_uids {
2953 // Read the key parameters for each key in its own transaction. It is OK to ignore
2954 // an error to get the properties of a particular key since it might have been deleted
2955 // under our feet after the previous transaction concluded. If the key was deleted
2956 // then it is no longer applicable if it was auth-bound or not.
2957 if let Ok(is_key_bound_to_sid) =
2958 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2959 let params = Self::load_key_parameters(key_id, tx)
2960 .context("Failed to load key parameters.")?;
2961 // Check if the key is bound to this secure user ID.
2962 let is_key_bound_to_sid = params.iter().any(|kp| {
2963 matches!(
2964 kp.key_parameter_value(),
2965 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2966 )
2967 });
2968 Ok(is_key_bound_to_sid).no_gc()
2969 })
2970 {
2971 if is_key_bound_to_sid {
2972 app_uids_affected_by_sid.insert(app_uid);
2973 }
2974 }
2975 }
2976
2977 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2978 Ok(app_uids_vec)
2979 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002980}
2981
2982#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002983pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002984
2985 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002986 use crate::key_parameter::{
2987 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2988 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2989 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002990 use crate::key_perm_set;
2991 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002992 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002993 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002994 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2995 HardwareAuthToken::HardwareAuthToken,
2996 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002997 };
2998 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002999 Timestamp::Timestamp,
3000 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003001 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003002 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003003 use std::collections::BTreeMap;
3004 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003005 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04003006 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003007 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003008 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003009 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003010 #[cfg(disabled)]
3011 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003012
Seth Moore7ee79f92021-12-07 11:42:49 -08003013 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003014 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003015
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003016 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003017 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003018 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003019 })?;
3020 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003021 }
3022
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003023 fn rebind_alias(
3024 db: &mut KeystoreDB,
3025 newid: &KeyIdGuard,
3026 alias: &str,
3027 domain: Domain,
3028 namespace: i64,
3029 ) -> Result<bool> {
3030 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003031 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003032 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003033 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003034 }
3035
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003036 #[test]
3037 fn datetime() -> Result<()> {
3038 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003039 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003040 let now = SystemTime::now();
3041 let duration = Duration::from_secs(1000);
3042 let then = now.checked_sub(duration).unwrap();
3043 let soon = now.checked_add(duration).unwrap();
3044 conn.execute(
3045 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3046 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3047 )?;
3048 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003049 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003050 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3051 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3052 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3053 assert!(rows.next()?.is_none());
3054 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3055 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3056 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3057 Ok(())
3058 }
3059
Joel Galenson0891bc12020-07-20 10:37:03 -07003060 // Ensure that we're using the "injected" random function, not the real one.
3061 #[test]
3062 fn test_mocked_random() {
3063 let rand1 = random();
3064 let rand2 = random();
3065 let rand3 = random();
3066 if rand1 == rand2 {
3067 assert_eq!(rand2 + 1, rand3);
3068 } else {
3069 assert_eq!(rand1 + 1, rand2);
3070 assert_eq!(rand2, rand3);
3071 }
3072 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003073
Joel Galenson26f4d012020-07-17 14:57:21 -07003074 // Test that we have the correct tables.
3075 #[test]
3076 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003077 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003078 let tables = db
3079 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003080 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003081 .query_map(params![], |row| row.get(0))?
3082 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003083 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003084 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003085 assert_eq!(tables[1], "blobmetadata");
3086 assert_eq!(tables[2], "grant");
3087 assert_eq!(tables[3], "keyentry");
3088 assert_eq!(tables[4], "keymetadata");
3089 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003090 Ok(())
3091 }
3092
3093 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003094 fn test_auth_token_table_invariant() -> Result<()> {
3095 let mut db = new_test_db()?;
3096 let auth_token1 = HardwareAuthToken {
3097 challenge: i64::MAX,
3098 userId: 200,
3099 authenticatorId: 200,
3100 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3101 timestamp: Timestamp { milliSeconds: 500 },
3102 mac: String::from("mac").into_bytes(),
3103 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003104 db.insert_auth_token(&auth_token1);
3105 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003106 assert_eq!(auth_tokens_returned.len(), 1);
3107
3108 // insert another auth token with the same values for the columns in the UNIQUE constraint
3109 // of the auth token table and different value for timestamp
3110 let auth_token2 = HardwareAuthToken {
3111 challenge: i64::MAX,
3112 userId: 200,
3113 authenticatorId: 200,
3114 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3115 timestamp: Timestamp { milliSeconds: 600 },
3116 mac: String::from("mac").into_bytes(),
3117 };
3118
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003119 db.insert_auth_token(&auth_token2);
3120 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003121 assert_eq!(auth_tokens_returned.len(), 1);
3122
3123 if let Some(auth_token) = auth_tokens_returned.pop() {
3124 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3125 }
3126
3127 // insert another auth token with the different values for the columns in the UNIQUE
3128 // constraint of the auth token table
3129 let auth_token3 = HardwareAuthToken {
3130 challenge: i64::MAX,
3131 userId: 201,
3132 authenticatorId: 200,
3133 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3134 timestamp: Timestamp { milliSeconds: 600 },
3135 mac: String::from("mac").into_bytes(),
3136 };
3137
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003138 db.insert_auth_token(&auth_token3);
3139 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003140 assert_eq!(auth_tokens_returned.len(), 2);
3141
3142 Ok(())
3143 }
3144
3145 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003146 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3147 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003148 }
3149
3150 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003151 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003152 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003153 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003154
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003155 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003156 let entries = get_keyentry(&db)?;
3157 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003158
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003159 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003160
3161 let entries_new = get_keyentry(&db)?;
3162 assert_eq!(entries, entries_new);
3163 Ok(())
3164 }
3165
3166 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003167 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003168 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3169 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003170 }
3171
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003172 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003173
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003174 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3175 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003176
3177 let entries = get_keyentry(&db)?;
3178 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003179 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3180 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003181
3182 // Test that we must pass in a valid Domain.
3183 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003184 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003185 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003186 );
3187 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003188 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003189 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003190 );
3191 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003192 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003193 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003194 );
3195
3196 Ok(())
3197 }
3198
Joel Galenson33c04ad2020-08-03 11:04:38 -07003199 #[test]
3200 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003201 fn extractor(
3202 ke: &KeyEntryRow,
3203 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3204 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003205 }
3206
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003207 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003208 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3209 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
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), None, 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 first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003222 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].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!(
3226 extractor(&entries[0]),
3227 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3228 );
3229 assert_eq!(
3230 extractor(&entries[1]),
3231 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3232 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003233
3234 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003235 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003236 let entries = get_keyentry(&db)?;
3237 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003238 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3239 assert_eq!(
3240 extractor(&entries[1]),
3241 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3242 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003243
3244 // Test that we must pass in a valid Domain.
3245 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003246 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003247 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003248 );
3249 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003250 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003251 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003252 );
3253 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003254 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003255 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003256 );
3257
3258 // Test that we correctly handle setting an alias for something that does not exist.
3259 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003260 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003261 "Expected to update a single entry but instead updated 0",
3262 );
3263 // Test that we correctly abort the transaction in this case.
3264 let entries = get_keyentry(&db)?;
3265 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003266 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3267 assert_eq!(
3268 extractor(&entries[1]),
3269 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3270 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003271
3272 Ok(())
3273 }
3274
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003275 #[test]
3276 fn test_grant_ungrant() -> Result<()> {
3277 const CALLER_UID: u32 = 15;
3278 const GRANTEE_UID: u32 = 12;
3279 const SELINUX_NAMESPACE: i64 = 7;
3280
3281 let mut db = new_test_db()?;
3282 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003283 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3284 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3285 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003286 )?;
3287 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003288 domain: super::Domain::APP,
3289 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003290 alias: Some("key".to_string()),
3291 blob: None,
3292 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003293 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3294 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003295
3296 // Reset totally predictable random number generator in case we
3297 // are not the first test running on this thread.
3298 reset_random();
3299 let next_random = 0i64;
3300
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003301 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003302 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303 assert_eq!(*a, PVEC1);
3304 assert_eq!(
3305 *k,
3306 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003307 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003308 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003309 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003310 alias: Some("key".to_string()),
3311 blob: None,
3312 }
3313 );
3314 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003315 })
3316 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003317
3318 assert_eq!(
3319 app_granted_key,
3320 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003321 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003322 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003323 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003324 alias: None,
3325 blob: None,
3326 }
3327 );
3328
3329 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003330 domain: super::Domain::SELINUX,
3331 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003332 alias: Some("yek".to_string()),
3333 blob: None,
3334 };
3335
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003336 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003337 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003338 assert_eq!(*a, PVEC1);
3339 assert_eq!(
3340 *k,
3341 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003342 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003343 // namespace must be the supplied SELinux
3344 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003345 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003346 alias: Some("yek".to_string()),
3347 blob: None,
3348 }
3349 );
3350 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003351 })
3352 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003353
3354 assert_eq!(
3355 selinux_granted_key,
3356 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003357 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003358 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003359 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003360 alias: None,
3361 blob: None,
3362 }
3363 );
3364
3365 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003366 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003367 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003368 assert_eq!(*a, PVEC2);
3369 assert_eq!(
3370 *k,
3371 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003372 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003373 // namespace must be the supplied SELinux
3374 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003375 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003376 alias: Some("yek".to_string()),
3377 blob: None,
3378 }
3379 );
3380 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003381 })
3382 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003383
3384 assert_eq!(
3385 selinux_granted_key,
3386 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003387 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003388 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003389 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003390 alias: None,
3391 blob: None,
3392 }
3393 );
3394
3395 {
3396 // Limiting scope of stmt, because it borrows db.
3397 let mut stmt = db
3398 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003399 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003400 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3401 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3402 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003403
3404 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003405 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003406 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003407 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003408 assert!(rows.next().is_none());
3409 }
3410
3411 debug_dump_keyentry_table(&mut db)?;
3412 println!("app_key {:?}", app_key);
3413 println!("selinux_key {:?}", selinux_key);
3414
Janis Danisevskis66784c42021-01-27 08:40:25 -08003415 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3416 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003417
3418 Ok(())
3419 }
3420
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003421 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003422 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3423 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3424
3425 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003426 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003427 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003428 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003429 let mut blob_metadata = BlobMetaData::new();
3430 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3431 db.set_blob(
3432 &key_id,
3433 SubComponentType::KEY_BLOB,
3434 Some(TEST_KEY_BLOB),
3435 Some(&blob_metadata),
3436 )?;
3437 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3438 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003439 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003440
3441 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003442 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003443 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003444 )?;
3445 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003446 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003447 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003448 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003449 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003450 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003451 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003452 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003453 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003454 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003455
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003456 drop(rows);
3457 drop(stmt);
3458
3459 assert_eq!(
3460 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3461 BlobMetaData::load_from_db(id, tx).no_gc()
3462 })
3463 .expect("Should find blob metadata."),
3464 blob_metadata
3465 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003466 Ok(())
3467 }
3468
3469 static TEST_ALIAS: &str = "my super duper key";
3470
3471 #[test]
3472 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3473 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003474 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003475 .context("test_insert_and_load_full_keyentry_domain_app")?
3476 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003477 let (_key_guard, key_entry) = db
3478 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003479 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003480 domain: Domain::APP,
3481 nspace: 0,
3482 alias: Some(TEST_ALIAS.to_string()),
3483 blob: None,
3484 },
3485 KeyType::Client,
3486 KeyEntryLoadBits::BOTH,
3487 1,
3488 |_k, _av| Ok(()),
3489 )
3490 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003491 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003492
3493 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003494 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003495 domain: Domain::APP,
3496 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003497 alias: Some(TEST_ALIAS.to_string()),
3498 blob: None,
3499 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003500 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003501 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003502 |_, _| Ok(()),
3503 )
3504 .unwrap();
3505
3506 assert_eq!(
3507 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3508 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003509 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003510 domain: Domain::APP,
3511 nspace: 0,
3512 alias: Some(TEST_ALIAS.to_string()),
3513 blob: None,
3514 },
3515 KeyType::Client,
3516 KeyEntryLoadBits::NONE,
3517 1,
3518 |_k, _av| Ok(()),
3519 )
3520 .unwrap_err()
3521 .root_cause()
3522 .downcast_ref::<KsError>()
3523 );
3524
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003525 Ok(())
3526 }
3527
3528 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003529 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3530 let mut db = new_test_db()?;
3531
3532 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003533 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003534 domain: Domain::APP,
3535 nspace: 1,
3536 alias: Some(TEST_ALIAS.to_string()),
3537 blob: None,
3538 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003539 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003540 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003541 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003542 )
3543 .expect("Trying to insert cert.");
3544
3545 let (_key_guard, mut key_entry) = db
3546 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003547 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003548 domain: Domain::APP,
3549 nspace: 1,
3550 alias: Some(TEST_ALIAS.to_string()),
3551 blob: None,
3552 },
3553 KeyType::Client,
3554 KeyEntryLoadBits::PUBLIC,
3555 1,
3556 |_k, _av| Ok(()),
3557 )
3558 .expect("Trying to read certificate entry.");
3559
3560 assert!(key_entry.pure_cert());
3561 assert!(key_entry.cert().is_none());
3562 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3563
3564 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003565 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003566 domain: Domain::APP,
3567 nspace: 1,
3568 alias: Some(TEST_ALIAS.to_string()),
3569 blob: None,
3570 },
3571 KeyType::Client,
3572 1,
3573 |_, _| Ok(()),
3574 )
3575 .unwrap();
3576
3577 assert_eq!(
3578 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3579 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003580 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003581 domain: Domain::APP,
3582 nspace: 1,
3583 alias: Some(TEST_ALIAS.to_string()),
3584 blob: None,
3585 },
3586 KeyType::Client,
3587 KeyEntryLoadBits::NONE,
3588 1,
3589 |_k, _av| Ok(()),
3590 )
3591 .unwrap_err()
3592 .root_cause()
3593 .downcast_ref::<KsError>()
3594 );
3595
3596 Ok(())
3597 }
3598
3599 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003600 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3601 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003602 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003603 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3604 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003605 let (_key_guard, key_entry) = db
3606 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003607 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003608 domain: Domain::SELINUX,
3609 nspace: 1,
3610 alias: Some(TEST_ALIAS.to_string()),
3611 blob: None,
3612 },
3613 KeyType::Client,
3614 KeyEntryLoadBits::BOTH,
3615 1,
3616 |_k, _av| Ok(()),
3617 )
3618 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003619 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003620
3621 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003622 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003623 domain: Domain::SELINUX,
3624 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003625 alias: Some(TEST_ALIAS.to_string()),
3626 blob: None,
3627 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003628 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003629 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003630 |_, _| Ok(()),
3631 )
3632 .unwrap();
3633
3634 assert_eq!(
3635 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3636 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003637 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003638 domain: Domain::SELINUX,
3639 nspace: 1,
3640 alias: Some(TEST_ALIAS.to_string()),
3641 blob: None,
3642 },
3643 KeyType::Client,
3644 KeyEntryLoadBits::NONE,
3645 1,
3646 |_k, _av| Ok(()),
3647 )
3648 .unwrap_err()
3649 .root_cause()
3650 .downcast_ref::<KsError>()
3651 );
3652
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003653 Ok(())
3654 }
3655
3656 #[test]
3657 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3658 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003659 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003660 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3661 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003662 let (_, key_entry) = db
3663 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003664 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003665 KeyType::Client,
3666 KeyEntryLoadBits::BOTH,
3667 1,
3668 |_k, _av| Ok(()),
3669 )
3670 .unwrap();
3671
Qi Wub9433b52020-12-01 14:52:46 +08003672 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003673
3674 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003675 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003676 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003677 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003678 |_, _| Ok(()),
3679 )
3680 .unwrap();
3681
3682 assert_eq!(
3683 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3684 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003685 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003686 KeyType::Client,
3687 KeyEntryLoadBits::NONE,
3688 1,
3689 |_k, _av| Ok(()),
3690 )
3691 .unwrap_err()
3692 .root_cause()
3693 .downcast_ref::<KsError>()
3694 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003695
3696 Ok(())
3697 }
3698
3699 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003700 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3701 let mut db = new_test_db()?;
3702 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3703 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3704 .0;
3705 // Update the usage count of the limited use key.
3706 db.check_and_update_key_usage_count(key_id)?;
3707
3708 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003709 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003710 KeyType::Client,
3711 KeyEntryLoadBits::BOTH,
3712 1,
3713 |_k, _av| Ok(()),
3714 )?;
3715
3716 // The usage count is decremented now.
3717 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3718
3719 Ok(())
3720 }
3721
3722 #[test]
3723 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3724 let mut db = new_test_db()?;
3725 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3726 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3727 .0;
3728 // Update the usage count of the limited use key.
3729 db.check_and_update_key_usage_count(key_id).expect(concat!(
3730 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3731 "This should succeed."
3732 ));
3733
3734 // Try to update the exhausted limited use key.
3735 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3736 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3737 "This should fail."
3738 ));
3739 assert_eq!(
3740 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3741 e.root_cause().downcast_ref::<KsError>().unwrap()
3742 );
3743
3744 Ok(())
3745 }
3746
3747 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003748 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3749 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003750 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003751 .context("test_insert_and_load_full_keyentry_from_grant")?
3752 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003753
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003754 let granted_key = db
3755 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003756 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003757 domain: Domain::APP,
3758 nspace: 0,
3759 alias: Some(TEST_ALIAS.to_string()),
3760 blob: None,
3761 },
3762 1,
3763 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003764 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003765 |_k, _av| Ok(()),
3766 )
3767 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003768
3769 debug_dump_grant_table(&mut db)?;
3770
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003771 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003772 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3773 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003774 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003775 Ok(())
3776 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003777 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003778
Qi Wub9433b52020-12-01 14:52:46 +08003779 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003780
Janis Danisevskis66784c42021-01-27 08:40:25 -08003781 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003782
3783 assert_eq!(
3784 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3785 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003786 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003787 KeyType::Client,
3788 KeyEntryLoadBits::NONE,
3789 2,
3790 |_k, _av| Ok(()),
3791 )
3792 .unwrap_err()
3793 .root_cause()
3794 .downcast_ref::<KsError>()
3795 );
3796
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003797 Ok(())
3798 }
3799
Janis Danisevskis45760022021-01-19 16:34:10 -08003800 // This test attempts to load a key by key id while the caller is not the owner
3801 // but a grant exists for the given key and the caller.
3802 #[test]
3803 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3804 let mut db = new_test_db()?;
3805 const OWNER_UID: u32 = 1u32;
3806 const GRANTEE_UID: u32 = 2u32;
3807 const SOMEONE_ELSE_UID: u32 = 3u32;
3808 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3809 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3810 .0;
3811
3812 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003813 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003814 domain: Domain::APP,
3815 nspace: 0,
3816 alias: Some(TEST_ALIAS.to_string()),
3817 blob: None,
3818 },
3819 OWNER_UID,
3820 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003821 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003822 |_k, _av| Ok(()),
3823 )
3824 .unwrap();
3825
3826 debug_dump_grant_table(&mut db)?;
3827
3828 let id_descriptor =
3829 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3830
3831 let (_, key_entry) = db
3832 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003833 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003834 KeyType::Client,
3835 KeyEntryLoadBits::BOTH,
3836 GRANTEE_UID,
3837 |k, av| {
3838 assert_eq!(Domain::APP, k.domain);
3839 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003840 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003841 Ok(())
3842 },
3843 )
3844 .unwrap();
3845
3846 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3847
3848 let (_, key_entry) = db
3849 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003850 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003851 KeyType::Client,
3852 KeyEntryLoadBits::BOTH,
3853 SOMEONE_ELSE_UID,
3854 |k, av| {
3855 assert_eq!(Domain::APP, k.domain);
3856 assert_eq!(OWNER_UID as i64, k.nspace);
3857 assert!(av.is_none());
3858 Ok(())
3859 },
3860 )
3861 .unwrap();
3862
3863 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3864
Janis Danisevskis66784c42021-01-27 08:40:25 -08003865 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003866
3867 assert_eq!(
3868 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3869 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003870 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003871 KeyType::Client,
3872 KeyEntryLoadBits::NONE,
3873 GRANTEE_UID,
3874 |_k, _av| Ok(()),
3875 )
3876 .unwrap_err()
3877 .root_cause()
3878 .downcast_ref::<KsError>()
3879 );
3880
3881 Ok(())
3882 }
3883
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003884 // Creates a key migrates it to a different location and then tries to access it by the old
3885 // and new location.
3886 #[test]
3887 fn test_migrate_key_app_to_app() -> Result<()> {
3888 let mut db = new_test_db()?;
3889 const SOURCE_UID: u32 = 1u32;
3890 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003891 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3892 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003893 let key_id_guard =
3894 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3895 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3896
3897 let source_descriptor: KeyDescriptor = KeyDescriptor {
3898 domain: Domain::APP,
3899 nspace: -1,
3900 alias: Some(SOURCE_ALIAS.to_string()),
3901 blob: None,
3902 };
3903
3904 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3905 domain: Domain::APP,
3906 nspace: -1,
3907 alias: Some(DESTINATION_ALIAS.to_string()),
3908 blob: None,
3909 };
3910
3911 let key_id = key_id_guard.id();
3912
3913 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3914 Ok(())
3915 })
3916 .unwrap();
3917
3918 let (_, key_entry) = db
3919 .load_key_entry(
3920 &destination_descriptor,
3921 KeyType::Client,
3922 KeyEntryLoadBits::BOTH,
3923 DESTINATION_UID,
3924 |k, av| {
3925 assert_eq!(Domain::APP, k.domain);
3926 assert_eq!(DESTINATION_UID as i64, k.nspace);
3927 assert!(av.is_none());
3928 Ok(())
3929 },
3930 )
3931 .unwrap();
3932
3933 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3934
3935 assert_eq!(
3936 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3937 db.load_key_entry(
3938 &source_descriptor,
3939 KeyType::Client,
3940 KeyEntryLoadBits::NONE,
3941 SOURCE_UID,
3942 |_k, _av| Ok(()),
3943 )
3944 .unwrap_err()
3945 .root_cause()
3946 .downcast_ref::<KsError>()
3947 );
3948
3949 Ok(())
3950 }
3951
3952 // Creates a key migrates it to a different location and then tries to access it by the old
3953 // and new location.
3954 #[test]
3955 fn test_migrate_key_app_to_selinux() -> Result<()> {
3956 let mut db = new_test_db()?;
3957 const SOURCE_UID: u32 = 1u32;
3958 const DESTINATION_UID: u32 = 2u32;
3959 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003960 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3961 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003962 let key_id_guard =
3963 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3964 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3965
3966 let source_descriptor: KeyDescriptor = KeyDescriptor {
3967 domain: Domain::APP,
3968 nspace: -1,
3969 alias: Some(SOURCE_ALIAS.to_string()),
3970 blob: None,
3971 };
3972
3973 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3974 domain: Domain::SELINUX,
3975 nspace: DESTINATION_NAMESPACE,
3976 alias: Some(DESTINATION_ALIAS.to_string()),
3977 blob: None,
3978 };
3979
3980 let key_id = key_id_guard.id();
3981
3982 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3983 Ok(())
3984 })
3985 .unwrap();
3986
3987 let (_, key_entry) = db
3988 .load_key_entry(
3989 &destination_descriptor,
3990 KeyType::Client,
3991 KeyEntryLoadBits::BOTH,
3992 DESTINATION_UID,
3993 |k, av| {
3994 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003995 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003996 assert!(av.is_none());
3997 Ok(())
3998 },
3999 )
4000 .unwrap();
4001
4002 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4003
4004 assert_eq!(
4005 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4006 db.load_key_entry(
4007 &source_descriptor,
4008 KeyType::Client,
4009 KeyEntryLoadBits::NONE,
4010 SOURCE_UID,
4011 |_k, _av| Ok(()),
4012 )
4013 .unwrap_err()
4014 .root_cause()
4015 .downcast_ref::<KsError>()
4016 );
4017
4018 Ok(())
4019 }
4020
4021 // Creates two keys and tries to migrate the first to the location of the second which
4022 // is expected to fail.
4023 #[test]
4024 fn test_migrate_key_destination_occupied() -> Result<()> {
4025 let mut db = new_test_db()?;
4026 const SOURCE_UID: u32 = 1u32;
4027 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004028 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4029 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004030 let key_id_guard =
4031 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4032 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4033 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4034 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4035
4036 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4037 domain: Domain::APP,
4038 nspace: -1,
4039 alias: Some(DESTINATION_ALIAS.to_string()),
4040 blob: None,
4041 };
4042
4043 assert_eq!(
4044 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4045 db.migrate_key_namespace(
4046 key_id_guard,
4047 &destination_descriptor,
4048 DESTINATION_UID,
4049 |_k| Ok(())
4050 )
4051 .unwrap_err()
4052 .root_cause()
4053 .downcast_ref::<KsError>()
4054 );
4055
4056 Ok(())
4057 }
4058
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004059 #[test]
4060 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004061 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4062 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4063 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004064 const UID: u32 = 33;
4065 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4066 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4067 let key_id_untouched1 =
4068 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4069 let key_id_untouched2 =
4070 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4071 let key_id_deleted =
4072 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4073
4074 let (_, key_entry) = db
4075 .load_key_entry(
4076 &KeyDescriptor {
4077 domain: Domain::APP,
4078 nspace: -1,
4079 alias: Some(ALIAS1.to_string()),
4080 blob: None,
4081 },
4082 KeyType::Client,
4083 KeyEntryLoadBits::BOTH,
4084 UID,
4085 |k, av| {
4086 assert_eq!(Domain::APP, k.domain);
4087 assert_eq!(UID as i64, k.nspace);
4088 assert!(av.is_none());
4089 Ok(())
4090 },
4091 )
4092 .unwrap();
4093 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4094 let (_, key_entry) = db
4095 .load_key_entry(
4096 &KeyDescriptor {
4097 domain: Domain::APP,
4098 nspace: -1,
4099 alias: Some(ALIAS2.to_string()),
4100 blob: None,
4101 },
4102 KeyType::Client,
4103 KeyEntryLoadBits::BOTH,
4104 UID,
4105 |k, av| {
4106 assert_eq!(Domain::APP, k.domain);
4107 assert_eq!(UID as i64, k.nspace);
4108 assert!(av.is_none());
4109 Ok(())
4110 },
4111 )
4112 .unwrap();
4113 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4114 let (_, key_entry) = db
4115 .load_key_entry(
4116 &KeyDescriptor {
4117 domain: Domain::APP,
4118 nspace: -1,
4119 alias: Some(ALIAS3.to_string()),
4120 blob: None,
4121 },
4122 KeyType::Client,
4123 KeyEntryLoadBits::BOTH,
4124 UID,
4125 |k, av| {
4126 assert_eq!(Domain::APP, k.domain);
4127 assert_eq!(UID as i64, k.nspace);
4128 assert!(av.is_none());
4129 Ok(())
4130 },
4131 )
4132 .unwrap();
4133 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4134
4135 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4136 KeystoreDB::from_0_to_1(tx).no_gc()
4137 })
4138 .unwrap();
4139
4140 let (_, key_entry) = db
4141 .load_key_entry(
4142 &KeyDescriptor {
4143 domain: Domain::APP,
4144 nspace: -1,
4145 alias: Some(ALIAS1.to_string()),
4146 blob: None,
4147 },
4148 KeyType::Client,
4149 KeyEntryLoadBits::BOTH,
4150 UID,
4151 |k, av| {
4152 assert_eq!(Domain::APP, k.domain);
4153 assert_eq!(UID as i64, k.nspace);
4154 assert!(av.is_none());
4155 Ok(())
4156 },
4157 )
4158 .unwrap();
4159 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4160 let (_, key_entry) = db
4161 .load_key_entry(
4162 &KeyDescriptor {
4163 domain: Domain::APP,
4164 nspace: -1,
4165 alias: Some(ALIAS2.to_string()),
4166 blob: None,
4167 },
4168 KeyType::Client,
4169 KeyEntryLoadBits::BOTH,
4170 UID,
4171 |k, av| {
4172 assert_eq!(Domain::APP, k.domain);
4173 assert_eq!(UID as i64, k.nspace);
4174 assert!(av.is_none());
4175 Ok(())
4176 },
4177 )
4178 .unwrap();
4179 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4180 assert_eq!(
4181 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4182 db.load_key_entry(
4183 &KeyDescriptor {
4184 domain: Domain::APP,
4185 nspace: -1,
4186 alias: Some(ALIAS3.to_string()),
4187 blob: None,
4188 },
4189 KeyType::Client,
4190 KeyEntryLoadBits::BOTH,
4191 UID,
4192 |k, av| {
4193 assert_eq!(Domain::APP, k.domain);
4194 assert_eq!(UID as i64, k.nspace);
4195 assert!(av.is_none());
4196 Ok(())
4197 },
4198 )
4199 .unwrap_err()
4200 .root_cause()
4201 .downcast_ref::<KsError>()
4202 );
4203 }
4204
Janis Danisevskisaec14592020-11-12 09:41:49 -08004205 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4206
Janis Danisevskisaec14592020-11-12 09:41:49 -08004207 #[test]
4208 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4209 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004210 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4211 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004212 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004213 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004214 .context("test_insert_and_load_full_keyentry_domain_app")?
4215 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004216 let (_key_guard, key_entry) = db
4217 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004218 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004219 domain: Domain::APP,
4220 nspace: 0,
4221 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4222 blob: None,
4223 },
4224 KeyType::Client,
4225 KeyEntryLoadBits::BOTH,
4226 33,
4227 |_k, _av| Ok(()),
4228 )
4229 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004230 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004231 let state = Arc::new(AtomicU8::new(1));
4232 let state2 = state.clone();
4233
4234 // Spawning a second thread that attempts to acquire the key id lock
4235 // for the same key as the primary thread. The primary thread then
4236 // waits, thereby forcing the secondary thread into the second stage
4237 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4238 // The test succeeds if the secondary thread observes the transition
4239 // of `state` from 1 to 2, despite having a whole second to overtake
4240 // the primary thread.
4241 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004242 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004243 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004244 assert!(db
4245 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004246 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004247 domain: Domain::APP,
4248 nspace: 0,
4249 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4250 blob: None,
4251 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004252 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004253 KeyEntryLoadBits::BOTH,
4254 33,
4255 |_k, _av| Ok(()),
4256 )
4257 .is_ok());
4258 // We should only see a 2 here because we can only return
4259 // from load_key_entry when the `_key_guard` expires,
4260 // which happens at the end of the scope.
4261 assert_eq!(2, state2.load(Ordering::Relaxed));
4262 });
4263
4264 thread::sleep(std::time::Duration::from_millis(1000));
4265
4266 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4267
4268 // Return the handle from this scope so we can join with the
4269 // secondary thread after the key id lock has expired.
4270 handle
4271 // This is where the `_key_guard` goes out of scope,
4272 // which is the reason for concurrent load_key_entry on the same key
4273 // to unblock.
4274 };
4275 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4276 // main test thread. We will not see failing asserts in secondary threads otherwise.
4277 handle.join().unwrap();
4278 Ok(())
4279 }
4280
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004281 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004282 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004283 let temp_dir =
4284 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4285
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004286 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4287 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004288
4289 let _tx1 = db1
4290 .conn
4291 .transaction_with_behavior(TransactionBehavior::Immediate)
4292 .expect("Failed to create first transaction.");
4293
4294 let error = db2
4295 .conn
4296 .transaction_with_behavior(TransactionBehavior::Immediate)
4297 .context("Transaction begin failed.")
4298 .expect_err("This should fail.");
4299 let root_cause = error.root_cause();
4300 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4301 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4302 {
4303 return;
4304 }
4305 panic!(
4306 "Unexpected error {:?} \n{:?} \n{:?}",
4307 error,
4308 root_cause,
4309 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4310 )
4311 }
4312
4313 #[cfg(disabled)]
4314 #[test]
4315 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4316 let temp_dir = Arc::new(
4317 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4318 .expect("Failed to create temp dir."),
4319 );
4320
4321 let test_begin = Instant::now();
4322
Janis Danisevskis66784c42021-01-27 08:40:25 -08004323 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004324 let mut db =
4325 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004326 const OPEN_DB_COUNT: u32 = 50u32;
4327
4328 let mut actual_key_count = KEY_COUNT;
4329 // First insert KEY_COUNT keys.
4330 for count in 0..KEY_COUNT {
4331 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4332 actual_key_count = count;
4333 break;
4334 }
4335 let alias = format!("test_alias_{}", count);
4336 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4337 .expect("Failed to make key entry.");
4338 }
4339
4340 // Insert more keys from a different thread and into a different namespace.
4341 let temp_dir1 = temp_dir.clone();
4342 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004343 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4344 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004345
4346 for count in 0..actual_key_count {
4347 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4348 return;
4349 }
4350 let alias = format!("test_alias_{}", count);
4351 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4352 .expect("Failed to make key entry.");
4353 }
4354
4355 // then unbind them again.
4356 for count in 0..actual_key_count {
4357 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4358 return;
4359 }
4360 let key = KeyDescriptor {
4361 domain: Domain::APP,
4362 nspace: -1,
4363 alias: Some(format!("test_alias_{}", count)),
4364 blob: None,
4365 };
4366 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4367 }
4368 });
4369
4370 // And start unbinding the first set of keys.
4371 let temp_dir2 = temp_dir.clone();
4372 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004373 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4374 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004375
4376 for count in 0..actual_key_count {
4377 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4378 return;
4379 }
4380 let key = KeyDescriptor {
4381 domain: Domain::APP,
4382 nspace: -1,
4383 alias: Some(format!("test_alias_{}", count)),
4384 blob: None,
4385 };
4386 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4387 }
4388 });
4389
Janis Danisevskis66784c42021-01-27 08:40:25 -08004390 // While a lot of inserting and deleting is going on we have to open database connections
4391 // successfully and use them.
4392 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4393 // out of scope.
4394 #[allow(clippy::redundant_clone)]
4395 let temp_dir4 = temp_dir.clone();
4396 let handle4 = thread::spawn(move || {
4397 for count in 0..OPEN_DB_COUNT {
4398 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4399 return;
4400 }
Seth Moore444b51a2021-06-11 09:49:49 -07004401 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4402 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004403
4404 let alias = format!("test_alias_{}", count);
4405 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4406 .expect("Failed to make key entry.");
4407 let key = KeyDescriptor {
4408 domain: Domain::APP,
4409 nspace: -1,
4410 alias: Some(alias),
4411 blob: None,
4412 };
4413 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4414 }
4415 });
4416
4417 handle1.join().expect("Thread 1 panicked.");
4418 handle2.join().expect("Thread 2 panicked.");
4419 handle4.join().expect("Thread 4 panicked.");
4420
Janis Danisevskis66784c42021-01-27 08:40:25 -08004421 Ok(())
4422 }
4423
4424 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004425 fn list() -> Result<()> {
4426 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004427 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004428 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4429 (Domain::APP, 1, "test1"),
4430 (Domain::APP, 1, "test2"),
4431 (Domain::APP, 1, "test3"),
4432 (Domain::APP, 1, "test4"),
4433 (Domain::APP, 1, "test5"),
4434 (Domain::APP, 1, "test6"),
4435 (Domain::APP, 1, "test7"),
4436 (Domain::APP, 2, "test1"),
4437 (Domain::APP, 2, "test2"),
4438 (Domain::APP, 2, "test3"),
4439 (Domain::APP, 2, "test4"),
4440 (Domain::APP, 2, "test5"),
4441 (Domain::APP, 2, "test6"),
4442 (Domain::APP, 2, "test8"),
4443 (Domain::SELINUX, 100, "test1"),
4444 (Domain::SELINUX, 100, "test2"),
4445 (Domain::SELINUX, 100, "test3"),
4446 (Domain::SELINUX, 100, "test4"),
4447 (Domain::SELINUX, 100, "test5"),
4448 (Domain::SELINUX, 100, "test6"),
4449 (Domain::SELINUX, 100, "test9"),
4450 ];
4451
4452 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4453 .iter()
4454 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004455 let entry =
4456 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004457 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4458 });
4459 (entry.id(), *ns)
4460 })
4461 .collect();
4462
4463 for (domain, namespace) in
4464 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4465 {
4466 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4467 .iter()
4468 .filter_map(|(domain, ns, alias)| match ns {
4469 ns if *ns == *namespace => Some(KeyDescriptor {
4470 domain: *domain,
4471 nspace: *ns,
4472 alias: Some(alias.to_string()),
4473 blob: None,
4474 }),
4475 _ => None,
4476 })
4477 .collect();
4478 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004479 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004480 list_result.sort();
4481 assert_eq!(list_o_descriptors, list_result);
4482
4483 let mut list_o_ids: Vec<i64> = list_o_descriptors
4484 .into_iter()
4485 .map(|d| {
4486 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004487 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004488 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004489 KeyType::Client,
4490 KeyEntryLoadBits::NONE,
4491 *namespace as u32,
4492 |_, _| Ok(()),
4493 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004494 .unwrap();
4495 entry.id()
4496 })
4497 .collect();
4498 list_o_ids.sort_unstable();
4499 let mut loaded_entries: Vec<i64> = list_o_keys
4500 .iter()
4501 .filter_map(|(id, ns)| match ns {
4502 ns if *ns == *namespace => Some(*id),
4503 _ => None,
4504 })
4505 .collect();
4506 loaded_entries.sort_unstable();
4507 assert_eq!(list_o_ids, loaded_entries);
4508 }
Eran Messeri24f31972023-01-25 17:00:33 +00004509 assert_eq!(
4510 Vec::<KeyDescriptor>::new(),
4511 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4512 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004513
4514 Ok(())
4515 }
4516
Joel Galenson0891bc12020-07-20 10:37:03 -07004517 // Helpers
4518
4519 // Checks that the given result is an error containing the given string.
4520 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4521 let error_str = format!(
4522 "{:#?}",
4523 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4524 );
4525 assert!(
4526 error_str.contains(target),
4527 "The string \"{}\" should contain \"{}\"",
4528 error_str,
4529 target
4530 );
4531 }
4532
Joel Galenson2aab4432020-07-22 15:27:57 -07004533 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004534 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004535 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004536 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004537 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004538 namespace: Option<i64>,
4539 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004540 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004541 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004542 }
4543
4544 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4545 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004546 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004547 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004548 Ok(KeyEntryRow {
4549 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004550 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004551 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004552 namespace: row.get(3)?,
4553 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004554 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004555 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004556 })
4557 })?
4558 .map(|r| r.context("Could not read keyentry row."))
4559 .collect::<Result<Vec<_>>>()
4560 }
4561
Eran Messeri4dc27b52024-01-09 12:43:31 +00004562 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4563 make_test_params_with_sids(max_usage_count, &[42])
4564 }
4565
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004566 // Note: The parameters and SecurityLevel associations are nonsensical. This
4567 // collection is only used to check if the parameters are preserved as expected by the
4568 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004569 fn make_test_params_with_sids(
4570 max_usage_count: Option<i32>,
4571 user_secure_ids: &[i64],
4572 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004573 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004574 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4575 KeyParameter::new(
4576 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4577 SecurityLevel::TRUSTED_ENVIRONMENT,
4578 ),
4579 KeyParameter::new(
4580 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4581 SecurityLevel::TRUSTED_ENVIRONMENT,
4582 ),
4583 KeyParameter::new(
4584 KeyParameterValue::Algorithm(Algorithm::RSA),
4585 SecurityLevel::TRUSTED_ENVIRONMENT,
4586 ),
4587 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4588 KeyParameter::new(
4589 KeyParameterValue::BlockMode(BlockMode::ECB),
4590 SecurityLevel::TRUSTED_ENVIRONMENT,
4591 ),
4592 KeyParameter::new(
4593 KeyParameterValue::BlockMode(BlockMode::GCM),
4594 SecurityLevel::TRUSTED_ENVIRONMENT,
4595 ),
4596 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4597 KeyParameter::new(
4598 KeyParameterValue::Digest(Digest::MD5),
4599 SecurityLevel::TRUSTED_ENVIRONMENT,
4600 ),
4601 KeyParameter::new(
4602 KeyParameterValue::Digest(Digest::SHA_2_224),
4603 SecurityLevel::TRUSTED_ENVIRONMENT,
4604 ),
4605 KeyParameter::new(
4606 KeyParameterValue::Digest(Digest::SHA_2_256),
4607 SecurityLevel::STRONGBOX,
4608 ),
4609 KeyParameter::new(
4610 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4611 SecurityLevel::TRUSTED_ENVIRONMENT,
4612 ),
4613 KeyParameter::new(
4614 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4615 SecurityLevel::TRUSTED_ENVIRONMENT,
4616 ),
4617 KeyParameter::new(
4618 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4619 SecurityLevel::STRONGBOX,
4620 ),
4621 KeyParameter::new(
4622 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4623 SecurityLevel::TRUSTED_ENVIRONMENT,
4624 ),
4625 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4626 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4627 KeyParameter::new(
4628 KeyParameterValue::EcCurve(EcCurve::P_224),
4629 SecurityLevel::TRUSTED_ENVIRONMENT,
4630 ),
4631 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4632 KeyParameter::new(
4633 KeyParameterValue::EcCurve(EcCurve::P_384),
4634 SecurityLevel::TRUSTED_ENVIRONMENT,
4635 ),
4636 KeyParameter::new(
4637 KeyParameterValue::EcCurve(EcCurve::P_521),
4638 SecurityLevel::TRUSTED_ENVIRONMENT,
4639 ),
4640 KeyParameter::new(
4641 KeyParameterValue::RSAPublicExponent(3),
4642 SecurityLevel::TRUSTED_ENVIRONMENT,
4643 ),
4644 KeyParameter::new(
4645 KeyParameterValue::IncludeUniqueID,
4646 SecurityLevel::TRUSTED_ENVIRONMENT,
4647 ),
4648 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4649 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4650 KeyParameter::new(
4651 KeyParameterValue::ActiveDateTime(1234567890),
4652 SecurityLevel::STRONGBOX,
4653 ),
4654 KeyParameter::new(
4655 KeyParameterValue::OriginationExpireDateTime(1234567890),
4656 SecurityLevel::TRUSTED_ENVIRONMENT,
4657 ),
4658 KeyParameter::new(
4659 KeyParameterValue::UsageExpireDateTime(1234567890),
4660 SecurityLevel::TRUSTED_ENVIRONMENT,
4661 ),
4662 KeyParameter::new(
4663 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4664 SecurityLevel::TRUSTED_ENVIRONMENT,
4665 ),
4666 KeyParameter::new(
4667 KeyParameterValue::MaxUsesPerBoot(1234567890),
4668 SecurityLevel::TRUSTED_ENVIRONMENT,
4669 ),
4670 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004671 KeyParameter::new(
4672 KeyParameterValue::NoAuthRequired,
4673 SecurityLevel::TRUSTED_ENVIRONMENT,
4674 ),
4675 KeyParameter::new(
4676 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4677 SecurityLevel::TRUSTED_ENVIRONMENT,
4678 ),
4679 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4680 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4681 KeyParameter::new(
4682 KeyParameterValue::TrustedUserPresenceRequired,
4683 SecurityLevel::TRUSTED_ENVIRONMENT,
4684 ),
4685 KeyParameter::new(
4686 KeyParameterValue::TrustedConfirmationRequired,
4687 SecurityLevel::TRUSTED_ENVIRONMENT,
4688 ),
4689 KeyParameter::new(
4690 KeyParameterValue::UnlockedDeviceRequired,
4691 SecurityLevel::TRUSTED_ENVIRONMENT,
4692 ),
4693 KeyParameter::new(
4694 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4695 SecurityLevel::SOFTWARE,
4696 ),
4697 KeyParameter::new(
4698 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4699 SecurityLevel::SOFTWARE,
4700 ),
4701 KeyParameter::new(
4702 KeyParameterValue::CreationDateTime(12345677890),
4703 SecurityLevel::SOFTWARE,
4704 ),
4705 KeyParameter::new(
4706 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4707 SecurityLevel::TRUSTED_ENVIRONMENT,
4708 ),
4709 KeyParameter::new(
4710 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4711 SecurityLevel::TRUSTED_ENVIRONMENT,
4712 ),
4713 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4714 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4715 KeyParameter::new(
4716 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4717 SecurityLevel::SOFTWARE,
4718 ),
4719 KeyParameter::new(
4720 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4721 SecurityLevel::TRUSTED_ENVIRONMENT,
4722 ),
4723 KeyParameter::new(
4724 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4725 SecurityLevel::TRUSTED_ENVIRONMENT,
4726 ),
4727 KeyParameter::new(
4728 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4729 SecurityLevel::TRUSTED_ENVIRONMENT,
4730 ),
4731 KeyParameter::new(
4732 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4733 SecurityLevel::TRUSTED_ENVIRONMENT,
4734 ),
4735 KeyParameter::new(
4736 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4737 SecurityLevel::TRUSTED_ENVIRONMENT,
4738 ),
4739 KeyParameter::new(
4740 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4741 SecurityLevel::TRUSTED_ENVIRONMENT,
4742 ),
4743 KeyParameter::new(
4744 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4745 SecurityLevel::TRUSTED_ENVIRONMENT,
4746 ),
4747 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004748 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4749 SecurityLevel::TRUSTED_ENVIRONMENT,
4750 ),
4751 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004752 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4753 SecurityLevel::TRUSTED_ENVIRONMENT,
4754 ),
4755 KeyParameter::new(
4756 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4757 SecurityLevel::TRUSTED_ENVIRONMENT,
4758 ),
4759 KeyParameter::new(
4760 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4761 SecurityLevel::TRUSTED_ENVIRONMENT,
4762 ),
4763 KeyParameter::new(
4764 KeyParameterValue::VendorPatchLevel(3),
4765 SecurityLevel::TRUSTED_ENVIRONMENT,
4766 ),
4767 KeyParameter::new(
4768 KeyParameterValue::BootPatchLevel(4),
4769 SecurityLevel::TRUSTED_ENVIRONMENT,
4770 ),
4771 KeyParameter::new(
4772 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4773 SecurityLevel::TRUSTED_ENVIRONMENT,
4774 ),
4775 KeyParameter::new(
4776 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4777 SecurityLevel::TRUSTED_ENVIRONMENT,
4778 ),
4779 KeyParameter::new(
4780 KeyParameterValue::MacLength(256),
4781 SecurityLevel::TRUSTED_ENVIRONMENT,
4782 ),
4783 KeyParameter::new(
4784 KeyParameterValue::ResetSinceIdRotation,
4785 SecurityLevel::TRUSTED_ENVIRONMENT,
4786 ),
4787 KeyParameter::new(
4788 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4789 SecurityLevel::TRUSTED_ENVIRONMENT,
4790 ),
Qi Wub9433b52020-12-01 14:52:46 +08004791 ];
4792 if let Some(value) = max_usage_count {
4793 params.push(KeyParameter::new(
4794 KeyParameterValue::UsageCountLimit(value),
4795 SecurityLevel::SOFTWARE,
4796 ));
4797 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004798
4799 for sid in user_secure_ids.iter() {
4800 params.push(KeyParameter::new(
4801 KeyParameterValue::UserSecureID(*sid),
4802 SecurityLevel::STRONGBOX,
4803 ));
4804 }
Qi Wub9433b52020-12-01 14:52:46 +08004805 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004806 }
4807
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004808 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004809 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004810 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004811 namespace: i64,
4812 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004813 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004814 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004815 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4816 }
4817
4818 pub fn make_test_key_entry_with_sids(
4819 db: &mut KeystoreDB,
4820 domain: Domain,
4821 namespace: i64,
4822 alias: &str,
4823 max_usage_count: Option<i32>,
4824 sids: &[i64],
4825 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004826 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004827 let mut blob_metadata = BlobMetaData::new();
4828 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4829 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4830 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4831 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4832 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4833
4834 db.set_blob(
4835 &key_id,
4836 SubComponentType::KEY_BLOB,
4837 Some(TEST_KEY_BLOB),
4838 Some(&blob_metadata),
4839 )?;
4840 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4841 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004842
Eran Messeri4dc27b52024-01-09 12:43:31 +00004843 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004844 db.insert_keyparameter(&key_id, &params)?;
4845
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004846 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004847 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004848 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004849 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004850 Ok(key_id)
4851 }
4852
Qi Wub9433b52020-12-01 14:52:46 +08004853 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4854 let params = make_test_params(max_usage_count);
4855
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004856 let mut blob_metadata = BlobMetaData::new();
4857 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4858 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4859 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4860 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4861 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4862
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004863 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004864 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004865
4866 KeyEntry {
4867 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004868 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004869 cert: Some(TEST_CERT_BLOB.to_vec()),
4870 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004871 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004872 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004873 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004874 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004875 }
4876 }
4877
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004878 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004879 db: &mut KeystoreDB,
4880 domain: Domain,
4881 namespace: i64,
4882 alias: &str,
4883 logical_only: bool,
4884 ) -> Result<KeyIdGuard> {
4885 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4886 let mut blob_metadata = BlobMetaData::new();
4887 if !logical_only {
4888 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4889 }
4890 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4891
4892 db.set_blob(
4893 &key_id,
4894 SubComponentType::KEY_BLOB,
4895 Some(TEST_KEY_BLOB),
4896 Some(&blob_metadata),
4897 )?;
4898 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4899 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4900
4901 let mut params = make_test_params(None);
4902 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4903
4904 db.insert_keyparameter(&key_id, &params)?;
4905
4906 let mut metadata = KeyMetaData::new();
4907 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4908 db.insert_key_metadata(&key_id, &metadata)?;
4909 rebind_alias(db, &key_id, alias, domain, namespace)?;
4910 Ok(key_id)
4911 }
4912
Eric Biggersb0478cf2023-10-27 03:55:29 +00004913 // Creates an app key that is marked as being superencrypted by the given
4914 // super key ID and that has the given authentication and unlocked device
4915 // parameters. This does not actually superencrypt the key blob.
4916 fn make_superencrypted_key_entry(
4917 db: &mut KeystoreDB,
4918 namespace: i64,
4919 alias: &str,
4920 requires_authentication: bool,
4921 requires_unlocked_device: bool,
4922 super_key_id: i64,
4923 ) -> Result<KeyIdGuard> {
4924 let domain = Domain::APP;
4925 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4926
4927 let mut blob_metadata = BlobMetaData::new();
4928 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4929 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4930 db.set_blob(
4931 &key_id,
4932 SubComponentType::KEY_BLOB,
4933 Some(TEST_KEY_BLOB),
4934 Some(&blob_metadata),
4935 )?;
4936
4937 let mut params = vec![];
4938 if requires_unlocked_device {
4939 params.push(KeyParameter::new(
4940 KeyParameterValue::UnlockedDeviceRequired,
4941 SecurityLevel::TRUSTED_ENVIRONMENT,
4942 ));
4943 }
4944 if requires_authentication {
4945 params.push(KeyParameter::new(
4946 KeyParameterValue::UserSecureID(42),
4947 SecurityLevel::TRUSTED_ENVIRONMENT,
4948 ));
4949 }
4950 db.insert_keyparameter(&key_id, &params)?;
4951
4952 let mut metadata = KeyMetaData::new();
4953 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4954 db.insert_key_metadata(&key_id, &metadata)?;
4955
4956 rebind_alias(db, &key_id, alias, domain, namespace)?;
4957 Ok(key_id)
4958 }
4959
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004960 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4961 let mut params = make_test_params(None);
4962 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4963
4964 let mut blob_metadata = BlobMetaData::new();
4965 if !logical_only {
4966 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4967 }
4968 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4969
4970 let mut metadata = KeyMetaData::new();
4971 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4972
4973 KeyEntry {
4974 id: key_id,
4975 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4976 cert: Some(TEST_CERT_BLOB.to_vec()),
4977 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4978 km_uuid: KEYSTORE_UUID,
4979 parameters: params,
4980 metadata,
4981 pure_cert: false,
4982 }
4983 }
4984
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004985 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004986 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004987 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004988 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004989 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004990 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004991 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004992 Ok((
4993 row.get(0)?,
4994 row.get(1)?,
4995 row.get(2)?,
4996 row.get(3)?,
4997 row.get(4)?,
4998 row.get(5)?,
4999 row.get(6)?,
5000 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005001 },
5002 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005003
5004 println!("Key entry table rows:");
5005 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005006 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005007 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005008 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5009 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005010 );
5011 }
5012 Ok(())
5013 }
5014
5015 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005016 let mut stmt = db
5017 .conn
5018 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005019 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005020 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5021 })?;
5022
5023 println!("Grant table rows:");
5024 for r in rows {
5025 let (id, gt, ki, av) = r.unwrap();
5026 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5027 }
5028 Ok(())
5029 }
5030
Joel Galenson0891bc12020-07-20 10:37:03 -07005031 // Use a custom random number generator that repeats each number once.
5032 // This allows us to test repeated elements.
5033
5034 thread_local! {
5035 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5036 }
5037
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005038 fn reset_random() {
5039 RANDOM_COUNTER.with(|counter| {
5040 *counter.borrow_mut() = 0;
5041 })
5042 }
5043
Joel Galenson0891bc12020-07-20 10:37:03 -07005044 pub fn random() -> i64 {
5045 RANDOM_COUNTER.with(|counter| {
5046 let result = *counter.borrow() / 2;
5047 *counter.borrow_mut() += 1;
5048 result
5049 })
5050 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005051
5052 #[test]
5053 fn test_last_off_body() -> Result<()> {
5054 let mut db = new_test_db()?;
Eric Biggers19b3b0d2024-01-31 22:46:47 +00005055 db.insert_last_off_body(BootTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005056 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005057 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005058 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005059 let one_second = Duration::from_secs(1);
5060 thread::sleep(one_second);
Eric Biggers19b3b0d2024-01-31 22:46:47 +00005061 db.update_last_off_body(BootTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005062 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005063 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005064 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005065 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005066 Ok(())
5067 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005068
5069 #[test]
5070 fn test_unbind_keys_for_user() -> Result<()> {
5071 let mut db = new_test_db()?;
5072 db.unbind_keys_for_user(1, false)?;
5073
5074 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5075 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5076 db.unbind_keys_for_user(2, false)?;
5077
Eran Messeri24f31972023-01-25 17:00:33 +00005078 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
5079 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005080
5081 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00005082 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005083
5084 Ok(())
5085 }
5086
5087 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005088 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5089 let mut db = new_test_db()?;
5090 let super_key = keystore2_crypto::generate_aes256_key()?;
5091 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5092 let (encrypted_super_key, metadata) =
5093 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5094
5095 let key_name_enc = SuperKeyType {
5096 alias: "test_super_key_1",
5097 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005098 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005099 };
5100
5101 let key_name_nonenc = SuperKeyType {
5102 alias: "test_super_key_2",
5103 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005104 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005105 };
5106
5107 // Install two super keys.
5108 db.store_super_key(
5109 1,
5110 &key_name_nonenc,
5111 &super_key,
5112 &BlobMetaData::new(),
5113 &KeyMetaData::new(),
5114 )?;
5115 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5116
5117 // Check that both can be found in the database.
5118 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5119 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5120
5121 // Install the same keys for a different user.
5122 db.store_super_key(
5123 2,
5124 &key_name_nonenc,
5125 &super_key,
5126 &BlobMetaData::new(),
5127 &KeyMetaData::new(),
5128 )?;
5129 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5130
5131 // Check that the second pair of keys can be found in the database.
5132 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5133 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5134
5135 // Delete only encrypted keys.
5136 db.unbind_keys_for_user(1, true)?;
5137
5138 // The encrypted superkey should be gone now.
5139 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5140 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5141
5142 // Reinsert the encrypted key.
5143 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5144
5145 // Check that both can be found in the database, again..
5146 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5147 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5148
5149 // Delete all even unencrypted keys.
5150 db.unbind_keys_for_user(1, false)?;
5151
5152 // Both should be gone now.
5153 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5154 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5155
5156 // Check that the second pair of keys was untouched.
5157 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5158 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5159
5160 Ok(())
5161 }
5162
Eric Biggersb0478cf2023-10-27 03:55:29 +00005163 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5164 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5165 }
5166
5167 // Tests the unbind_auth_bound_keys_for_user() function.
5168 #[test]
5169 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5170 let mut db = new_test_db()?;
5171 let user_id = 1;
5172 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5173 let other_user_id = 2;
5174 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5175 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5176
5177 // Create a superencryption key.
5178 let super_key = keystore2_crypto::generate_aes256_key()?;
5179 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5180 let (encrypted_super_key, blob_metadata) =
5181 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5182 db.store_super_key(
5183 user_id,
5184 super_key_type,
5185 &encrypted_super_key,
5186 &blob_metadata,
5187 &KeyMetaData::new(),
5188 )?;
5189 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5190
5191 // Store 4 superencrypted app keys, one for each possible combination of
5192 // (authentication required, unlocked device required).
5193 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5194 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5195 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5196 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5197 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5198 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5199 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5200 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5201
5202 // Also store a key for a different user that requires authentication.
5203 make_superencrypted_key_entry(
5204 &mut db,
5205 other_user_nspace,
5206 "auth_ud",
5207 true,
5208 true,
5209 super_key_id,
5210 )?;
5211
5212 db.unbind_auth_bound_keys_for_user(user_id)?;
5213
5214 // Verify that only the user's app keys that require authentication were
5215 // deleted. Keys that require an unlocked device but not authentication
5216 // should *not* have been deleted, nor should the super key have been
5217 // deleted, nor should other users' keys have been deleted.
5218 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5219 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5220 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5221 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5222 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5223 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5224
5225 Ok(())
5226 }
5227
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005228 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005229 fn test_store_super_key() -> Result<()> {
5230 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005231 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005232 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005233 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005234 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005235 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005236
5237 let (encrypted_super_key, metadata) =
5238 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005239 db.store_super_key(
5240 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005241 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005242 &encrypted_super_key,
5243 &metadata,
5244 &KeyMetaData::new(),
5245 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005246
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005247 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005248 assert!(db.key_exists(
5249 Domain::APP,
5250 1,
5251 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5252 KeyType::Super
5253 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005254
Eric Biggers673d34a2023-10-18 01:54:18 +00005255 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005256 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005257 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005258 key_entry,
5259 &pw,
5260 None,
5261 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005262
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005263 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005264 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005265
Hasini Gunasingheda895552021-01-27 19:34:37 +00005266 Ok(())
5267 }
Seth Moore78c091f2021-04-09 21:38:30 +00005268
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005269 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005270 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005271 MetricsStorage::KEY_ENTRY,
5272 MetricsStorage::KEY_ENTRY_ID_INDEX,
5273 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5274 MetricsStorage::BLOB_ENTRY,
5275 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5276 MetricsStorage::KEY_PARAMETER,
5277 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5278 MetricsStorage::KEY_METADATA,
5279 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5280 MetricsStorage::GRANT,
5281 MetricsStorage::AUTH_TOKEN,
5282 MetricsStorage::BLOB_METADATA,
5283 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005284 ]
5285 }
5286
5287 /// Perform a simple check to ensure that we can query all the storage types
5288 /// that are supported by the DB. Check for reasonable values.
5289 #[test]
5290 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005291 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005292
5293 let mut db = new_test_db()?;
5294
5295 for t in get_valid_statsd_storage_types() {
5296 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005297 // AuthToken can be less than a page since it's in a btree, not sqlite
5298 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005299 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005300 } else {
5301 assert!(stat.size >= PAGE_SIZE);
5302 }
Seth Moore78c091f2021-04-09 21:38:30 +00005303 assert!(stat.size >= stat.unused_size);
5304 }
5305
5306 Ok(())
5307 }
5308
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005309 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005310 get_valid_statsd_storage_types()
5311 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005312 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005313 .collect()
5314 }
5315
5316 fn assert_storage_increased(
5317 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005318 increased_storage_types: Vec<MetricsStorage>,
5319 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005320 ) {
5321 for storage in increased_storage_types {
5322 // Verify the expected storage increased.
5323 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005324 let old = &baseline[&storage.0];
5325 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005326 assert!(
5327 new.unused_size <= old.unused_size,
5328 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005329 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005330 new.unused_size,
5331 old.unused_size
5332 );
5333
5334 // Update the baseline with the new value so that it succeeds in the
5335 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005336 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005337 }
5338
5339 // Get an updated map of the storage and verify there were no unexpected changes.
5340 let updated_stats = get_storage_stats_map(db);
5341 assert_eq!(updated_stats.len(), baseline.len());
5342
5343 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005344 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005345 let mut s = String::new();
5346 for &k in map.keys() {
5347 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5348 .expect("string concat failed");
5349 }
5350 s
5351 };
5352
5353 assert!(
5354 updated_stats[&k].size == baseline[&k].size
5355 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5356 "updated_stats:\n{}\nbaseline:\n{}",
5357 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005358 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005359 );
5360 }
5361 }
5362
5363 #[test]
5364 fn test_verify_key_table_size_reporting() -> Result<()> {
5365 let mut db = new_test_db()?;
5366 let mut working_stats = get_storage_stats_map(&mut db);
5367
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005368 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005369 assert_storage_increased(
5370 &mut db,
5371 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005372 MetricsStorage::KEY_ENTRY,
5373 MetricsStorage::KEY_ENTRY_ID_INDEX,
5374 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005375 ],
5376 &mut working_stats,
5377 );
5378
5379 let mut blob_metadata = BlobMetaData::new();
5380 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5381 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5382 assert_storage_increased(
5383 &mut db,
5384 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005385 MetricsStorage::BLOB_ENTRY,
5386 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5387 MetricsStorage::BLOB_METADATA,
5388 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005389 ],
5390 &mut working_stats,
5391 );
5392
5393 let params = make_test_params(None);
5394 db.insert_keyparameter(&key_id, &params)?;
5395 assert_storage_increased(
5396 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005397 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005398 &mut working_stats,
5399 );
5400
5401 let mut metadata = KeyMetaData::new();
5402 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5403 db.insert_key_metadata(&key_id, &metadata)?;
5404 assert_storage_increased(
5405 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005406 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005407 &mut working_stats,
5408 );
5409
5410 let mut sum = 0;
5411 for stat in working_stats.values() {
5412 sum += stat.size;
5413 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005414 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005415 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5416
5417 Ok(())
5418 }
5419
5420 #[test]
5421 fn test_verify_auth_table_size_reporting() -> Result<()> {
5422 let mut db = new_test_db()?;
5423 let mut working_stats = get_storage_stats_map(&mut db);
5424 db.insert_auth_token(&HardwareAuthToken {
5425 challenge: 123,
5426 userId: 456,
5427 authenticatorId: 789,
5428 authenticatorType: kmhw_authenticator_type::ANY,
5429 timestamp: Timestamp { milliSeconds: 10 },
5430 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005431 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005432 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005433 Ok(())
5434 }
5435
5436 #[test]
5437 fn test_verify_grant_table_size_reporting() -> Result<()> {
5438 const OWNER: i64 = 1;
5439 let mut db = new_test_db()?;
5440 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5441
5442 let mut working_stats = get_storage_stats_map(&mut db);
5443 db.grant(
5444 &KeyDescriptor {
5445 domain: Domain::APP,
5446 nspace: 0,
5447 alias: Some(TEST_ALIAS.to_string()),
5448 blob: None,
5449 },
5450 OWNER as u32,
5451 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005452 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005453 |_, _| Ok(()),
5454 )?;
5455
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005456 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005457
5458 Ok(())
5459 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005460
5461 #[test]
5462 fn find_auth_token_entry_returns_latest() -> Result<()> {
5463 let mut db = new_test_db()?;
5464 db.insert_auth_token(&HardwareAuthToken {
5465 challenge: 123,
5466 userId: 456,
5467 authenticatorId: 789,
5468 authenticatorType: kmhw_authenticator_type::ANY,
5469 timestamp: Timestamp { milliSeconds: 10 },
5470 mac: b"mac0".to_vec(),
5471 });
5472 std::thread::sleep(std::time::Duration::from_millis(1));
5473 db.insert_auth_token(&HardwareAuthToken {
5474 challenge: 123,
5475 userId: 457,
5476 authenticatorId: 789,
5477 authenticatorType: kmhw_authenticator_type::ANY,
5478 timestamp: Timestamp { milliSeconds: 12 },
5479 mac: b"mac1".to_vec(),
5480 });
5481 std::thread::sleep(std::time::Duration::from_millis(1));
5482 db.insert_auth_token(&HardwareAuthToken {
5483 challenge: 123,
5484 userId: 458,
5485 authenticatorId: 789,
5486 authenticatorType: kmhw_authenticator_type::ANY,
5487 timestamp: Timestamp { milliSeconds: 3 },
5488 mac: b"mac2".to_vec(),
5489 });
5490 // All three entries are in the database
5491 assert_eq!(db.perboot.auth_tokens_len(), 3);
5492 // It selected the most recent timestamp
5493 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5494 Ok(())
5495 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005496
5497 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005498 fn test_load_key_descriptor() -> Result<()> {
5499 let mut db = new_test_db()?;
5500 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5501
5502 let key = db.load_key_descriptor(key_id)?.unwrap();
5503
5504 assert_eq!(key.domain, Domain::APP);
5505 assert_eq!(key.nspace, 1);
5506 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5507
5508 // No such id
5509 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5510 Ok(())
5511 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005512
5513 #[test]
5514 fn test_get_list_app_uids_for_sid() -> Result<()> {
5515 let uid: i32 = 1;
5516 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5517 let first_sid = 667;
5518 let second_sid = 669;
5519 let first_app_id: i64 = 123 + uid_offset;
5520 let second_app_id: i64 = 456 + uid_offset;
5521 let third_app_id: i64 = 789 + uid_offset;
5522 let unrelated_app_id: i64 = 1011 + uid_offset;
5523 let mut db = new_test_db()?;
5524 make_test_key_entry_with_sids(
5525 &mut db,
5526 Domain::APP,
5527 first_app_id,
5528 TEST_ALIAS,
5529 None,
5530 &[first_sid],
5531 )
5532 .context("test_get_list_app_uids_for_sid")?;
5533 make_test_key_entry_with_sids(
5534 &mut db,
5535 Domain::APP,
5536 second_app_id,
5537 "alias2",
5538 None,
5539 &[first_sid],
5540 )
5541 .context("test_get_list_app_uids_for_sid")?;
5542 make_test_key_entry_with_sids(
5543 &mut db,
5544 Domain::APP,
5545 second_app_id,
5546 TEST_ALIAS,
5547 None,
5548 &[second_sid],
5549 )
5550 .context("test_get_list_app_uids_for_sid")?;
5551 make_test_key_entry_with_sids(
5552 &mut db,
5553 Domain::APP,
5554 third_app_id,
5555 "alias3",
5556 None,
5557 &[second_sid],
5558 )
5559 .context("test_get_list_app_uids_for_sid")?;
5560 make_test_key_entry_with_sids(
5561 &mut db,
5562 Domain::APP,
5563 unrelated_app_id,
5564 TEST_ALIAS,
5565 None,
5566 &[],
5567 )
5568 .context("test_get_list_app_uids_for_sid")?;
5569
5570 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5571 first_sid_apps.sort();
5572 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5573 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5574 second_sid_apps.sort();
5575 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5576 Ok(())
5577 }
5578
5579 #[test]
5580 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5581 let uid: i32 = 1;
5582 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5583 let first_sid = 667;
5584 let second_sid = 669;
5585 let third_sid = 772;
5586 let first_app_id: i64 = 123 + uid_offset;
5587 let second_app_id: i64 = 456 + uid_offset;
5588 let mut db = new_test_db()?;
5589 make_test_key_entry_with_sids(
5590 &mut db,
5591 Domain::APP,
5592 first_app_id,
5593 TEST_ALIAS,
5594 None,
5595 &[first_sid, second_sid],
5596 )
5597 .context("test_get_list_app_uids_for_sid")?;
5598 make_test_key_entry_with_sids(
5599 &mut db,
5600 Domain::APP,
5601 second_app_id,
5602 "alias2",
5603 None,
5604 &[second_sid, third_sid],
5605 )
5606 .context("test_get_list_app_uids_for_sid")?;
5607
5608 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5609 assert_eq!(first_sid_apps, vec![first_app_id]);
5610
5611 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5612 second_sid_apps.sort();
5613 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5614
5615 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5616 assert_eq!(third_sid_apps, vec![second_app_id]);
5617 Ok(())
5618 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005619}