blob: 2757313f547bf5525cfd8f9018e05a7695032b36 [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 {
James Farrellefe1a2f2024-02-28 21:36:47 +00001470 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001471 .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)
James Farrellefe1a2f2024-02-28 21:36:47 +00001478 });
1479 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001480 Ok(result) => break Ok(result),
1481 Err(e) => {
1482 if Self::is_locked_error(&e) {
1483 std::thread::sleep(std::time::Duration::from_micros(500));
1484 continue;
1485 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001486 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001487 }
1488 }
1489 }
1490 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001491 .map(|(need_gc, result)| {
1492 if need_gc {
1493 if let Some(ref gc) = self.gc {
1494 gc.notify_gc();
1495 }
1496 }
1497 result
1498 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001499 }
1500
1501 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001502 matches!(
1503 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1504 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1505 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1506 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001507 }
1508
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001509 /// Creates a new key entry and allocates a new randomized id for the new key.
1510 /// The key id gets associated with a domain and namespace but not with an alias.
1511 /// To complete key generation `rebind_alias` should be called after all of the
1512 /// key artifacts, i.e., blobs and parameters have been associated with the new
1513 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1514 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001515 pub fn create_key_entry(
1516 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001517 domain: &Domain,
1518 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001519 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001520 km_uuid: &Uuid,
1521 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001522 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1523
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001524 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001525 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001526 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001527 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 }
1529
1530 fn create_key_entry_internal(
1531 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001532 domain: &Domain,
1533 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001534 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001535 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001536 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001537 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001538 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001539 _ => {
1540 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001541 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001542 }
1543 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001544 Ok(KEY_ID_LOCK.get(
1545 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001546 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001547 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001548 (id, key_type, domain, namespace, alias, state, km_uuid)
1549 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001550 params![
1551 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001552 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001553 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001554 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001555 KeyLifeCycle::Existing,
1556 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001557 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001558 )
1559 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001560 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001561 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001562 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001563
Janis Danisevskis377d1002021-01-27 19:07:48 -08001564 /// Set a new blob and associates it with the given key id. Each blob
1565 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001566 /// Each key can have one of each sub component type associated. If more
1567 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001568 /// will get garbage collected.
1569 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1570 /// removed by setting blob to None.
1571 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001572 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001573 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001574 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001575 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001576 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001577 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001578 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1579
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001580 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001581 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001582 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001583 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001584 }
1585
Janis Danisevskiseed69842021-02-18 20:04:10 -08001586 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1587 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1588 /// We use this to insert key blobs into the database which can then be garbage collected
1589 /// lazily by the key garbage collector.
1590 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001591 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1592
Janis Danisevskiseed69842021-02-18 20:04:10 -08001593 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1594 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001595 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001596 Self::UNASSIGNED_KEY_ID,
1597 SubComponentType::KEY_BLOB,
1598 Some(blob),
1599 Some(blob_metadata),
1600 )
1601 .need_gc()
1602 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001603 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001604 }
1605
Janis Danisevskis377d1002021-01-27 19:07:48 -08001606 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001607 tx: &Transaction,
1608 key_id: i64,
1609 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001610 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001611 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001612 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001613 match (blob, sc_type) {
1614 (Some(blob), _) => {
1615 tx.execute(
1616 "INSERT INTO persistent.blobentry
1617 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1618 params![sc_type, key_id, blob],
1619 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001620 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001621 if let Some(blob_metadata) = blob_metadata {
1622 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001623 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001624 row.get(0)
1625 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001626 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001627 blob_metadata
1628 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001629 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001630 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001631 }
1632 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1633 tx.execute(
1634 "DELETE FROM persistent.blobentry
1635 WHERE subcomponent_type = ? AND keyentryid = ?;",
1636 params![sc_type, key_id],
1637 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001638 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001639 }
1640 (None, _) => {
1641 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001642 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001643 }
1644 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001645 Ok(())
1646 }
1647
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001648 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1649 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001650 #[cfg(test)]
1651 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001652 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001653 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001654 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001655 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001656 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001657
Janis Danisevskis66784c42021-01-27 08:40:25 -08001658 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001659 tx: &Transaction,
1660 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001661 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001662 ) -> Result<()> {
1663 let mut stmt = tx
1664 .prepare(
1665 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1666 VALUES (?, ?, ?, ?);",
1667 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001668 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001669
Janis Danisevskis66784c42021-01-27 08:40:25 -08001670 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001671 stmt.insert(params![
1672 key_id.0,
1673 p.get_tag().0,
1674 p.key_parameter_value(),
1675 p.security_level().0
1676 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001677 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001678 }
1679 Ok(())
1680 }
1681
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001682 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001683 #[cfg(test)]
1684 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001686 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001687 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001688 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001689 }
1690
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001691 /// Updates the alias column of the given key id `newid` with the given alias,
1692 /// and atomically, removes the alias, domain, and namespace from another row
1693 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001694 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1695 /// collector.
1696 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001697 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001698 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001699 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001700 domain: &Domain,
1701 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001702 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001703 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001704 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001705 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001706 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001707 return Err(KsError::sys())
1708 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001709 }
1710 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001711 let updated = tx
1712 .execute(
1713 "UPDATE persistent.keyentry
1714 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001715 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1716 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001717 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001718 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001719 let result = tx
1720 .execute(
1721 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001722 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001723 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001724 params![
1725 alias,
1726 KeyLifeCycle::Live,
1727 newid.0,
1728 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001729 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001730 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001731 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001732 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001733 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001734 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001735 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001736 return Err(KsError::sys()).context(ks_err!(
1737 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001738 result
1739 ));
1740 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001741 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001742 }
1743
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001744 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1745 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1746 pub fn migrate_key_namespace(
1747 &mut self,
1748 key_id_guard: KeyIdGuard,
1749 destination: &KeyDescriptor,
1750 caller_uid: u32,
1751 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1752 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001753 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1754
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001755 let destination = match destination.domain {
1756 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1757 Domain::SELINUX => (*destination).clone(),
1758 domain => {
1759 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1760 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1761 }
1762 };
1763
1764 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001765 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001766
1767 let alias = destination
1768 .alias
1769 .as_ref()
1770 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001771 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001772
1773 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1774 // Query the destination location. If there is a key, the migration request fails.
1775 if tx
1776 .query_row(
1777 "SELECT id FROM persistent.keyentry
1778 WHERE alias = ? AND domain = ? AND namespace = ?;",
1779 params![alias, destination.domain.0, destination.nspace],
1780 |_| Ok(()),
1781 )
1782 .optional()
1783 .context("Failed to query destination.")?
1784 .is_some()
1785 {
1786 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1787 .context("Target already exists.");
1788 }
1789
1790 let updated = tx
1791 .execute(
1792 "UPDATE persistent.keyentry
1793 SET alias = ?, domain = ?, namespace = ?
1794 WHERE id = ?;",
1795 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1796 )
1797 .context("Failed to update key entry.")?;
1798
1799 if updated != 1 {
1800 return Err(KsError::sys())
1801 .context(format!("Update succeeded, but {} rows were updated.", updated));
1802 }
1803 Ok(()).no_gc()
1804 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001805 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001806 }
1807
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001808 /// Store a new key in a single transaction.
1809 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1810 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001811 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1812 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001813 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001814 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001815 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001816 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001817 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001818 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001819 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001820 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001821 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001822 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001823 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001824 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1825
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001826 let (alias, domain, namespace) = match key {
1827 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1828 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1829 (alias, key.domain, nspace)
1830 }
1831 _ => {
1832 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001833 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001834 }
1835 };
1836 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001837 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001838 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001839 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1840
1841 // In some occasions the key blob is already upgraded during the import.
1842 // In order to make sure it gets properly deleted it is inserted into the
1843 // database here and then immediately replaced by the superseding blob.
1844 // The garbage collector will then subject the blob to deleteKey of the
1845 // KM back end to permanently invalidate the key.
1846 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1847 Self::set_blob_internal(
1848 tx,
1849 key_id.id(),
1850 SubComponentType::KEY_BLOB,
1851 Some(blob),
1852 Some(blob_metadata),
1853 )
1854 .context("Trying to insert superseded key blob.")?;
1855 true
1856 } else {
1857 false
1858 };
1859
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001860 Self::set_blob_internal(
1861 tx,
1862 key_id.id(),
1863 SubComponentType::KEY_BLOB,
1864 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001865 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001866 )
1867 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001868 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001869 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001870 .context("Trying to insert the certificate.")?;
1871 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001872 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001873 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001874 tx,
1875 key_id.id(),
1876 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001877 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001878 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001879 )
1880 .context("Trying to insert the certificate chain.")?;
1881 }
1882 Self::insert_keyparameter_internal(tx, &key_id, params)
1883 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001884 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001885 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001886 .context("Trying to rebind alias.")?
1887 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001888 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001889 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001890 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001891 }
1892
Janis Danisevskis377d1002021-01-27 19:07:48 -08001893 /// Store a new certificate
1894 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1895 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001896 pub fn store_new_certificate(
1897 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001898 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001899 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001900 cert: &[u8],
1901 km_uuid: &Uuid,
1902 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001903 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1904
Janis Danisevskis377d1002021-01-27 19:07:48 -08001905 let (alias, domain, namespace) = match key {
1906 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1907 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1908 (alias, key.domain, nspace)
1909 }
1910 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001911 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1912 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001913 }
1914 };
1915 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001916 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001917 .context("Trying to create new key entry.")?;
1918
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001919 Self::set_blob_internal(
1920 tx,
1921 key_id.id(),
1922 SubComponentType::CERT_CHAIN,
1923 Some(cert),
1924 None,
1925 )
1926 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001927
1928 let mut metadata = KeyMetaData::new();
1929 metadata.add(KeyMetaEntry::CreationDate(
1930 DateTime::now().context("Trying to make creation time.")?,
1931 ));
1932
1933 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1934
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001935 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001936 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001937 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001938 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001939 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001940 }
1941
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001942 // Helper function loading the key_id given the key descriptor
1943 // tuple comprising domain, namespace, and alias.
1944 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001945 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001946 let alias = key
1947 .alias
1948 .as_ref()
1949 .map_or_else(|| Err(KsError::sys()), Ok)
1950 .context("In load_key_entry_id: Alias must be specified.")?;
1951 let mut stmt = tx
1952 .prepare(
1953 "SELECT id FROM persistent.keyentry
1954 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001955 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001956 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001957 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001958 AND alias = ?
1959 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001960 )
1961 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1962 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001963 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001964 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001965 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001966 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001967 .get(0)
1968 .context("Failed to unpack id.")
1969 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001970 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001971 }
1972
1973 /// This helper function completes the access tuple of a key, which is required
1974 /// to perform access control. The strategy depends on the `domain` field in the
1975 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001976 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001977 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001978 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001979 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001980 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001981 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001982 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001983 /// `namespace`.
1984 /// In each case the information returned is sufficient to perform the access
1985 /// check and the key id can be used to load further key artifacts.
1986 fn load_access_tuple(
1987 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001988 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001989 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001990 caller_uid: u32,
1991 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1992 match key.domain {
1993 // Domain App or SELinux. In this case we load the key_id from
1994 // the keyentry database for further loading of key components.
1995 // We already have the full access tuple to perform access control.
1996 // The only distinction is that we use the caller_uid instead
1997 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001998 // Domain::APP.
1999 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002000 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002001 if access_key.domain == Domain::APP {
2002 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002003 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002004 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002005 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002006
2007 Ok((key_id, access_key, None))
2008 }
2009
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002010 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002011 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002012 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002013 let mut stmt = tx
2014 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002015 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002016 WHERE grantee = ? AND id = ? AND
2017 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002018 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002019 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002020 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002021 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002022 .context("Domain:Grant: query failed.")?;
2023 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002024 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002025 let r =
2026 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002027 Ok((
2028 r.get(0).context("Failed to unpack key_id.")?,
2029 r.get(1).context("Failed to unpack access_vector.")?,
2030 ))
2031 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002032 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002033 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002034 }
2035
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002036 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002037 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002038 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002039 let (domain, namespace): (Domain, i64) = {
2040 let mut stmt = tx
2041 .prepare(
2042 "SELECT domain, namespace FROM persistent.keyentry
2043 WHERE
2044 id = ?
2045 AND state = ?;",
2046 )
2047 .context("Domain::KEY_ID: prepare statement failed")?;
2048 let mut rows = stmt
2049 .query(params![key.nspace, KeyLifeCycle::Live])
2050 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002051 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002052 let r =
2053 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002054 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002055 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002056 r.get(1).context("Failed to unpack namespace.")?,
2057 ))
2058 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002059 .context("Domain::KEY_ID.")?
2060 };
2061
2062 // We may use a key by id after loading it by grant.
2063 // In this case we have to check if the caller has a grant for this particular
2064 // key. We can skip this if we already know that the caller is the owner.
2065 // But we cannot know this if domain is anything but App. E.g. in the case
2066 // of Domain::SELINUX we have to speculatively check for grants because we have to
2067 // consult the SEPolicy before we know if the caller is the owner.
2068 let access_vector: Option<KeyPermSet> =
2069 if domain != Domain::APP || namespace != caller_uid as i64 {
2070 let access_vector: Option<i32> = tx
2071 .query_row(
2072 "SELECT access_vector FROM persistent.grant
2073 WHERE grantee = ? AND keyentryid = ?;",
2074 params![caller_uid as i64, key.nspace],
2075 |row| row.get(0),
2076 )
2077 .optional()
2078 .context("Domain::KEY_ID: query grant failed.")?;
2079 access_vector.map(|p| p.into())
2080 } else {
2081 None
2082 };
2083
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002084 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002085 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002086 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002087 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002088
Janis Danisevskis45760022021-01-19 16:34:10 -08002089 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002090 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002091 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002092 }
2093 }
2094
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002095 fn load_blob_components(
2096 key_id: i64,
2097 load_bits: KeyEntryLoadBits,
2098 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002099 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002100 let mut stmt = tx
2101 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002102 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002103 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2104 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002105 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002106
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002107 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002108
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002109 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002110 let mut cert_blob: Option<Vec<u8>> = None;
2111 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002112 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002113 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002114 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002115 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002116 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002117 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2118 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002119 key_blob = Some((
2120 row.get(0).context("Failed to extract key blob id.")?,
2121 row.get(2).context("Failed to extract key blob.")?,
2122 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002123 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002124 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002125 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002126 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002127 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002128 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002129 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002130 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002131 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002132 (SubComponentType::CERT, _, _)
2133 | (SubComponentType::CERT_CHAIN, _, _)
2134 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002135 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2136 }
2137 Ok(())
2138 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002139 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002140
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002141 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2142 Ok(Some((
2143 blob,
2144 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002145 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002146 )))
2147 })?;
2148
2149 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002150 }
2151
2152 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2153 let mut stmt = tx
2154 .prepare(
2155 "SELECT tag, data, security_level from persistent.keyparameter
2156 WHERE keyentryid = ?;",
2157 )
2158 .context("In load_key_parameters: prepare statement failed.")?;
2159
2160 let mut parameters: Vec<KeyParameter> = Vec::new();
2161
2162 let mut rows =
2163 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002164 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002165 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2166 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002167 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002168 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002169 .context("Failed to read KeyParameter.")?,
2170 );
2171 Ok(())
2172 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002173 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002174
2175 Ok(parameters)
2176 }
2177
Qi Wub9433b52020-12-01 14:52:46 +08002178 /// Decrements the usage count of a limited use key. This function first checks whether the
2179 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2180 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2181 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002182 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002183 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2184
Qi Wub9433b52020-12-01 14:52:46 +08002185 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2186 let limit: Option<i32> = tx
2187 .query_row(
2188 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2189 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2190 |row| row.get(0),
2191 )
2192 .optional()
2193 .context("Trying to load usage count")?;
2194
2195 let limit = limit
2196 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2197 .context("The Key no longer exists. Key is exhausted.")?;
2198
2199 tx.execute(
2200 "UPDATE persistent.keyparameter
2201 SET data = data - 1
2202 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2203 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2204 )
2205 .context("Failed to update key usage count.")?;
2206
2207 match limit {
2208 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002209 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002210 .context("Trying to mark limited use key for deletion."),
2211 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002212 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002213 }
2214 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002215 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002216 }
2217
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002218 /// Load a key entry by the given key descriptor.
2219 /// It uses the `check_permission` callback to verify if the access is allowed
2220 /// given the key access tuple read from the database using `load_access_tuple`.
2221 /// With `load_bits` the caller may specify which blobs shall be loaded from
2222 /// the blob database.
2223 pub fn load_key_entry(
2224 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002225 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002226 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002227 load_bits: KeyEntryLoadBits,
2228 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002229 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2230 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002231 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2232
Janis Danisevskis66784c42021-01-27 08:40:25 -08002233 loop {
2234 match self.load_key_entry_internal(
2235 key,
2236 key_type,
2237 load_bits,
2238 caller_uid,
2239 &check_permission,
2240 ) {
2241 Ok(result) => break Ok(result),
2242 Err(e) => {
2243 if Self::is_locked_error(&e) {
2244 std::thread::sleep(std::time::Duration::from_micros(500));
2245 continue;
2246 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002247 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002248 }
2249 }
2250 }
2251 }
2252 }
2253
2254 fn load_key_entry_internal(
2255 &mut self,
2256 key: &KeyDescriptor,
2257 key_type: KeyType,
2258 load_bits: KeyEntryLoadBits,
2259 caller_uid: u32,
2260 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002261 ) -> Result<(KeyIdGuard, KeyEntry)> {
2262 // KEY ID LOCK 1/2
2263 // If we got a key descriptor with a key id we can get the lock right away.
2264 // Otherwise we have to defer it until we know the key id.
2265 let key_id_guard = match key.domain {
2266 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2267 _ => None,
2268 };
2269
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002270 let tx = self
2271 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002272 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002273 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002274
2275 // Load the key_id and complete the access control tuple.
2276 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002277 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002278
2279 // Perform access control. It is vital that we return here if the permission is denied.
2280 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002281 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002282
Janis Danisevskisaec14592020-11-12 09:41:49 -08002283 // KEY ID LOCK 2/2
2284 // If we did not get a key id lock by now, it was because we got a key descriptor
2285 // without a key id. At this point we got the key id, so we can try and get a lock.
2286 // However, we cannot block here, because we are in the middle of the transaction.
2287 // So first we try to get the lock non blocking. If that fails, we roll back the
2288 // transaction and block until we get the lock. After we successfully got the lock,
2289 // we start a new transaction and load the access tuple again.
2290 //
2291 // We don't need to perform access control again, because we already established
2292 // that the caller had access to the given key. But we need to make sure that the
2293 // key id still exists. So we have to load the key entry by key id this time.
2294 let (key_id_guard, tx) = match key_id_guard {
2295 None => match KEY_ID_LOCK.try_get(key_id) {
2296 None => {
2297 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002298 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002299
Janis Danisevskisaec14592020-11-12 09:41:49 -08002300 // Block until we have a key id lock.
2301 let key_id_guard = KEY_ID_LOCK.get(key_id);
2302
2303 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002304 let tx = self
2305 .conn
2306 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002307 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002308
2309 Self::load_access_tuple(
2310 &tx,
2311 // This time we have to load the key by the retrieved key id, because the
2312 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002313 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002314 domain: Domain::KEY_ID,
2315 nspace: key_id,
2316 ..Default::default()
2317 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002318 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002319 caller_uid,
2320 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002321 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002322 (key_id_guard, tx)
2323 }
2324 Some(l) => (l, tx),
2325 },
2326 Some(key_id_guard) => (key_id_guard, tx),
2327 };
2328
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002329 let key_entry =
2330 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002331
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002332 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002333
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002334 Ok((key_id_guard, key_entry))
2335 }
2336
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002337 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002338 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002339 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2340 .context("Trying to delete keyentry.")?;
2341 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2342 .context("Trying to delete keymetadata.")?;
2343 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2344 .context("Trying to delete keyparameters.")?;
2345 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2346 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002347 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002348 }
2349
2350 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002351 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002352 pub fn unbind_key(
2353 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002354 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002355 key_type: KeyType,
2356 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002357 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002358 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002359 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2360
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002361 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2362 let (key_id, access_key_descriptor, access_vector) =
2363 Self::load_access_tuple(tx, key, key_type, caller_uid)
2364 .context("Trying to get access tuple.")?;
2365
2366 // Perform access control. It is vital that we return here if the permission is denied.
2367 // So do not touch that '?' at the end.
2368 check_permission(&access_key_descriptor, access_vector)
2369 .context("While checking permission.")?;
2370
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002371 Self::mark_unreferenced(tx, key_id)
2372 .map(|need_gc| (need_gc, ()))
2373 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002374 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002375 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002376 }
2377
Max Bires8e93d2b2021-01-14 13:17:59 -08002378 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2379 tx.query_row(
2380 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2381 params![key_id],
2382 |row| row.get(0),
2383 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002384 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002385 }
2386
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002387 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2388 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2389 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002390 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2391
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002392 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002393 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002394 }
2395 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2396 tx.execute(
2397 "DELETE FROM persistent.keymetadata
2398 WHERE keyentryid IN (
2399 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002400 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002401 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002402 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002403 )
2404 .context("Trying to delete keymetadata.")?;
2405 tx.execute(
2406 "DELETE FROM persistent.keyparameter
2407 WHERE keyentryid IN (
2408 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002409 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002410 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002411 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002412 )
2413 .context("Trying to delete keyparameters.")?;
2414 tx.execute(
2415 "DELETE FROM persistent.grant
2416 WHERE keyentryid IN (
2417 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002418 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002419 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002420 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002421 )
2422 .context("Trying to delete grants.")?;
2423 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002424 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002425 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2426 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002427 )
2428 .context("Trying to delete keyentry.")?;
2429 Ok(()).need_gc()
2430 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002431 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002432 }
2433
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002434 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2435 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2436 {
2437 tx.execute(
2438 "DELETE FROM persistent.keymetadata
2439 WHERE keyentryid IN (
2440 SELECT id FROM persistent.keyentry
2441 WHERE state = ?
2442 );",
2443 params![KeyLifeCycle::Unreferenced],
2444 )
2445 .context("Trying to delete keymetadata.")?;
2446 tx.execute(
2447 "DELETE FROM persistent.keyparameter
2448 WHERE keyentryid IN (
2449 SELECT id FROM persistent.keyentry
2450 WHERE state = ?
2451 );",
2452 params![KeyLifeCycle::Unreferenced],
2453 )
2454 .context("Trying to delete keyparameters.")?;
2455 tx.execute(
2456 "DELETE FROM persistent.grant
2457 WHERE keyentryid IN (
2458 SELECT id FROM persistent.keyentry
2459 WHERE state = ?
2460 );",
2461 params![KeyLifeCycle::Unreferenced],
2462 )
2463 .context("Trying to delete grants.")?;
2464 tx.execute(
2465 "DELETE FROM persistent.keyentry
2466 WHERE state = ?;",
2467 params![KeyLifeCycle::Unreferenced],
2468 )
2469 .context("Trying to delete keyentry.")?;
2470 Result::<()>::Ok(())
2471 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002472 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002473 }
2474
Hasini Gunasingheda895552021-01-27 19:34:37 +00002475 /// Delete the keys created on behalf of the user, denoted by the user id.
2476 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2477 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2478 /// The caller of this function should notify the gc if the returned value is true.
2479 pub fn unbind_keys_for_user(
2480 &mut self,
2481 user_id: u32,
2482 keep_non_super_encrypted_keys: bool,
2483 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002484 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2485
Hasini Gunasingheda895552021-01-27 19:34:37 +00002486 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2487 let mut stmt = tx
2488 .prepare(&format!(
2489 "SELECT id from persistent.keyentry
2490 WHERE (
2491 key_type = ?
2492 AND domain = ?
2493 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2494 AND state = ?
2495 ) OR (
2496 key_type = ?
2497 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002498 AND state = ?
2499 );",
2500 aid_user_offset = AID_USER_OFFSET
2501 ))
2502 .context(concat!(
2503 "In unbind_keys_for_user. ",
2504 "Failed to prepare the query to find the keys created by apps."
2505 ))?;
2506
2507 let mut rows = stmt
2508 .query(params![
2509 // WHERE client key:
2510 KeyType::Client,
2511 Domain::APP.0 as u32,
2512 user_id,
2513 KeyLifeCycle::Live,
2514 // OR super key:
2515 KeyType::Super,
2516 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002517 KeyLifeCycle::Live
2518 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002519 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002520
2521 let mut key_ids: Vec<i64> = Vec::new();
2522 db_utils::with_rows_extract_all(&mut rows, |row| {
2523 key_ids
2524 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2525 Ok(())
2526 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002527 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002528
2529 let mut notify_gc = false;
2530 for key_id in key_ids {
2531 if keep_non_super_encrypted_keys {
2532 // Load metadata and filter out non-super-encrypted keys.
2533 if let (_, Some((_, blob_metadata)), _, _) =
2534 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002535 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002536 {
2537 if blob_metadata.encrypted_by().is_none() {
2538 continue;
2539 }
2540 }
2541 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002542 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002543 .context("In unbind_keys_for_user.")?
2544 || notify_gc;
2545 }
2546 Ok(()).do_gc(notify_gc)
2547 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002548 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002549 }
2550
Eric Biggersb0478cf2023-10-27 03:55:29 +00002551 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2552 /// This runs when the user's lock screen is being changed to Swipe or None.
2553 ///
2554 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2555 /// such keys also require user authentication. Keystore's concept of user authentication is
2556 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2557 /// authentication is no longer possible. In contrast, keys that just require that the device
2558 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2559 /// is always considered "unlocked" in that case.
2560 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2561 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2562
2563 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2564 let mut stmt = tx
2565 .prepare(&format!(
2566 "SELECT id from persistent.keyentry
2567 WHERE key_type = ?
2568 AND domain = ?
2569 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2570 AND state = ?;",
2571 aid_user_offset = AID_USER_OFFSET
2572 ))
2573 .context(concat!(
2574 "In unbind_auth_bound_keys_for_user. ",
2575 "Failed to prepare the query to find the keys created by apps."
2576 ))?;
2577
2578 let mut rows = stmt
2579 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2580 .context(ks_err!("Failed to query the keys created by apps."))?;
2581
2582 let mut key_ids: Vec<i64> = Vec::new();
2583 db_utils::with_rows_extract_all(&mut rows, |row| {
2584 key_ids
2585 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2586 Ok(())
2587 })
2588 .context(ks_err!())?;
2589
2590 let mut notify_gc = false;
2591 let mut num_unbound = 0;
2592 for key_id in key_ids {
2593 // Load the key parameters and filter out non-auth-bound keys. To identify
2594 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2595 // could also be used, but UserSecureID is what Keystore treats as authoritative
2596 // when actually enforcing the key parameters (it might not matter, though).
2597 let params = Self::load_key_parameters(key_id, tx)
2598 .context("Failed to load key parameters.")?;
2599 let is_auth_bound_key = params.iter().any(|kp| {
2600 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2601 });
2602 if is_auth_bound_key {
2603 notify_gc = Self::mark_unreferenced(tx, key_id)
2604 .context("In unbind_auth_bound_keys_for_user.")?
2605 || notify_gc;
2606 num_unbound += 1;
2607 }
2608 }
2609 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2610 Ok(()).do_gc(notify_gc)
2611 })
2612 .context(ks_err!())
2613 }
2614
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002615 fn load_key_components(
2616 tx: &Transaction,
2617 load_bits: KeyEntryLoadBits,
2618 key_id: i64,
2619 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002620 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002621
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002622 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002623 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002624
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002625 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002626 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002627
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002628 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002629 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002630
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002631 Ok(KeyEntry {
2632 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002633 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002634 cert: cert_blob,
2635 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002636 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002637 parameters,
2638 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002639 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002640 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002641 }
2642
Eran Messeri24f31972023-01-25 17:00:33 +00002643 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2644 /// aliases are greater than the specified 'start_past_alias'. If no value
2645 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002646 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002647 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002648 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002649 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002650 &mut self,
2651 domain: Domain,
2652 namespace: i64,
2653 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002654 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002655 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002656 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002657
Eran Messeri24f31972023-01-25 17:00:33 +00002658 let query = format!(
2659 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002660 WHERE domain = ?
2661 AND namespace = ?
2662 AND alias IS NOT NULL
2663 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002664 AND key_type = ?
2665 {}
2666 ORDER BY alias ASC;",
2667 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2668 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002669
Eran Messeri24f31972023-01-25 17:00:33 +00002670 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2671 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2672
2673 let mut rows = match start_past_alias {
2674 Some(past_alias) => stmt
2675 .query(params![
2676 domain.0 as u32,
2677 namespace,
2678 KeyLifeCycle::Live,
2679 key_type,
2680 past_alias
2681 ])
2682 .context(ks_err!("Failed to query."))?,
2683 None => stmt
2684 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2685 .context(ks_err!("Failed to query."))?,
2686 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002687
Janis Danisevskis66784c42021-01-27 08:40:25 -08002688 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2689 db_utils::with_rows_extract_all(&mut rows, |row| {
2690 descriptors.push(KeyDescriptor {
2691 domain,
2692 nspace: namespace,
2693 alias: Some(row.get(0).context("Trying to extract alias.")?),
2694 blob: None,
2695 });
2696 Ok(())
2697 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002698 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002699 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002700 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002701 }
2702
Eran Messeri24f31972023-01-25 17:00:33 +00002703 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2704 /// Domain must be APP or SELINUX, the caller must make sure of that.
2705 pub fn count_keys(
2706 &mut self,
2707 domain: Domain,
2708 namespace: i64,
2709 key_type: KeyType,
2710 ) -> Result<usize> {
2711 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2712
2713 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2714 tx.query_row(
2715 "SELECT COUNT(alias) FROM persistent.keyentry
2716 WHERE domain = ?
2717 AND namespace = ?
2718 AND alias IS NOT NULL
2719 AND state = ?
2720 AND key_type = ?;",
2721 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2722 |row| row.get(0),
2723 )
2724 .context(ks_err!("Failed to count number of keys."))
2725 .no_gc()
2726 })?;
2727 Ok(num_keys)
2728 }
2729
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002730 /// Adds a grant to the grant table.
2731 /// Like `load_key_entry` this function loads the access tuple before
2732 /// it uses the callback for a permission check. Upon success,
2733 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2734 /// grant table. The new row will have a randomized id, which is used as
2735 /// grant id in the namespace field of the resulting KeyDescriptor.
2736 pub fn grant(
2737 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002738 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002739 caller_uid: u32,
2740 grantee_uid: u32,
2741 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002742 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002743 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002744 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2745
Janis Danisevskis66784c42021-01-27 08:40:25 -08002746 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2747 // Load the key_id and complete the access control tuple.
2748 // We ignore the access vector here because grants cannot be granted.
2749 // The access vector returned here expresses the permissions the
2750 // grantee has if key.domain == Domain::GRANT. But this vector
2751 // cannot include the grant permission by design, so there is no way the
2752 // subsequent permission check can pass.
2753 // We could check key.domain == Domain::GRANT and fail early.
2754 // But even if we load the access tuple by grant here, the permission
2755 // check denies the attempt to create a grant by grant descriptor.
2756 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002757 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002758
Janis Danisevskis66784c42021-01-27 08:40:25 -08002759 // Perform access control. It is vital that we return here if the permission
2760 // was denied. So do not touch that '?' at the end of the line.
2761 // This permission check checks if the caller has the grant permission
2762 // for the given key and in addition to all of the permissions
2763 // expressed in `access_vector`.
2764 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002765 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002766
Janis Danisevskis66784c42021-01-27 08:40:25 -08002767 let grant_id = if let Some(grant_id) = tx
2768 .query_row(
2769 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002770 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002771 params![key_id, grantee_uid],
2772 |row| row.get(0),
2773 )
2774 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002775 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002776 {
2777 tx.execute(
2778 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002779 SET access_vector = ?
2780 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002781 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002782 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002783 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002784 grant_id
2785 } else {
2786 Self::insert_with_retry(|id| {
2787 tx.execute(
2788 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2789 VALUES (?, ?, ?, ?);",
2790 params![id, grantee_uid, key_id, i32::from(access_vector)],
2791 )
2792 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002793 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002794 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002795
Janis Danisevskis66784c42021-01-27 08:40:25 -08002796 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002797 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002798 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002799 }
2800
2801 /// This function checks permissions like `grant` and `load_key_entry`
2802 /// before removing a grant from the grant table.
2803 pub fn ungrant(
2804 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002805 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002806 caller_uid: u32,
2807 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002808 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002809 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002810 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2811
Janis Danisevskis66784c42021-01-27 08:40:25 -08002812 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2813 // Load the key_id and complete the access control tuple.
2814 // We ignore the access vector here because grants cannot be granted.
2815 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002816 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002817
Janis Danisevskis66784c42021-01-27 08:40:25 -08002818 // Perform access control. We must return here if the permission
2819 // was denied. So do not touch the '?' at the end of this line.
2820 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002821 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002822
Janis Danisevskis66784c42021-01-27 08:40:25 -08002823 tx.execute(
2824 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002825 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002826 params![key_id, grantee_uid],
2827 )
2828 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002829
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002830 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002831 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002832 }
2833
Joel Galenson845f74b2020-09-09 14:11:55 -07002834 // Generates a random id and passes it to the given function, which will
2835 // try to insert it into a database. If that insertion fails, retry;
2836 // otherwise return the id.
2837 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2838 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002839 let newid: i64 = match random() {
2840 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2841 i => i,
2842 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002843 match inserter(newid) {
2844 // If the id already existed, try again.
2845 Err(rusqlite::Error::SqliteFailure(
2846 libsqlite3_sys::Error {
2847 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2848 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2849 },
2850 _,
2851 )) => (),
2852 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002853 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002854 }
2855 _ => return Ok(newid),
2856 }
2857 }
2858 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002859
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002860 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2861 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002862 self.perboot
2863 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002864 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002865
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002866 /// Find the newest auth token matching the given predicate.
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002867 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, BootTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002868 where
2869 F: Fn(&AuthTokenEntry) -> bool,
2870 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002871 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002872 }
2873
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002874 /// Insert last_off_body into the metadata table at the initialization of auth token table
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002875 pub fn insert_last_off_body(&self, last_off_body: BootTime) {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002876 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002877 }
2878
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002879 /// Update last_off_body when on_device_off_body is called
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002880 pub fn update_last_off_body(&self, last_off_body: BootTime) {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002881 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002882 }
2883
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002884 /// Get last_off_body time when finding auth tokens
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002885 fn get_last_off_body(&self) -> BootTime {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002886 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002887 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002888
2889 /// Load descriptor of a key by key id
2890 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2891 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2892
2893 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2894 tx.query_row(
2895 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2896 params![key_id],
2897 |row| {
2898 Ok(KeyDescriptor {
2899 domain: Domain(row.get(0)?),
2900 nspace: row.get(1)?,
2901 alias: row.get(2)?,
2902 blob: None,
2903 })
2904 },
2905 )
2906 .optional()
2907 .context("Trying to load key descriptor")
2908 .no_gc()
2909 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002910 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002911 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002912
2913 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2914 /// (for the given user_id).
2915 /// This is helpful for finding out which apps will have their keys invalidated when
2916 /// the user changes biometrics enrollment or removes their LSKF.
2917 pub fn get_app_uids_affected_by_sid(
2918 &mut self,
2919 user_id: i32,
2920 secure_user_id: i64,
2921 ) -> Result<Vec<i64>> {
2922 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2923
2924 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2925 let mut stmt = tx
2926 .prepare(&format!(
2927 "SELECT id, namespace from persistent.keyentry
2928 WHERE key_type = ?
2929 AND domain = ?
2930 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2931 AND state = ?;",
2932 ))
2933 .context(concat!(
2934 "In get_app_uids_affected_by_sid, ",
2935 "failed to prepare the query to find the keys created by apps."
2936 ))?;
2937
2938 let mut rows = stmt
2939 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2940 .context(ks_err!("Failed to query the keys created by apps."))?;
2941
2942 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2943 db_utils::with_rows_extract_all(&mut rows, |row| {
2944 key_ids_and_app_uids.insert(
2945 row.get(0).context("Failed to read key id of a key created by an app.")?,
2946 row.get(1).context("Failed to read the app uid")?,
2947 );
2948 Ok(())
2949 })?;
2950 Ok(key_ids_and_app_uids).no_gc()
2951 })?;
2952 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2953 for (key_id, app_uid) in key_ids_and_app_uids {
2954 // Read the key parameters for each key in its own transaction. It is OK to ignore
2955 // an error to get the properties of a particular key since it might have been deleted
2956 // under our feet after the previous transaction concluded. If the key was deleted
2957 // then it is no longer applicable if it was auth-bound or not.
2958 if let Ok(is_key_bound_to_sid) =
2959 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2960 let params = Self::load_key_parameters(key_id, tx)
2961 .context("Failed to load key parameters.")?;
2962 // Check if the key is bound to this secure user ID.
2963 let is_key_bound_to_sid = params.iter().any(|kp| {
2964 matches!(
2965 kp.key_parameter_value(),
2966 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2967 )
2968 });
2969 Ok(is_key_bound_to_sid).no_gc()
2970 })
2971 {
2972 if is_key_bound_to_sid {
2973 app_uids_affected_by_sid.insert(app_uid);
2974 }
2975 }
2976 }
2977
2978 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2979 Ok(app_uids_vec)
2980 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002981}
2982
2983#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002984pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002985
2986 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002987 use crate::key_parameter::{
2988 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2989 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2990 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002991 use crate::key_perm_set;
2992 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002993 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002994 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002995 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2996 HardwareAuthToken::HardwareAuthToken,
2997 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002998 };
2999 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003000 Timestamp::Timestamp,
3001 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003002 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003003 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003004 use std::collections::BTreeMap;
3005 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003006 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04003007 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003008 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003009 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003010 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003011 #[cfg(disabled)]
3012 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003013
Seth Moore7ee79f92021-12-07 11:42:49 -08003014 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003015 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003016
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003017 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003018 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003019 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003020 })?;
3021 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003022 }
3023
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003024 fn rebind_alias(
3025 db: &mut KeystoreDB,
3026 newid: &KeyIdGuard,
3027 alias: &str,
3028 domain: Domain,
3029 namespace: i64,
3030 ) -> Result<bool> {
3031 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003032 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003033 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003034 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003035 }
3036
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003037 #[test]
3038 fn datetime() -> Result<()> {
3039 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003040 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003041 let now = SystemTime::now();
3042 let duration = Duration::from_secs(1000);
3043 let then = now.checked_sub(duration).unwrap();
3044 let soon = now.checked_add(duration).unwrap();
3045 conn.execute(
3046 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3047 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3048 )?;
3049 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003050 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003051 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3052 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3053 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3054 assert!(rows.next()?.is_none());
3055 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3056 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3057 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3058 Ok(())
3059 }
3060
Joel Galenson0891bc12020-07-20 10:37:03 -07003061 // Ensure that we're using the "injected" random function, not the real one.
3062 #[test]
3063 fn test_mocked_random() {
3064 let rand1 = random();
3065 let rand2 = random();
3066 let rand3 = random();
3067 if rand1 == rand2 {
3068 assert_eq!(rand2 + 1, rand3);
3069 } else {
3070 assert_eq!(rand1 + 1, rand2);
3071 assert_eq!(rand2, rand3);
3072 }
3073 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003074
Joel Galenson26f4d012020-07-17 14:57:21 -07003075 // Test that we have the correct tables.
3076 #[test]
3077 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003078 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003079 let tables = db
3080 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003081 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003082 .query_map(params![], |row| row.get(0))?
3083 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003084 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003085 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003086 assert_eq!(tables[1], "blobmetadata");
3087 assert_eq!(tables[2], "grant");
3088 assert_eq!(tables[3], "keyentry");
3089 assert_eq!(tables[4], "keymetadata");
3090 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003091 Ok(())
3092 }
3093
3094 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003095 fn test_auth_token_table_invariant() -> Result<()> {
3096 let mut db = new_test_db()?;
3097 let auth_token1 = HardwareAuthToken {
3098 challenge: i64::MAX,
3099 userId: 200,
3100 authenticatorId: 200,
3101 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3102 timestamp: Timestamp { milliSeconds: 500 },
3103 mac: String::from("mac").into_bytes(),
3104 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003105 db.insert_auth_token(&auth_token1);
3106 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003107 assert_eq!(auth_tokens_returned.len(), 1);
3108
3109 // insert another auth token with the same values for the columns in the UNIQUE constraint
3110 // of the auth token table and different value for timestamp
3111 let auth_token2 = HardwareAuthToken {
3112 challenge: i64::MAX,
3113 userId: 200,
3114 authenticatorId: 200,
3115 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3116 timestamp: Timestamp { milliSeconds: 600 },
3117 mac: String::from("mac").into_bytes(),
3118 };
3119
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003120 db.insert_auth_token(&auth_token2);
3121 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003122 assert_eq!(auth_tokens_returned.len(), 1);
3123
3124 if let Some(auth_token) = auth_tokens_returned.pop() {
3125 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3126 }
3127
3128 // insert another auth token with the different values for the columns in the UNIQUE
3129 // constraint of the auth token table
3130 let auth_token3 = HardwareAuthToken {
3131 challenge: i64::MAX,
3132 userId: 201,
3133 authenticatorId: 200,
3134 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3135 timestamp: Timestamp { milliSeconds: 600 },
3136 mac: String::from("mac").into_bytes(),
3137 };
3138
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003139 db.insert_auth_token(&auth_token3);
3140 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003141 assert_eq!(auth_tokens_returned.len(), 2);
3142
3143 Ok(())
3144 }
3145
3146 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003147 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3148 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003149 }
3150
3151 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003152 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003153 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003154 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003155
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003156 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003157 let entries = get_keyentry(&db)?;
3158 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003159
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003160 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003161
3162 let entries_new = get_keyentry(&db)?;
3163 assert_eq!(entries, entries_new);
3164 Ok(())
3165 }
3166
3167 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003168 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003169 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3170 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003171 }
3172
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003173 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003174
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003175 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3176 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003177
3178 let entries = get_keyentry(&db)?;
3179 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003180 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3181 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003182
3183 // Test that we must pass in a valid Domain.
3184 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003185 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003186 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003187 );
3188 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003189 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003190 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003191 );
3192 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003193 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003194 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003195 );
3196
3197 Ok(())
3198 }
3199
Joel Galenson33c04ad2020-08-03 11:04:38 -07003200 #[test]
3201 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003202 fn extractor(
3203 ke: &KeyEntryRow,
3204 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3205 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003206 }
3207
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003208 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003209 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3210 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003211 let entries = get_keyentry(&db)?;
3212 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003213 assert_eq!(
3214 extractor(&entries[0]),
3215 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3216 );
3217 assert_eq!(
3218 extractor(&entries[1]),
3219 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3220 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003221
3222 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003223 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003224 let entries = get_keyentry(&db)?;
3225 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003226 assert_eq!(
3227 extractor(&entries[0]),
3228 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3229 );
3230 assert_eq!(
3231 extractor(&entries[1]),
3232 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3233 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003234
3235 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003236 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003237 let entries = get_keyentry(&db)?;
3238 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003239 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3240 assert_eq!(
3241 extractor(&entries[1]),
3242 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3243 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003244
3245 // Test that we must pass in a valid Domain.
3246 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003247 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003248 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003249 );
3250 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003251 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003252 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003253 );
3254 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003255 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003256 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003257 );
3258
3259 // Test that we correctly handle setting an alias for something that does not exist.
3260 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003261 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003262 "Expected to update a single entry but instead updated 0",
3263 );
3264 // Test that we correctly abort the transaction in this case.
3265 let entries = get_keyentry(&db)?;
3266 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003267 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3268 assert_eq!(
3269 extractor(&entries[1]),
3270 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3271 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003272
3273 Ok(())
3274 }
3275
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003276 #[test]
3277 fn test_grant_ungrant() -> Result<()> {
3278 const CALLER_UID: u32 = 15;
3279 const GRANTEE_UID: u32 = 12;
3280 const SELINUX_NAMESPACE: i64 = 7;
3281
3282 let mut db = new_test_db()?;
3283 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003284 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3285 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3286 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003287 )?;
3288 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003289 domain: super::Domain::APP,
3290 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003291 alias: Some("key".to_string()),
3292 blob: None,
3293 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003294 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3295 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003296
3297 // Reset totally predictable random number generator in case we
3298 // are not the first test running on this thread.
3299 reset_random();
3300 let next_random = 0i64;
3301
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003302 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003303 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003304 assert_eq!(*a, PVEC1);
3305 assert_eq!(
3306 *k,
3307 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003308 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003309 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003310 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003311 alias: Some("key".to_string()),
3312 blob: None,
3313 }
3314 );
3315 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003316 })
3317 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003318
3319 assert_eq!(
3320 app_granted_key,
3321 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003322 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003323 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003324 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003325 alias: None,
3326 blob: None,
3327 }
3328 );
3329
3330 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003331 domain: super::Domain::SELINUX,
3332 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003333 alias: Some("yek".to_string()),
3334 blob: None,
3335 };
3336
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003337 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003338 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003339 assert_eq!(*a, PVEC1);
3340 assert_eq!(
3341 *k,
3342 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003343 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003344 // namespace must be the supplied SELinux
3345 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003346 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003347 alias: Some("yek".to_string()),
3348 blob: None,
3349 }
3350 );
3351 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003352 })
3353 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003354
3355 assert_eq!(
3356 selinux_granted_key,
3357 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003358 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003359 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003360 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003361 alias: None,
3362 blob: None,
3363 }
3364 );
3365
3366 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003367 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003368 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003369 assert_eq!(*a, PVEC2);
3370 assert_eq!(
3371 *k,
3372 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003373 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003374 // namespace must be the supplied SELinux
3375 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003376 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003377 alias: Some("yek".to_string()),
3378 blob: None,
3379 }
3380 );
3381 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003382 })
3383 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003384
3385 assert_eq!(
3386 selinux_granted_key,
3387 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003388 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003389 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003390 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003391 alias: None,
3392 blob: None,
3393 }
3394 );
3395
3396 {
3397 // Limiting scope of stmt, because it borrows db.
3398 let mut stmt = db
3399 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003400 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003401 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3402 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3403 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003404
3405 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003406 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003407 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003408 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003409 assert!(rows.next().is_none());
3410 }
3411
3412 debug_dump_keyentry_table(&mut db)?;
3413 println!("app_key {:?}", app_key);
3414 println!("selinux_key {:?}", selinux_key);
3415
Janis Danisevskis66784c42021-01-27 08:40:25 -08003416 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3417 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003418
3419 Ok(())
3420 }
3421
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003422 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003423 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3424 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3425
3426 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003427 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003428 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003429 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003430 let mut blob_metadata = BlobMetaData::new();
3431 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3432 db.set_blob(
3433 &key_id,
3434 SubComponentType::KEY_BLOB,
3435 Some(TEST_KEY_BLOB),
3436 Some(&blob_metadata),
3437 )?;
3438 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3439 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003440 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003441
3442 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003443 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003444 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003445 )?;
3446 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003447 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003448 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003449 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003450 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003451 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003452 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003453 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003454 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003455 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003456
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003457 drop(rows);
3458 drop(stmt);
3459
3460 assert_eq!(
3461 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3462 BlobMetaData::load_from_db(id, tx).no_gc()
3463 })
3464 .expect("Should find blob metadata."),
3465 blob_metadata
3466 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003467 Ok(())
3468 }
3469
3470 static TEST_ALIAS: &str = "my super duper key";
3471
3472 #[test]
3473 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3474 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003475 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003476 .context("test_insert_and_load_full_keyentry_domain_app")?
3477 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003478 let (_key_guard, key_entry) = db
3479 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003480 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003481 domain: Domain::APP,
3482 nspace: 0,
3483 alias: Some(TEST_ALIAS.to_string()),
3484 blob: None,
3485 },
3486 KeyType::Client,
3487 KeyEntryLoadBits::BOTH,
3488 1,
3489 |_k, _av| Ok(()),
3490 )
3491 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003492 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003493
3494 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003495 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003496 domain: Domain::APP,
3497 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003498 alias: Some(TEST_ALIAS.to_string()),
3499 blob: None,
3500 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003501 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003502 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003503 |_, _| Ok(()),
3504 )
3505 .unwrap();
3506
3507 assert_eq!(
3508 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3509 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003510 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003511 domain: Domain::APP,
3512 nspace: 0,
3513 alias: Some(TEST_ALIAS.to_string()),
3514 blob: None,
3515 },
3516 KeyType::Client,
3517 KeyEntryLoadBits::NONE,
3518 1,
3519 |_k, _av| Ok(()),
3520 )
3521 .unwrap_err()
3522 .root_cause()
3523 .downcast_ref::<KsError>()
3524 );
3525
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003526 Ok(())
3527 }
3528
3529 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003530 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3531 let mut db = new_test_db()?;
3532
3533 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003534 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003535 domain: Domain::APP,
3536 nspace: 1,
3537 alias: Some(TEST_ALIAS.to_string()),
3538 blob: None,
3539 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003540 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003541 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003542 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003543 )
3544 .expect("Trying to insert cert.");
3545
3546 let (_key_guard, mut key_entry) = db
3547 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003548 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003549 domain: Domain::APP,
3550 nspace: 1,
3551 alias: Some(TEST_ALIAS.to_string()),
3552 blob: None,
3553 },
3554 KeyType::Client,
3555 KeyEntryLoadBits::PUBLIC,
3556 1,
3557 |_k, _av| Ok(()),
3558 )
3559 .expect("Trying to read certificate entry.");
3560
3561 assert!(key_entry.pure_cert());
3562 assert!(key_entry.cert().is_none());
3563 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3564
3565 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003566 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003567 domain: Domain::APP,
3568 nspace: 1,
3569 alias: Some(TEST_ALIAS.to_string()),
3570 blob: None,
3571 },
3572 KeyType::Client,
3573 1,
3574 |_, _| Ok(()),
3575 )
3576 .unwrap();
3577
3578 assert_eq!(
3579 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3580 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003581 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003582 domain: Domain::APP,
3583 nspace: 1,
3584 alias: Some(TEST_ALIAS.to_string()),
3585 blob: None,
3586 },
3587 KeyType::Client,
3588 KeyEntryLoadBits::NONE,
3589 1,
3590 |_k, _av| Ok(()),
3591 )
3592 .unwrap_err()
3593 .root_cause()
3594 .downcast_ref::<KsError>()
3595 );
3596
3597 Ok(())
3598 }
3599
3600 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003601 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3602 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003603 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003604 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3605 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003606 let (_key_guard, key_entry) = db
3607 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003608 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003609 domain: Domain::SELINUX,
3610 nspace: 1,
3611 alias: Some(TEST_ALIAS.to_string()),
3612 blob: None,
3613 },
3614 KeyType::Client,
3615 KeyEntryLoadBits::BOTH,
3616 1,
3617 |_k, _av| Ok(()),
3618 )
3619 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003620 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003621
3622 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003623 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003624 domain: Domain::SELINUX,
3625 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003626 alias: Some(TEST_ALIAS.to_string()),
3627 blob: None,
3628 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003629 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003630 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003631 |_, _| Ok(()),
3632 )
3633 .unwrap();
3634
3635 assert_eq!(
3636 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3637 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003638 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003639 domain: Domain::SELINUX,
3640 nspace: 1,
3641 alias: Some(TEST_ALIAS.to_string()),
3642 blob: None,
3643 },
3644 KeyType::Client,
3645 KeyEntryLoadBits::NONE,
3646 1,
3647 |_k, _av| Ok(()),
3648 )
3649 .unwrap_err()
3650 .root_cause()
3651 .downcast_ref::<KsError>()
3652 );
3653
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003654 Ok(())
3655 }
3656
3657 #[test]
3658 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3659 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003660 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003661 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3662 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003663 let (_, key_entry) = db
3664 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003665 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003666 KeyType::Client,
3667 KeyEntryLoadBits::BOTH,
3668 1,
3669 |_k, _av| Ok(()),
3670 )
3671 .unwrap();
3672
Qi Wub9433b52020-12-01 14:52:46 +08003673 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003674
3675 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003676 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003677 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003678 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003679 |_, _| Ok(()),
3680 )
3681 .unwrap();
3682
3683 assert_eq!(
3684 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3685 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003686 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003687 KeyType::Client,
3688 KeyEntryLoadBits::NONE,
3689 1,
3690 |_k, _av| Ok(()),
3691 )
3692 .unwrap_err()
3693 .root_cause()
3694 .downcast_ref::<KsError>()
3695 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003696
3697 Ok(())
3698 }
3699
3700 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003701 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3702 let mut db = new_test_db()?;
3703 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3704 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3705 .0;
3706 // Update the usage count of the limited use key.
3707 db.check_and_update_key_usage_count(key_id)?;
3708
3709 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003710 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003711 KeyType::Client,
3712 KeyEntryLoadBits::BOTH,
3713 1,
3714 |_k, _av| Ok(()),
3715 )?;
3716
3717 // The usage count is decremented now.
3718 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3719
3720 Ok(())
3721 }
3722
3723 #[test]
3724 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3725 let mut db = new_test_db()?;
3726 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3727 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3728 .0;
3729 // Update the usage count of the limited use key.
3730 db.check_and_update_key_usage_count(key_id).expect(concat!(
3731 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3732 "This should succeed."
3733 ));
3734
3735 // Try to update the exhausted limited use key.
3736 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3737 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3738 "This should fail."
3739 ));
3740 assert_eq!(
3741 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3742 e.root_cause().downcast_ref::<KsError>().unwrap()
3743 );
3744
3745 Ok(())
3746 }
3747
3748 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003749 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3750 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003751 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003752 .context("test_insert_and_load_full_keyentry_from_grant")?
3753 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003755 let granted_key = db
3756 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003757 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003758 domain: Domain::APP,
3759 nspace: 0,
3760 alias: Some(TEST_ALIAS.to_string()),
3761 blob: None,
3762 },
3763 1,
3764 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003765 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766 |_k, _av| Ok(()),
3767 )
3768 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003769
3770 debug_dump_grant_table(&mut db)?;
3771
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003772 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003773 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3774 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003775 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003776 Ok(())
3777 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003778 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003779
Qi Wub9433b52020-12-01 14:52:46 +08003780 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003781
Janis Danisevskis66784c42021-01-27 08:40:25 -08003782 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003783
3784 assert_eq!(
3785 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3786 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003787 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003788 KeyType::Client,
3789 KeyEntryLoadBits::NONE,
3790 2,
3791 |_k, _av| Ok(()),
3792 )
3793 .unwrap_err()
3794 .root_cause()
3795 .downcast_ref::<KsError>()
3796 );
3797
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003798 Ok(())
3799 }
3800
Janis Danisevskis45760022021-01-19 16:34:10 -08003801 // This test attempts to load a key by key id while the caller is not the owner
3802 // but a grant exists for the given key and the caller.
3803 #[test]
3804 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3805 let mut db = new_test_db()?;
3806 const OWNER_UID: u32 = 1u32;
3807 const GRANTEE_UID: u32 = 2u32;
3808 const SOMEONE_ELSE_UID: u32 = 3u32;
3809 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3810 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3811 .0;
3812
3813 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003814 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003815 domain: Domain::APP,
3816 nspace: 0,
3817 alias: Some(TEST_ALIAS.to_string()),
3818 blob: None,
3819 },
3820 OWNER_UID,
3821 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003822 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003823 |_k, _av| Ok(()),
3824 )
3825 .unwrap();
3826
3827 debug_dump_grant_table(&mut db)?;
3828
3829 let id_descriptor =
3830 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3831
3832 let (_, key_entry) = db
3833 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003834 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003835 KeyType::Client,
3836 KeyEntryLoadBits::BOTH,
3837 GRANTEE_UID,
3838 |k, av| {
3839 assert_eq!(Domain::APP, k.domain);
3840 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003841 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003842 Ok(())
3843 },
3844 )
3845 .unwrap();
3846
3847 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3848
3849 let (_, key_entry) = db
3850 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003851 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003852 KeyType::Client,
3853 KeyEntryLoadBits::BOTH,
3854 SOMEONE_ELSE_UID,
3855 |k, av| {
3856 assert_eq!(Domain::APP, k.domain);
3857 assert_eq!(OWNER_UID as i64, k.nspace);
3858 assert!(av.is_none());
3859 Ok(())
3860 },
3861 )
3862 .unwrap();
3863
3864 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3865
Janis Danisevskis66784c42021-01-27 08:40:25 -08003866 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003867
3868 assert_eq!(
3869 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3870 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003871 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003872 KeyType::Client,
3873 KeyEntryLoadBits::NONE,
3874 GRANTEE_UID,
3875 |_k, _av| Ok(()),
3876 )
3877 .unwrap_err()
3878 .root_cause()
3879 .downcast_ref::<KsError>()
3880 );
3881
3882 Ok(())
3883 }
3884
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003885 // Creates a key migrates it to a different location and then tries to access it by the old
3886 // and new location.
3887 #[test]
3888 fn test_migrate_key_app_to_app() -> Result<()> {
3889 let mut db = new_test_db()?;
3890 const SOURCE_UID: u32 = 1u32;
3891 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003892 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3893 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003894 let key_id_guard =
3895 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3896 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3897
3898 let source_descriptor: KeyDescriptor = KeyDescriptor {
3899 domain: Domain::APP,
3900 nspace: -1,
3901 alias: Some(SOURCE_ALIAS.to_string()),
3902 blob: None,
3903 };
3904
3905 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3906 domain: Domain::APP,
3907 nspace: -1,
3908 alias: Some(DESTINATION_ALIAS.to_string()),
3909 blob: None,
3910 };
3911
3912 let key_id = key_id_guard.id();
3913
3914 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3915 Ok(())
3916 })
3917 .unwrap();
3918
3919 let (_, key_entry) = db
3920 .load_key_entry(
3921 &destination_descriptor,
3922 KeyType::Client,
3923 KeyEntryLoadBits::BOTH,
3924 DESTINATION_UID,
3925 |k, av| {
3926 assert_eq!(Domain::APP, k.domain);
3927 assert_eq!(DESTINATION_UID as i64, k.nspace);
3928 assert!(av.is_none());
3929 Ok(())
3930 },
3931 )
3932 .unwrap();
3933
3934 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3935
3936 assert_eq!(
3937 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3938 db.load_key_entry(
3939 &source_descriptor,
3940 KeyType::Client,
3941 KeyEntryLoadBits::NONE,
3942 SOURCE_UID,
3943 |_k, _av| Ok(()),
3944 )
3945 .unwrap_err()
3946 .root_cause()
3947 .downcast_ref::<KsError>()
3948 );
3949
3950 Ok(())
3951 }
3952
3953 // Creates a key migrates it to a different location and then tries to access it by the old
3954 // and new location.
3955 #[test]
3956 fn test_migrate_key_app_to_selinux() -> Result<()> {
3957 let mut db = new_test_db()?;
3958 const SOURCE_UID: u32 = 1u32;
3959 const DESTINATION_UID: u32 = 2u32;
3960 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003961 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3962 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003963 let key_id_guard =
3964 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3965 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3966
3967 let source_descriptor: KeyDescriptor = KeyDescriptor {
3968 domain: Domain::APP,
3969 nspace: -1,
3970 alias: Some(SOURCE_ALIAS.to_string()),
3971 blob: None,
3972 };
3973
3974 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3975 domain: Domain::SELINUX,
3976 nspace: DESTINATION_NAMESPACE,
3977 alias: Some(DESTINATION_ALIAS.to_string()),
3978 blob: None,
3979 };
3980
3981 let key_id = key_id_guard.id();
3982
3983 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3984 Ok(())
3985 })
3986 .unwrap();
3987
3988 let (_, key_entry) = db
3989 .load_key_entry(
3990 &destination_descriptor,
3991 KeyType::Client,
3992 KeyEntryLoadBits::BOTH,
3993 DESTINATION_UID,
3994 |k, av| {
3995 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003996 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003997 assert!(av.is_none());
3998 Ok(())
3999 },
4000 )
4001 .unwrap();
4002
4003 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4004
4005 assert_eq!(
4006 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4007 db.load_key_entry(
4008 &source_descriptor,
4009 KeyType::Client,
4010 KeyEntryLoadBits::NONE,
4011 SOURCE_UID,
4012 |_k, _av| Ok(()),
4013 )
4014 .unwrap_err()
4015 .root_cause()
4016 .downcast_ref::<KsError>()
4017 );
4018
4019 Ok(())
4020 }
4021
4022 // Creates two keys and tries to migrate the first to the location of the second which
4023 // is expected to fail.
4024 #[test]
4025 fn test_migrate_key_destination_occupied() -> Result<()> {
4026 let mut db = new_test_db()?;
4027 const SOURCE_UID: u32 = 1u32;
4028 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004029 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4030 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004031 let key_id_guard =
4032 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4033 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4034 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4035 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4036
4037 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4038 domain: Domain::APP,
4039 nspace: -1,
4040 alias: Some(DESTINATION_ALIAS.to_string()),
4041 blob: None,
4042 };
4043
4044 assert_eq!(
4045 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4046 db.migrate_key_namespace(
4047 key_id_guard,
4048 &destination_descriptor,
4049 DESTINATION_UID,
4050 |_k| Ok(())
4051 )
4052 .unwrap_err()
4053 .root_cause()
4054 .downcast_ref::<KsError>()
4055 );
4056
4057 Ok(())
4058 }
4059
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004060 #[test]
4061 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004062 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4063 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4064 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004065 const UID: u32 = 33;
4066 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4067 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4068 let key_id_untouched1 =
4069 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4070 let key_id_untouched2 =
4071 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4072 let key_id_deleted =
4073 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4074
4075 let (_, key_entry) = db
4076 .load_key_entry(
4077 &KeyDescriptor {
4078 domain: Domain::APP,
4079 nspace: -1,
4080 alias: Some(ALIAS1.to_string()),
4081 blob: None,
4082 },
4083 KeyType::Client,
4084 KeyEntryLoadBits::BOTH,
4085 UID,
4086 |k, av| {
4087 assert_eq!(Domain::APP, k.domain);
4088 assert_eq!(UID as i64, k.nspace);
4089 assert!(av.is_none());
4090 Ok(())
4091 },
4092 )
4093 .unwrap();
4094 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4095 let (_, key_entry) = db
4096 .load_key_entry(
4097 &KeyDescriptor {
4098 domain: Domain::APP,
4099 nspace: -1,
4100 alias: Some(ALIAS2.to_string()),
4101 blob: None,
4102 },
4103 KeyType::Client,
4104 KeyEntryLoadBits::BOTH,
4105 UID,
4106 |k, av| {
4107 assert_eq!(Domain::APP, k.domain);
4108 assert_eq!(UID as i64, k.nspace);
4109 assert!(av.is_none());
4110 Ok(())
4111 },
4112 )
4113 .unwrap();
4114 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4115 let (_, key_entry) = db
4116 .load_key_entry(
4117 &KeyDescriptor {
4118 domain: Domain::APP,
4119 nspace: -1,
4120 alias: Some(ALIAS3.to_string()),
4121 blob: None,
4122 },
4123 KeyType::Client,
4124 KeyEntryLoadBits::BOTH,
4125 UID,
4126 |k, av| {
4127 assert_eq!(Domain::APP, k.domain);
4128 assert_eq!(UID as i64, k.nspace);
4129 assert!(av.is_none());
4130 Ok(())
4131 },
4132 )
4133 .unwrap();
4134 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4135
4136 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4137 KeystoreDB::from_0_to_1(tx).no_gc()
4138 })
4139 .unwrap();
4140
4141 let (_, key_entry) = db
4142 .load_key_entry(
4143 &KeyDescriptor {
4144 domain: Domain::APP,
4145 nspace: -1,
4146 alias: Some(ALIAS1.to_string()),
4147 blob: None,
4148 },
4149 KeyType::Client,
4150 KeyEntryLoadBits::BOTH,
4151 UID,
4152 |k, av| {
4153 assert_eq!(Domain::APP, k.domain);
4154 assert_eq!(UID as i64, k.nspace);
4155 assert!(av.is_none());
4156 Ok(())
4157 },
4158 )
4159 .unwrap();
4160 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4161 let (_, key_entry) = db
4162 .load_key_entry(
4163 &KeyDescriptor {
4164 domain: Domain::APP,
4165 nspace: -1,
4166 alias: Some(ALIAS2.to_string()),
4167 blob: None,
4168 },
4169 KeyType::Client,
4170 KeyEntryLoadBits::BOTH,
4171 UID,
4172 |k, av| {
4173 assert_eq!(Domain::APP, k.domain);
4174 assert_eq!(UID as i64, k.nspace);
4175 assert!(av.is_none());
4176 Ok(())
4177 },
4178 )
4179 .unwrap();
4180 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4181 assert_eq!(
4182 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4183 db.load_key_entry(
4184 &KeyDescriptor {
4185 domain: Domain::APP,
4186 nspace: -1,
4187 alias: Some(ALIAS3.to_string()),
4188 blob: None,
4189 },
4190 KeyType::Client,
4191 KeyEntryLoadBits::BOTH,
4192 UID,
4193 |k, av| {
4194 assert_eq!(Domain::APP, k.domain);
4195 assert_eq!(UID as i64, k.nspace);
4196 assert!(av.is_none());
4197 Ok(())
4198 },
4199 )
4200 .unwrap_err()
4201 .root_cause()
4202 .downcast_ref::<KsError>()
4203 );
4204 }
4205
Janis Danisevskisaec14592020-11-12 09:41:49 -08004206 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4207
Janis Danisevskisaec14592020-11-12 09:41:49 -08004208 #[test]
4209 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4210 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004211 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4212 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004213 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004214 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004215 .context("test_insert_and_load_full_keyentry_domain_app")?
4216 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004217 let (_key_guard, key_entry) = db
4218 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004219 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004220 domain: Domain::APP,
4221 nspace: 0,
4222 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4223 blob: None,
4224 },
4225 KeyType::Client,
4226 KeyEntryLoadBits::BOTH,
4227 33,
4228 |_k, _av| Ok(()),
4229 )
4230 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004231 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004232 let state = Arc::new(AtomicU8::new(1));
4233 let state2 = state.clone();
4234
4235 // Spawning a second thread that attempts to acquire the key id lock
4236 // for the same key as the primary thread. The primary thread then
4237 // waits, thereby forcing the secondary thread into the second stage
4238 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4239 // The test succeeds if the secondary thread observes the transition
4240 // of `state` from 1 to 2, despite having a whole second to overtake
4241 // the primary thread.
4242 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004243 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004244 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004245 assert!(db
4246 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004247 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004248 domain: Domain::APP,
4249 nspace: 0,
4250 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4251 blob: None,
4252 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004253 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004254 KeyEntryLoadBits::BOTH,
4255 33,
4256 |_k, _av| Ok(()),
4257 )
4258 .is_ok());
4259 // We should only see a 2 here because we can only return
4260 // from load_key_entry when the `_key_guard` expires,
4261 // which happens at the end of the scope.
4262 assert_eq!(2, state2.load(Ordering::Relaxed));
4263 });
4264
4265 thread::sleep(std::time::Duration::from_millis(1000));
4266
4267 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4268
4269 // Return the handle from this scope so we can join with the
4270 // secondary thread after the key id lock has expired.
4271 handle
4272 // This is where the `_key_guard` goes out of scope,
4273 // which is the reason for concurrent load_key_entry on the same key
4274 // to unblock.
4275 };
4276 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4277 // main test thread. We will not see failing asserts in secondary threads otherwise.
4278 handle.join().unwrap();
4279 Ok(())
4280 }
4281
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004282 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004283 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004284 let temp_dir =
4285 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4286
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004287 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4288 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004289
4290 let _tx1 = db1
4291 .conn
4292 .transaction_with_behavior(TransactionBehavior::Immediate)
4293 .expect("Failed to create first transaction.");
4294
4295 let error = db2
4296 .conn
4297 .transaction_with_behavior(TransactionBehavior::Immediate)
4298 .context("Transaction begin failed.")
4299 .expect_err("This should fail.");
4300 let root_cause = error.root_cause();
4301 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4302 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4303 {
4304 return;
4305 }
4306 panic!(
4307 "Unexpected error {:?} \n{:?} \n{:?}",
4308 error,
4309 root_cause,
4310 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4311 )
4312 }
4313
4314 #[cfg(disabled)]
4315 #[test]
4316 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4317 let temp_dir = Arc::new(
4318 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4319 .expect("Failed to create temp dir."),
4320 );
4321
4322 let test_begin = Instant::now();
4323
Janis Danisevskis66784c42021-01-27 08:40:25 -08004324 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004325 let mut db =
4326 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004327 const OPEN_DB_COUNT: u32 = 50u32;
4328
4329 let mut actual_key_count = KEY_COUNT;
4330 // First insert KEY_COUNT keys.
4331 for count in 0..KEY_COUNT {
4332 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4333 actual_key_count = count;
4334 break;
4335 }
4336 let alias = format!("test_alias_{}", count);
4337 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4338 .expect("Failed to make key entry.");
4339 }
4340
4341 // Insert more keys from a different thread and into a different namespace.
4342 let temp_dir1 = temp_dir.clone();
4343 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004344 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4345 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004346
4347 for count in 0..actual_key_count {
4348 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4349 return;
4350 }
4351 let alias = format!("test_alias_{}", count);
4352 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4353 .expect("Failed to make key entry.");
4354 }
4355
4356 // then unbind them again.
4357 for count in 0..actual_key_count {
4358 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4359 return;
4360 }
4361 let key = KeyDescriptor {
4362 domain: Domain::APP,
4363 nspace: -1,
4364 alias: Some(format!("test_alias_{}", count)),
4365 blob: None,
4366 };
4367 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4368 }
4369 });
4370
4371 // And start unbinding the first set of keys.
4372 let temp_dir2 = temp_dir.clone();
4373 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004374 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4375 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004376
4377 for count in 0..actual_key_count {
4378 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4379 return;
4380 }
4381 let key = KeyDescriptor {
4382 domain: Domain::APP,
4383 nspace: -1,
4384 alias: Some(format!("test_alias_{}", count)),
4385 blob: None,
4386 };
4387 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4388 }
4389 });
4390
Janis Danisevskis66784c42021-01-27 08:40:25 -08004391 // While a lot of inserting and deleting is going on we have to open database connections
4392 // successfully and use them.
4393 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4394 // out of scope.
4395 #[allow(clippy::redundant_clone)]
4396 let temp_dir4 = temp_dir.clone();
4397 let handle4 = thread::spawn(move || {
4398 for count in 0..OPEN_DB_COUNT {
4399 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4400 return;
4401 }
Seth Moore444b51a2021-06-11 09:49:49 -07004402 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4403 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004404
4405 let alias = format!("test_alias_{}", count);
4406 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4407 .expect("Failed to make key entry.");
4408 let key = KeyDescriptor {
4409 domain: Domain::APP,
4410 nspace: -1,
4411 alias: Some(alias),
4412 blob: None,
4413 };
4414 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4415 }
4416 });
4417
4418 handle1.join().expect("Thread 1 panicked.");
4419 handle2.join().expect("Thread 2 panicked.");
4420 handle4.join().expect("Thread 4 panicked.");
4421
Janis Danisevskis66784c42021-01-27 08:40:25 -08004422 Ok(())
4423 }
4424
4425 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004426 fn list() -> Result<()> {
4427 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004428 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004429 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4430 (Domain::APP, 1, "test1"),
4431 (Domain::APP, 1, "test2"),
4432 (Domain::APP, 1, "test3"),
4433 (Domain::APP, 1, "test4"),
4434 (Domain::APP, 1, "test5"),
4435 (Domain::APP, 1, "test6"),
4436 (Domain::APP, 1, "test7"),
4437 (Domain::APP, 2, "test1"),
4438 (Domain::APP, 2, "test2"),
4439 (Domain::APP, 2, "test3"),
4440 (Domain::APP, 2, "test4"),
4441 (Domain::APP, 2, "test5"),
4442 (Domain::APP, 2, "test6"),
4443 (Domain::APP, 2, "test8"),
4444 (Domain::SELINUX, 100, "test1"),
4445 (Domain::SELINUX, 100, "test2"),
4446 (Domain::SELINUX, 100, "test3"),
4447 (Domain::SELINUX, 100, "test4"),
4448 (Domain::SELINUX, 100, "test5"),
4449 (Domain::SELINUX, 100, "test6"),
4450 (Domain::SELINUX, 100, "test9"),
4451 ];
4452
4453 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4454 .iter()
4455 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004456 let entry =
4457 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004458 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4459 });
4460 (entry.id(), *ns)
4461 })
4462 .collect();
4463
4464 for (domain, namespace) in
4465 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4466 {
4467 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4468 .iter()
4469 .filter_map(|(domain, ns, alias)| match ns {
4470 ns if *ns == *namespace => Some(KeyDescriptor {
4471 domain: *domain,
4472 nspace: *ns,
4473 alias: Some(alias.to_string()),
4474 blob: None,
4475 }),
4476 _ => None,
4477 })
4478 .collect();
4479 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004480 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004481 list_result.sort();
4482 assert_eq!(list_o_descriptors, list_result);
4483
4484 let mut list_o_ids: Vec<i64> = list_o_descriptors
4485 .into_iter()
4486 .map(|d| {
4487 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004488 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004489 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004490 KeyType::Client,
4491 KeyEntryLoadBits::NONE,
4492 *namespace as u32,
4493 |_, _| Ok(()),
4494 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004495 .unwrap();
4496 entry.id()
4497 })
4498 .collect();
4499 list_o_ids.sort_unstable();
4500 let mut loaded_entries: Vec<i64> = list_o_keys
4501 .iter()
4502 .filter_map(|(id, ns)| match ns {
4503 ns if *ns == *namespace => Some(*id),
4504 _ => None,
4505 })
4506 .collect();
4507 loaded_entries.sort_unstable();
4508 assert_eq!(list_o_ids, loaded_entries);
4509 }
Eran Messeri24f31972023-01-25 17:00:33 +00004510 assert_eq!(
4511 Vec::<KeyDescriptor>::new(),
4512 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4513 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004514
4515 Ok(())
4516 }
4517
Joel Galenson0891bc12020-07-20 10:37:03 -07004518 // Helpers
4519
4520 // Checks that the given result is an error containing the given string.
4521 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4522 let error_str = format!(
4523 "{:#?}",
4524 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4525 );
4526 assert!(
4527 error_str.contains(target),
4528 "The string \"{}\" should contain \"{}\"",
4529 error_str,
4530 target
4531 );
4532 }
4533
Joel Galenson2aab4432020-07-22 15:27:57 -07004534 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004535 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004536 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004537 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004538 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004539 namespace: Option<i64>,
4540 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004541 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004542 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004543 }
4544
4545 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4546 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004547 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004548 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004549 Ok(KeyEntryRow {
4550 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004551 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004552 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004553 namespace: row.get(3)?,
4554 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004555 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004556 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004557 })
4558 })?
4559 .map(|r| r.context("Could not read keyentry row."))
4560 .collect::<Result<Vec<_>>>()
4561 }
4562
Eran Messeri4dc27b52024-01-09 12:43:31 +00004563 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4564 make_test_params_with_sids(max_usage_count, &[42])
4565 }
4566
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004567 // Note: The parameters and SecurityLevel associations are nonsensical. This
4568 // collection is only used to check if the parameters are preserved as expected by the
4569 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004570 fn make_test_params_with_sids(
4571 max_usage_count: Option<i32>,
4572 user_secure_ids: &[i64],
4573 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004574 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004575 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4576 KeyParameter::new(
4577 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4578 SecurityLevel::TRUSTED_ENVIRONMENT,
4579 ),
4580 KeyParameter::new(
4581 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4582 SecurityLevel::TRUSTED_ENVIRONMENT,
4583 ),
4584 KeyParameter::new(
4585 KeyParameterValue::Algorithm(Algorithm::RSA),
4586 SecurityLevel::TRUSTED_ENVIRONMENT,
4587 ),
4588 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4589 KeyParameter::new(
4590 KeyParameterValue::BlockMode(BlockMode::ECB),
4591 SecurityLevel::TRUSTED_ENVIRONMENT,
4592 ),
4593 KeyParameter::new(
4594 KeyParameterValue::BlockMode(BlockMode::GCM),
4595 SecurityLevel::TRUSTED_ENVIRONMENT,
4596 ),
4597 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4598 KeyParameter::new(
4599 KeyParameterValue::Digest(Digest::MD5),
4600 SecurityLevel::TRUSTED_ENVIRONMENT,
4601 ),
4602 KeyParameter::new(
4603 KeyParameterValue::Digest(Digest::SHA_2_224),
4604 SecurityLevel::TRUSTED_ENVIRONMENT,
4605 ),
4606 KeyParameter::new(
4607 KeyParameterValue::Digest(Digest::SHA_2_256),
4608 SecurityLevel::STRONGBOX,
4609 ),
4610 KeyParameter::new(
4611 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4612 SecurityLevel::TRUSTED_ENVIRONMENT,
4613 ),
4614 KeyParameter::new(
4615 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4616 SecurityLevel::TRUSTED_ENVIRONMENT,
4617 ),
4618 KeyParameter::new(
4619 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4620 SecurityLevel::STRONGBOX,
4621 ),
4622 KeyParameter::new(
4623 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4624 SecurityLevel::TRUSTED_ENVIRONMENT,
4625 ),
4626 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4627 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4628 KeyParameter::new(
4629 KeyParameterValue::EcCurve(EcCurve::P_224),
4630 SecurityLevel::TRUSTED_ENVIRONMENT,
4631 ),
4632 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4633 KeyParameter::new(
4634 KeyParameterValue::EcCurve(EcCurve::P_384),
4635 SecurityLevel::TRUSTED_ENVIRONMENT,
4636 ),
4637 KeyParameter::new(
4638 KeyParameterValue::EcCurve(EcCurve::P_521),
4639 SecurityLevel::TRUSTED_ENVIRONMENT,
4640 ),
4641 KeyParameter::new(
4642 KeyParameterValue::RSAPublicExponent(3),
4643 SecurityLevel::TRUSTED_ENVIRONMENT,
4644 ),
4645 KeyParameter::new(
4646 KeyParameterValue::IncludeUniqueID,
4647 SecurityLevel::TRUSTED_ENVIRONMENT,
4648 ),
4649 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4650 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4651 KeyParameter::new(
4652 KeyParameterValue::ActiveDateTime(1234567890),
4653 SecurityLevel::STRONGBOX,
4654 ),
4655 KeyParameter::new(
4656 KeyParameterValue::OriginationExpireDateTime(1234567890),
4657 SecurityLevel::TRUSTED_ENVIRONMENT,
4658 ),
4659 KeyParameter::new(
4660 KeyParameterValue::UsageExpireDateTime(1234567890),
4661 SecurityLevel::TRUSTED_ENVIRONMENT,
4662 ),
4663 KeyParameter::new(
4664 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4665 SecurityLevel::TRUSTED_ENVIRONMENT,
4666 ),
4667 KeyParameter::new(
4668 KeyParameterValue::MaxUsesPerBoot(1234567890),
4669 SecurityLevel::TRUSTED_ENVIRONMENT,
4670 ),
4671 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004672 KeyParameter::new(
4673 KeyParameterValue::NoAuthRequired,
4674 SecurityLevel::TRUSTED_ENVIRONMENT,
4675 ),
4676 KeyParameter::new(
4677 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4678 SecurityLevel::TRUSTED_ENVIRONMENT,
4679 ),
4680 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4681 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4682 KeyParameter::new(
4683 KeyParameterValue::TrustedUserPresenceRequired,
4684 SecurityLevel::TRUSTED_ENVIRONMENT,
4685 ),
4686 KeyParameter::new(
4687 KeyParameterValue::TrustedConfirmationRequired,
4688 SecurityLevel::TRUSTED_ENVIRONMENT,
4689 ),
4690 KeyParameter::new(
4691 KeyParameterValue::UnlockedDeviceRequired,
4692 SecurityLevel::TRUSTED_ENVIRONMENT,
4693 ),
4694 KeyParameter::new(
4695 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4696 SecurityLevel::SOFTWARE,
4697 ),
4698 KeyParameter::new(
4699 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4700 SecurityLevel::SOFTWARE,
4701 ),
4702 KeyParameter::new(
4703 KeyParameterValue::CreationDateTime(12345677890),
4704 SecurityLevel::SOFTWARE,
4705 ),
4706 KeyParameter::new(
4707 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4708 SecurityLevel::TRUSTED_ENVIRONMENT,
4709 ),
4710 KeyParameter::new(
4711 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4712 SecurityLevel::TRUSTED_ENVIRONMENT,
4713 ),
4714 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4715 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4716 KeyParameter::new(
4717 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4718 SecurityLevel::SOFTWARE,
4719 ),
4720 KeyParameter::new(
4721 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4722 SecurityLevel::TRUSTED_ENVIRONMENT,
4723 ),
4724 KeyParameter::new(
4725 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4726 SecurityLevel::TRUSTED_ENVIRONMENT,
4727 ),
4728 KeyParameter::new(
4729 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4730 SecurityLevel::TRUSTED_ENVIRONMENT,
4731 ),
4732 KeyParameter::new(
4733 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4734 SecurityLevel::TRUSTED_ENVIRONMENT,
4735 ),
4736 KeyParameter::new(
4737 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4738 SecurityLevel::TRUSTED_ENVIRONMENT,
4739 ),
4740 KeyParameter::new(
4741 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4742 SecurityLevel::TRUSTED_ENVIRONMENT,
4743 ),
4744 KeyParameter::new(
4745 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4746 SecurityLevel::TRUSTED_ENVIRONMENT,
4747 ),
4748 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004749 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4750 SecurityLevel::TRUSTED_ENVIRONMENT,
4751 ),
4752 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004753 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4754 SecurityLevel::TRUSTED_ENVIRONMENT,
4755 ),
4756 KeyParameter::new(
4757 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4758 SecurityLevel::TRUSTED_ENVIRONMENT,
4759 ),
4760 KeyParameter::new(
4761 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4762 SecurityLevel::TRUSTED_ENVIRONMENT,
4763 ),
4764 KeyParameter::new(
4765 KeyParameterValue::VendorPatchLevel(3),
4766 SecurityLevel::TRUSTED_ENVIRONMENT,
4767 ),
4768 KeyParameter::new(
4769 KeyParameterValue::BootPatchLevel(4),
4770 SecurityLevel::TRUSTED_ENVIRONMENT,
4771 ),
4772 KeyParameter::new(
4773 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4774 SecurityLevel::TRUSTED_ENVIRONMENT,
4775 ),
4776 KeyParameter::new(
4777 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4778 SecurityLevel::TRUSTED_ENVIRONMENT,
4779 ),
4780 KeyParameter::new(
4781 KeyParameterValue::MacLength(256),
4782 SecurityLevel::TRUSTED_ENVIRONMENT,
4783 ),
4784 KeyParameter::new(
4785 KeyParameterValue::ResetSinceIdRotation,
4786 SecurityLevel::TRUSTED_ENVIRONMENT,
4787 ),
4788 KeyParameter::new(
4789 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4790 SecurityLevel::TRUSTED_ENVIRONMENT,
4791 ),
Qi Wub9433b52020-12-01 14:52:46 +08004792 ];
4793 if let Some(value) = max_usage_count {
4794 params.push(KeyParameter::new(
4795 KeyParameterValue::UsageCountLimit(value),
4796 SecurityLevel::SOFTWARE,
4797 ));
4798 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004799
4800 for sid in user_secure_ids.iter() {
4801 params.push(KeyParameter::new(
4802 KeyParameterValue::UserSecureID(*sid),
4803 SecurityLevel::STRONGBOX,
4804 ));
4805 }
Qi Wub9433b52020-12-01 14:52:46 +08004806 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004807 }
4808
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004809 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004810 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004811 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004812 namespace: i64,
4813 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004814 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004815 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004816 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4817 }
4818
4819 pub fn make_test_key_entry_with_sids(
4820 db: &mut KeystoreDB,
4821 domain: Domain,
4822 namespace: i64,
4823 alias: &str,
4824 max_usage_count: Option<i32>,
4825 sids: &[i64],
4826 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004827 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004828 let mut blob_metadata = BlobMetaData::new();
4829 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4830 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4831 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4832 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4833 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4834
4835 db.set_blob(
4836 &key_id,
4837 SubComponentType::KEY_BLOB,
4838 Some(TEST_KEY_BLOB),
4839 Some(&blob_metadata),
4840 )?;
4841 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4842 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004843
Eran Messeri4dc27b52024-01-09 12:43:31 +00004844 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004845 db.insert_keyparameter(&key_id, &params)?;
4846
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004847 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004848 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004849 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004850 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004851 Ok(key_id)
4852 }
4853
Qi Wub9433b52020-12-01 14:52:46 +08004854 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4855 let params = make_test_params(max_usage_count);
4856
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004857 let mut blob_metadata = BlobMetaData::new();
4858 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4859 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4860 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4861 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4862 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4863
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004864 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004865 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004866
4867 KeyEntry {
4868 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004869 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004870 cert: Some(TEST_CERT_BLOB.to_vec()),
4871 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004872 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004873 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004874 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004875 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004876 }
4877 }
4878
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004879 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004880 db: &mut KeystoreDB,
4881 domain: Domain,
4882 namespace: i64,
4883 alias: &str,
4884 logical_only: bool,
4885 ) -> Result<KeyIdGuard> {
4886 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4887 let mut blob_metadata = BlobMetaData::new();
4888 if !logical_only {
4889 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4890 }
4891 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4892
4893 db.set_blob(
4894 &key_id,
4895 SubComponentType::KEY_BLOB,
4896 Some(TEST_KEY_BLOB),
4897 Some(&blob_metadata),
4898 )?;
4899 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4900 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4901
4902 let mut params = make_test_params(None);
4903 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4904
4905 db.insert_keyparameter(&key_id, &params)?;
4906
4907 let mut metadata = KeyMetaData::new();
4908 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4909 db.insert_key_metadata(&key_id, &metadata)?;
4910 rebind_alias(db, &key_id, alias, domain, namespace)?;
4911 Ok(key_id)
4912 }
4913
Eric Biggersb0478cf2023-10-27 03:55:29 +00004914 // Creates an app key that is marked as being superencrypted by the given
4915 // super key ID and that has the given authentication and unlocked device
4916 // parameters. This does not actually superencrypt the key blob.
4917 fn make_superencrypted_key_entry(
4918 db: &mut KeystoreDB,
4919 namespace: i64,
4920 alias: &str,
4921 requires_authentication: bool,
4922 requires_unlocked_device: bool,
4923 super_key_id: i64,
4924 ) -> Result<KeyIdGuard> {
4925 let domain = Domain::APP;
4926 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4927
4928 let mut blob_metadata = BlobMetaData::new();
4929 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4930 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4931 db.set_blob(
4932 &key_id,
4933 SubComponentType::KEY_BLOB,
4934 Some(TEST_KEY_BLOB),
4935 Some(&blob_metadata),
4936 )?;
4937
4938 let mut params = vec![];
4939 if requires_unlocked_device {
4940 params.push(KeyParameter::new(
4941 KeyParameterValue::UnlockedDeviceRequired,
4942 SecurityLevel::TRUSTED_ENVIRONMENT,
4943 ));
4944 }
4945 if requires_authentication {
4946 params.push(KeyParameter::new(
4947 KeyParameterValue::UserSecureID(42),
4948 SecurityLevel::TRUSTED_ENVIRONMENT,
4949 ));
4950 }
4951 db.insert_keyparameter(&key_id, &params)?;
4952
4953 let mut metadata = KeyMetaData::new();
4954 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4955 db.insert_key_metadata(&key_id, &metadata)?;
4956
4957 rebind_alias(db, &key_id, alias, domain, namespace)?;
4958 Ok(key_id)
4959 }
4960
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004961 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4962 let mut params = make_test_params(None);
4963 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4964
4965 let mut blob_metadata = BlobMetaData::new();
4966 if !logical_only {
4967 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4968 }
4969 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4970
4971 let mut metadata = KeyMetaData::new();
4972 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4973
4974 KeyEntry {
4975 id: key_id,
4976 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4977 cert: Some(TEST_CERT_BLOB.to_vec()),
4978 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4979 km_uuid: KEYSTORE_UUID,
4980 parameters: params,
4981 metadata,
4982 pure_cert: false,
4983 }
4984 }
4985
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004986 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004987 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004988 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004989 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004990 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004991 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004992 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004993 Ok((
4994 row.get(0)?,
4995 row.get(1)?,
4996 row.get(2)?,
4997 row.get(3)?,
4998 row.get(4)?,
4999 row.get(5)?,
5000 row.get(6)?,
5001 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005002 },
5003 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005004
5005 println!("Key entry table rows:");
5006 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005007 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005008 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005009 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5010 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005011 );
5012 }
5013 Ok(())
5014 }
5015
5016 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005017 let mut stmt = db
5018 .conn
5019 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005020 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005021 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5022 })?;
5023
5024 println!("Grant table rows:");
5025 for r in rows {
5026 let (id, gt, ki, av) = r.unwrap();
5027 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5028 }
5029 Ok(())
5030 }
5031
Joel Galenson0891bc12020-07-20 10:37:03 -07005032 // Use a custom random number generator that repeats each number once.
5033 // This allows us to test repeated elements.
5034
5035 thread_local! {
5036 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5037 }
5038
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005039 fn reset_random() {
5040 RANDOM_COUNTER.with(|counter| {
5041 *counter.borrow_mut() = 0;
5042 })
5043 }
5044
Joel Galenson0891bc12020-07-20 10:37:03 -07005045 pub fn random() -> i64 {
5046 RANDOM_COUNTER.with(|counter| {
5047 let result = *counter.borrow() / 2;
5048 *counter.borrow_mut() += 1;
5049 result
5050 })
5051 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005052
5053 #[test]
5054 fn test_last_off_body() -> Result<()> {
5055 let mut db = new_test_db()?;
Eric Biggers19b3b0d2024-01-31 22:46:47 +00005056 db.insert_last_off_body(BootTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005057 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005058 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005059 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005060 let one_second = Duration::from_secs(1);
5061 thread::sleep(one_second);
Eric Biggers19b3b0d2024-01-31 22:46:47 +00005062 db.update_last_off_body(BootTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005063 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005064 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005065 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005066 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005067 Ok(())
5068 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005069
5070 #[test]
5071 fn test_unbind_keys_for_user() -> Result<()> {
5072 let mut db = new_test_db()?;
5073 db.unbind_keys_for_user(1, false)?;
5074
5075 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5076 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5077 db.unbind_keys_for_user(2, false)?;
5078
Eran Messeri24f31972023-01-25 17:00:33 +00005079 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
5080 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005081
5082 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00005083 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005084
5085 Ok(())
5086 }
5087
5088 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005089 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5090 let mut db = new_test_db()?;
5091 let super_key = keystore2_crypto::generate_aes256_key()?;
5092 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5093 let (encrypted_super_key, metadata) =
5094 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5095
5096 let key_name_enc = SuperKeyType {
5097 alias: "test_super_key_1",
5098 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005099 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005100 };
5101
5102 let key_name_nonenc = SuperKeyType {
5103 alias: "test_super_key_2",
5104 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005105 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005106 };
5107
5108 // Install two super keys.
5109 db.store_super_key(
5110 1,
5111 &key_name_nonenc,
5112 &super_key,
5113 &BlobMetaData::new(),
5114 &KeyMetaData::new(),
5115 )?;
5116 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5117
5118 // Check that both can be found in the database.
5119 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5120 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5121
5122 // Install the same keys for a different user.
5123 db.store_super_key(
5124 2,
5125 &key_name_nonenc,
5126 &super_key,
5127 &BlobMetaData::new(),
5128 &KeyMetaData::new(),
5129 )?;
5130 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5131
5132 // Check that the second pair of keys can be found in the database.
5133 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5134 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5135
5136 // Delete only encrypted keys.
5137 db.unbind_keys_for_user(1, true)?;
5138
5139 // The encrypted superkey should be gone now.
5140 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5141 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5142
5143 // Reinsert the encrypted key.
5144 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5145
5146 // Check that both can be found in the database, again..
5147 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5148 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5149
5150 // Delete all even unencrypted keys.
5151 db.unbind_keys_for_user(1, false)?;
5152
5153 // Both should be gone now.
5154 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5155 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5156
5157 // Check that the second pair of keys was untouched.
5158 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5159 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5160
5161 Ok(())
5162 }
5163
Eric Biggersb0478cf2023-10-27 03:55:29 +00005164 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5165 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5166 }
5167
5168 // Tests the unbind_auth_bound_keys_for_user() function.
5169 #[test]
5170 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5171 let mut db = new_test_db()?;
5172 let user_id = 1;
5173 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5174 let other_user_id = 2;
5175 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5176 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5177
5178 // Create a superencryption key.
5179 let super_key = keystore2_crypto::generate_aes256_key()?;
5180 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5181 let (encrypted_super_key, blob_metadata) =
5182 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5183 db.store_super_key(
5184 user_id,
5185 super_key_type,
5186 &encrypted_super_key,
5187 &blob_metadata,
5188 &KeyMetaData::new(),
5189 )?;
5190 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5191
5192 // Store 4 superencrypted app keys, one for each possible combination of
5193 // (authentication required, unlocked device required).
5194 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5195 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5196 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5197 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5198 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5199 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5200 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5201 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5202
5203 // Also store a key for a different user that requires authentication.
5204 make_superencrypted_key_entry(
5205 &mut db,
5206 other_user_nspace,
5207 "auth_ud",
5208 true,
5209 true,
5210 super_key_id,
5211 )?;
5212
5213 db.unbind_auth_bound_keys_for_user(user_id)?;
5214
5215 // Verify that only the user's app keys that require authentication were
5216 // deleted. Keys that require an unlocked device but not authentication
5217 // should *not* have been deleted, nor should the super key have been
5218 // deleted, nor should other users' keys have been deleted.
5219 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5220 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5221 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5222 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5223 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5224 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5225
5226 Ok(())
5227 }
5228
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005229 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005230 fn test_store_super_key() -> Result<()> {
5231 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005232 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005233 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005234 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005235 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005236 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005237
5238 let (encrypted_super_key, metadata) =
5239 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005240 db.store_super_key(
5241 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005242 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005243 &encrypted_super_key,
5244 &metadata,
5245 &KeyMetaData::new(),
5246 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005247
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005248 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005249 assert!(db.key_exists(
5250 Domain::APP,
5251 1,
5252 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5253 KeyType::Super
5254 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005255
Eric Biggers673d34a2023-10-18 01:54:18 +00005256 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005257 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005258 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005259 key_entry,
5260 &pw,
5261 None,
5262 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005263
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005264 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005265 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005266
Hasini Gunasingheda895552021-01-27 19:34:37 +00005267 Ok(())
5268 }
Seth Moore78c091f2021-04-09 21:38:30 +00005269
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005270 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005271 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005272 MetricsStorage::KEY_ENTRY,
5273 MetricsStorage::KEY_ENTRY_ID_INDEX,
5274 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5275 MetricsStorage::BLOB_ENTRY,
5276 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5277 MetricsStorage::KEY_PARAMETER,
5278 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5279 MetricsStorage::KEY_METADATA,
5280 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5281 MetricsStorage::GRANT,
5282 MetricsStorage::AUTH_TOKEN,
5283 MetricsStorage::BLOB_METADATA,
5284 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005285 ]
5286 }
5287
5288 /// Perform a simple check to ensure that we can query all the storage types
5289 /// that are supported by the DB. Check for reasonable values.
5290 #[test]
5291 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005292 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005293
5294 let mut db = new_test_db()?;
5295
5296 for t in get_valid_statsd_storage_types() {
5297 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005298 // AuthToken can be less than a page since it's in a btree, not sqlite
5299 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005300 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005301 } else {
5302 assert!(stat.size >= PAGE_SIZE);
5303 }
Seth Moore78c091f2021-04-09 21:38:30 +00005304 assert!(stat.size >= stat.unused_size);
5305 }
5306
5307 Ok(())
5308 }
5309
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005310 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005311 get_valid_statsd_storage_types()
5312 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005313 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005314 .collect()
5315 }
5316
5317 fn assert_storage_increased(
5318 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005319 increased_storage_types: Vec<MetricsStorage>,
5320 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005321 ) {
5322 for storage in increased_storage_types {
5323 // Verify the expected storage increased.
5324 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005325 let old = &baseline[&storage.0];
5326 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005327 assert!(
5328 new.unused_size <= old.unused_size,
5329 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005330 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005331 new.unused_size,
5332 old.unused_size
5333 );
5334
5335 // Update the baseline with the new value so that it succeeds in the
5336 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005337 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005338 }
5339
5340 // Get an updated map of the storage and verify there were no unexpected changes.
5341 let updated_stats = get_storage_stats_map(db);
5342 assert_eq!(updated_stats.len(), baseline.len());
5343
5344 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005345 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005346 let mut s = String::new();
5347 for &k in map.keys() {
5348 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5349 .expect("string concat failed");
5350 }
5351 s
5352 };
5353
5354 assert!(
5355 updated_stats[&k].size == baseline[&k].size
5356 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5357 "updated_stats:\n{}\nbaseline:\n{}",
5358 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005359 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005360 );
5361 }
5362 }
5363
5364 #[test]
5365 fn test_verify_key_table_size_reporting() -> Result<()> {
5366 let mut db = new_test_db()?;
5367 let mut working_stats = get_storage_stats_map(&mut db);
5368
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005369 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005370 assert_storage_increased(
5371 &mut db,
5372 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005373 MetricsStorage::KEY_ENTRY,
5374 MetricsStorage::KEY_ENTRY_ID_INDEX,
5375 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005376 ],
5377 &mut working_stats,
5378 );
5379
5380 let mut blob_metadata = BlobMetaData::new();
5381 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5382 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5383 assert_storage_increased(
5384 &mut db,
5385 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005386 MetricsStorage::BLOB_ENTRY,
5387 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5388 MetricsStorage::BLOB_METADATA,
5389 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005390 ],
5391 &mut working_stats,
5392 );
5393
5394 let params = make_test_params(None);
5395 db.insert_keyparameter(&key_id, &params)?;
5396 assert_storage_increased(
5397 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005398 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005399 &mut working_stats,
5400 );
5401
5402 let mut metadata = KeyMetaData::new();
5403 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5404 db.insert_key_metadata(&key_id, &metadata)?;
5405 assert_storage_increased(
5406 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005407 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005408 &mut working_stats,
5409 );
5410
5411 let mut sum = 0;
5412 for stat in working_stats.values() {
5413 sum += stat.size;
5414 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005415 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005416 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5417
5418 Ok(())
5419 }
5420
5421 #[test]
5422 fn test_verify_auth_table_size_reporting() -> Result<()> {
5423 let mut db = new_test_db()?;
5424 let mut working_stats = get_storage_stats_map(&mut db);
5425 db.insert_auth_token(&HardwareAuthToken {
5426 challenge: 123,
5427 userId: 456,
5428 authenticatorId: 789,
5429 authenticatorType: kmhw_authenticator_type::ANY,
5430 timestamp: Timestamp { milliSeconds: 10 },
5431 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005432 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005433 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005434 Ok(())
5435 }
5436
5437 #[test]
5438 fn test_verify_grant_table_size_reporting() -> Result<()> {
5439 const OWNER: i64 = 1;
5440 let mut db = new_test_db()?;
5441 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5442
5443 let mut working_stats = get_storage_stats_map(&mut db);
5444 db.grant(
5445 &KeyDescriptor {
5446 domain: Domain::APP,
5447 nspace: 0,
5448 alias: Some(TEST_ALIAS.to_string()),
5449 blob: None,
5450 },
5451 OWNER as u32,
5452 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005453 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005454 |_, _| Ok(()),
5455 )?;
5456
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005457 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005458
5459 Ok(())
5460 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005461
5462 #[test]
5463 fn find_auth_token_entry_returns_latest() -> Result<()> {
5464 let mut db = new_test_db()?;
5465 db.insert_auth_token(&HardwareAuthToken {
5466 challenge: 123,
5467 userId: 456,
5468 authenticatorId: 789,
5469 authenticatorType: kmhw_authenticator_type::ANY,
5470 timestamp: Timestamp { milliSeconds: 10 },
5471 mac: b"mac0".to_vec(),
5472 });
5473 std::thread::sleep(std::time::Duration::from_millis(1));
5474 db.insert_auth_token(&HardwareAuthToken {
5475 challenge: 123,
5476 userId: 457,
5477 authenticatorId: 789,
5478 authenticatorType: kmhw_authenticator_type::ANY,
5479 timestamp: Timestamp { milliSeconds: 12 },
5480 mac: b"mac1".to_vec(),
5481 });
5482 std::thread::sleep(std::time::Duration::from_millis(1));
5483 db.insert_auth_token(&HardwareAuthToken {
5484 challenge: 123,
5485 userId: 458,
5486 authenticatorId: 789,
5487 authenticatorType: kmhw_authenticator_type::ANY,
5488 timestamp: Timestamp { milliSeconds: 3 },
5489 mac: b"mac2".to_vec(),
5490 });
5491 // All three entries are in the database
5492 assert_eq!(db.perboot.auth_tokens_len(), 3);
5493 // It selected the most recent timestamp
5494 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5495 Ok(())
5496 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005497
5498 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005499 fn test_load_key_descriptor() -> Result<()> {
5500 let mut db = new_test_db()?;
5501 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5502
5503 let key = db.load_key_descriptor(key_id)?.unwrap();
5504
5505 assert_eq!(key.domain, Domain::APP);
5506 assert_eq!(key.nspace, 1);
5507 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5508
5509 // No such id
5510 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5511 Ok(())
5512 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005513
5514 #[test]
5515 fn test_get_list_app_uids_for_sid() -> Result<()> {
5516 let uid: i32 = 1;
5517 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5518 let first_sid = 667;
5519 let second_sid = 669;
5520 let first_app_id: i64 = 123 + uid_offset;
5521 let second_app_id: i64 = 456 + uid_offset;
5522 let third_app_id: i64 = 789 + uid_offset;
5523 let unrelated_app_id: i64 = 1011 + uid_offset;
5524 let mut db = new_test_db()?;
5525 make_test_key_entry_with_sids(
5526 &mut db,
5527 Domain::APP,
5528 first_app_id,
5529 TEST_ALIAS,
5530 None,
5531 &[first_sid],
5532 )
5533 .context("test_get_list_app_uids_for_sid")?;
5534 make_test_key_entry_with_sids(
5535 &mut db,
5536 Domain::APP,
5537 second_app_id,
5538 "alias2",
5539 None,
5540 &[first_sid],
5541 )
5542 .context("test_get_list_app_uids_for_sid")?;
5543 make_test_key_entry_with_sids(
5544 &mut db,
5545 Domain::APP,
5546 second_app_id,
5547 TEST_ALIAS,
5548 None,
5549 &[second_sid],
5550 )
5551 .context("test_get_list_app_uids_for_sid")?;
5552 make_test_key_entry_with_sids(
5553 &mut db,
5554 Domain::APP,
5555 third_app_id,
5556 "alias3",
5557 None,
5558 &[second_sid],
5559 )
5560 .context("test_get_list_app_uids_for_sid")?;
5561 make_test_key_entry_with_sids(
5562 &mut db,
5563 Domain::APP,
5564 unrelated_app_id,
5565 TEST_ALIAS,
5566 None,
5567 &[],
5568 )
5569 .context("test_get_list_app_uids_for_sid")?;
5570
5571 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5572 first_sid_apps.sort();
5573 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5574 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5575 second_sid_apps.sort();
5576 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5577 Ok(())
5578 }
5579
5580 #[test]
5581 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5582 let uid: i32 = 1;
5583 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5584 let first_sid = 667;
5585 let second_sid = 669;
5586 let third_sid = 772;
5587 let first_app_id: i64 = 123 + uid_offset;
5588 let second_app_id: i64 = 456 + uid_offset;
5589 let mut db = new_test_db()?;
5590 make_test_key_entry_with_sids(
5591 &mut db,
5592 Domain::APP,
5593 first_app_id,
5594 TEST_ALIAS,
5595 None,
5596 &[first_sid, second_sid],
5597 )
5598 .context("test_get_list_app_uids_for_sid")?;
5599 make_test_key_entry_with_sids(
5600 &mut db,
5601 Domain::APP,
5602 second_app_id,
5603 "alias2",
5604 None,
5605 &[second_sid, third_sid],
5606 )
5607 .context("test_get_list_app_uids_for_sid")?;
5608
5609 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5610 assert_eq!(first_sid_apps, vec![first_app_id]);
5611
5612 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5613 second_sid_apps.sort();
5614 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5615
5616 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5617 assert_eq!(third_sid_apps, vec![second_app_id]);
5618 Ok(())
5619 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005620}