blob: f343cb333b95d4b5a7c05c6108cb444c9f834c45 [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 Biggersb5613da2024-03-13 19:31:42 +00002867 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002868 where
2869 F: Fn(&AuthTokenEntry) -> bool,
2870 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002871 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002872 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002873
2874 /// Load descriptor of a key by key id
2875 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2876 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2877
2878 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2879 tx.query_row(
2880 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2881 params![key_id],
2882 |row| {
2883 Ok(KeyDescriptor {
2884 domain: Domain(row.get(0)?),
2885 nspace: row.get(1)?,
2886 alias: row.get(2)?,
2887 blob: None,
2888 })
2889 },
2890 )
2891 .optional()
2892 .context("Trying to load key descriptor")
2893 .no_gc()
2894 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002895 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002896 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002897
2898 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2899 /// (for the given user_id).
2900 /// This is helpful for finding out which apps will have their keys invalidated when
2901 /// the user changes biometrics enrollment or removes their LSKF.
2902 pub fn get_app_uids_affected_by_sid(
2903 &mut self,
2904 user_id: i32,
2905 secure_user_id: i64,
2906 ) -> Result<Vec<i64>> {
2907 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2908
2909 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2910 let mut stmt = tx
2911 .prepare(&format!(
2912 "SELECT id, namespace from persistent.keyentry
2913 WHERE key_type = ?
2914 AND domain = ?
2915 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2916 AND state = ?;",
2917 ))
2918 .context(concat!(
2919 "In get_app_uids_affected_by_sid, ",
2920 "failed to prepare the query to find the keys created by apps."
2921 ))?;
2922
2923 let mut rows = stmt
2924 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2925 .context(ks_err!("Failed to query the keys created by apps."))?;
2926
2927 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2928 db_utils::with_rows_extract_all(&mut rows, |row| {
2929 key_ids_and_app_uids.insert(
2930 row.get(0).context("Failed to read key id of a key created by an app.")?,
2931 row.get(1).context("Failed to read the app uid")?,
2932 );
2933 Ok(())
2934 })?;
2935 Ok(key_ids_and_app_uids).no_gc()
2936 })?;
2937 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2938 for (key_id, app_uid) in key_ids_and_app_uids {
2939 // Read the key parameters for each key in its own transaction. It is OK to ignore
2940 // an error to get the properties of a particular key since it might have been deleted
2941 // under our feet after the previous transaction concluded. If the key was deleted
2942 // then it is no longer applicable if it was auth-bound or not.
2943 if let Ok(is_key_bound_to_sid) =
2944 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2945 let params = Self::load_key_parameters(key_id, tx)
2946 .context("Failed to load key parameters.")?;
2947 // Check if the key is bound to this secure user ID.
2948 let is_key_bound_to_sid = params.iter().any(|kp| {
2949 matches!(
2950 kp.key_parameter_value(),
2951 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2952 )
2953 });
2954 Ok(is_key_bound_to_sid).no_gc()
2955 })
2956 {
2957 if is_key_bound_to_sid {
2958 app_uids_affected_by_sid.insert(app_uid);
2959 }
2960 }
2961 }
2962
2963 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2964 Ok(app_uids_vec)
2965 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002966}
2967
2968#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002969pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002970
2971 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002972 use crate::key_parameter::{
2973 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2974 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2975 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002976 use crate::key_perm_set;
2977 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002978 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002979 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002980 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2981 HardwareAuthToken::HardwareAuthToken,
2982 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002983 };
2984 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002985 Timestamp::Timestamp,
2986 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002987 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07002988 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002989 use std::collections::BTreeMap;
2990 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002991 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002992 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002993 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002994 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002995 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002996 #[cfg(disabled)]
2997 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002998
Seth Moore7ee79f92021-12-07 11:42:49 -08002999 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003000 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003001
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003002 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003003 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003004 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003005 })?;
3006 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003007 }
3008
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003009 fn rebind_alias(
3010 db: &mut KeystoreDB,
3011 newid: &KeyIdGuard,
3012 alias: &str,
3013 domain: Domain,
3014 namespace: i64,
3015 ) -> Result<bool> {
3016 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003017 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003018 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003019 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003020 }
3021
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003022 #[test]
3023 fn datetime() -> Result<()> {
3024 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003025 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003026 let now = SystemTime::now();
3027 let duration = Duration::from_secs(1000);
3028 let then = now.checked_sub(duration).unwrap();
3029 let soon = now.checked_add(duration).unwrap();
3030 conn.execute(
3031 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3032 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3033 )?;
3034 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003035 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003036 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3037 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3038 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3039 assert!(rows.next()?.is_none());
3040 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3041 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3042 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3043 Ok(())
3044 }
3045
Joel Galenson0891bc12020-07-20 10:37:03 -07003046 // Ensure that we're using the "injected" random function, not the real one.
3047 #[test]
3048 fn test_mocked_random() {
3049 let rand1 = random();
3050 let rand2 = random();
3051 let rand3 = random();
3052 if rand1 == rand2 {
3053 assert_eq!(rand2 + 1, rand3);
3054 } else {
3055 assert_eq!(rand1 + 1, rand2);
3056 assert_eq!(rand2, rand3);
3057 }
3058 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003059
Joel Galenson26f4d012020-07-17 14:57:21 -07003060 // Test that we have the correct tables.
3061 #[test]
3062 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003063 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003064 let tables = db
3065 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003066 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003067 .query_map(params![], |row| row.get(0))?
3068 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003069 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003070 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003071 assert_eq!(tables[1], "blobmetadata");
3072 assert_eq!(tables[2], "grant");
3073 assert_eq!(tables[3], "keyentry");
3074 assert_eq!(tables[4], "keymetadata");
3075 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003076 Ok(())
3077 }
3078
3079 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003080 fn test_auth_token_table_invariant() -> Result<()> {
3081 let mut db = new_test_db()?;
3082 let auth_token1 = HardwareAuthToken {
3083 challenge: i64::MAX,
3084 userId: 200,
3085 authenticatorId: 200,
3086 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3087 timestamp: Timestamp { milliSeconds: 500 },
3088 mac: String::from("mac").into_bytes(),
3089 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003090 db.insert_auth_token(&auth_token1);
3091 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003092 assert_eq!(auth_tokens_returned.len(), 1);
3093
3094 // insert another auth token with the same values for the columns in the UNIQUE constraint
3095 // of the auth token table and different value for timestamp
3096 let auth_token2 = HardwareAuthToken {
3097 challenge: i64::MAX,
3098 userId: 200,
3099 authenticatorId: 200,
3100 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3101 timestamp: Timestamp { milliSeconds: 600 },
3102 mac: String::from("mac").into_bytes(),
3103 };
3104
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003105 db.insert_auth_token(&auth_token2);
3106 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003107 assert_eq!(auth_tokens_returned.len(), 1);
3108
3109 if let Some(auth_token) = auth_tokens_returned.pop() {
3110 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3111 }
3112
3113 // insert another auth token with the different values for the columns in the UNIQUE
3114 // constraint of the auth token table
3115 let auth_token3 = HardwareAuthToken {
3116 challenge: i64::MAX,
3117 userId: 201,
3118 authenticatorId: 200,
3119 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3120 timestamp: Timestamp { milliSeconds: 600 },
3121 mac: String::from("mac").into_bytes(),
3122 };
3123
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003124 db.insert_auth_token(&auth_token3);
3125 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003126 assert_eq!(auth_tokens_returned.len(), 2);
3127
3128 Ok(())
3129 }
3130
3131 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003132 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3133 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003134 }
3135
3136 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003137 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003138 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003139 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003140
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003141 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003142 let entries = get_keyentry(&db)?;
3143 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003144
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003145 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003146
3147 let entries_new = get_keyentry(&db)?;
3148 assert_eq!(entries, entries_new);
3149 Ok(())
3150 }
3151
3152 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003153 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003154 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3155 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003156 }
3157
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003158 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003159
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003160 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3161 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003162
3163 let entries = get_keyentry(&db)?;
3164 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003165 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3166 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003167
3168 // Test that we must pass in a valid Domain.
3169 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003170 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003171 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003172 );
3173 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003174 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003175 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003176 );
3177 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003178 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003179 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003180 );
3181
3182 Ok(())
3183 }
3184
Joel Galenson33c04ad2020-08-03 11:04:38 -07003185 #[test]
3186 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003187 fn extractor(
3188 ke: &KeyEntryRow,
3189 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3190 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003191 }
3192
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003193 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003194 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3195 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003196 let entries = get_keyentry(&db)?;
3197 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003198 assert_eq!(
3199 extractor(&entries[0]),
3200 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3201 );
3202 assert_eq!(
3203 extractor(&entries[1]),
3204 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3205 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003206
3207 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003208 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003209 let entries = get_keyentry(&db)?;
3210 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003211 assert_eq!(
3212 extractor(&entries[0]),
3213 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3214 );
3215 assert_eq!(
3216 extractor(&entries[1]),
3217 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3218 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003219
3220 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003221 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003222 let entries = get_keyentry(&db)?;
3223 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003224 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3225 assert_eq!(
3226 extractor(&entries[1]),
3227 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3228 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003229
3230 // Test that we must pass in a valid Domain.
3231 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003232 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003233 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003234 );
3235 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003236 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003237 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003238 );
3239 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003240 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003241 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003242 );
3243
3244 // Test that we correctly handle setting an alias for something that does not exist.
3245 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003246 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003247 "Expected to update a single entry but instead updated 0",
3248 );
3249 // Test that we correctly abort the transaction in this case.
3250 let entries = get_keyentry(&db)?;
3251 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003252 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3253 assert_eq!(
3254 extractor(&entries[1]),
3255 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3256 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003257
3258 Ok(())
3259 }
3260
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003261 #[test]
3262 fn test_grant_ungrant() -> Result<()> {
3263 const CALLER_UID: u32 = 15;
3264 const GRANTEE_UID: u32 = 12;
3265 const SELINUX_NAMESPACE: i64 = 7;
3266
3267 let mut db = new_test_db()?;
3268 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003269 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3270 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3271 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003272 )?;
3273 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003274 domain: super::Domain::APP,
3275 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003276 alias: Some("key".to_string()),
3277 blob: None,
3278 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003279 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3280 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003281
3282 // Reset totally predictable random number generator in case we
3283 // are not the first test running on this thread.
3284 reset_random();
3285 let next_random = 0i64;
3286
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003287 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003288 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003289 assert_eq!(*a, PVEC1);
3290 assert_eq!(
3291 *k,
3292 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003293 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003294 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003295 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003296 alias: Some("key".to_string()),
3297 blob: None,
3298 }
3299 );
3300 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003301 })
3302 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303
3304 assert_eq!(
3305 app_granted_key,
3306 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003307 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003308 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003309 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003310 alias: None,
3311 blob: None,
3312 }
3313 );
3314
3315 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003316 domain: super::Domain::SELINUX,
3317 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003318 alias: Some("yek".to_string()),
3319 blob: None,
3320 };
3321
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003322 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003323 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003324 assert_eq!(*a, PVEC1);
3325 assert_eq!(
3326 *k,
3327 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003328 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003329 // namespace must be the supplied SELinux
3330 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003331 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003332 alias: Some("yek".to_string()),
3333 blob: None,
3334 }
3335 );
3336 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003337 })
3338 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003339
3340 assert_eq!(
3341 selinux_granted_key,
3342 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003343 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003344 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003345 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003346 alias: None,
3347 blob: None,
3348 }
3349 );
3350
3351 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003352 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003353 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003354 assert_eq!(*a, PVEC2);
3355 assert_eq!(
3356 *k,
3357 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003358 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003359 // namespace must be the supplied SELinux
3360 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003361 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003362 alias: Some("yek".to_string()),
3363 blob: None,
3364 }
3365 );
3366 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003367 })
3368 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003369
3370 assert_eq!(
3371 selinux_granted_key,
3372 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003373 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003374 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003375 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003376 alias: None,
3377 blob: None,
3378 }
3379 );
3380
3381 {
3382 // Limiting scope of stmt, because it borrows db.
3383 let mut stmt = db
3384 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003385 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003386 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3387 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3388 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003389
3390 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003391 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003392 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003393 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003394 assert!(rows.next().is_none());
3395 }
3396
3397 debug_dump_keyentry_table(&mut db)?;
3398 println!("app_key {:?}", app_key);
3399 println!("selinux_key {:?}", selinux_key);
3400
Janis Danisevskis66784c42021-01-27 08:40:25 -08003401 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3402 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003403
3404 Ok(())
3405 }
3406
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003407 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003408 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3409 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3410
3411 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003412 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003413 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003414 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003415 let mut blob_metadata = BlobMetaData::new();
3416 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3417 db.set_blob(
3418 &key_id,
3419 SubComponentType::KEY_BLOB,
3420 Some(TEST_KEY_BLOB),
3421 Some(&blob_metadata),
3422 )?;
3423 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3424 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003425 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003426
3427 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003428 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003429 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003430 )?;
3431 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003432 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003433 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003434 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003435 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003436 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003437 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003438 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003439 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003440 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003441
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003442 drop(rows);
3443 drop(stmt);
3444
3445 assert_eq!(
3446 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3447 BlobMetaData::load_from_db(id, tx).no_gc()
3448 })
3449 .expect("Should find blob metadata."),
3450 blob_metadata
3451 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003452 Ok(())
3453 }
3454
3455 static TEST_ALIAS: &str = "my super duper key";
3456
3457 #[test]
3458 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3459 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003460 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003461 .context("test_insert_and_load_full_keyentry_domain_app")?
3462 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003463 let (_key_guard, key_entry) = db
3464 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003465 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003466 domain: Domain::APP,
3467 nspace: 0,
3468 alias: Some(TEST_ALIAS.to_string()),
3469 blob: None,
3470 },
3471 KeyType::Client,
3472 KeyEntryLoadBits::BOTH,
3473 1,
3474 |_k, _av| Ok(()),
3475 )
3476 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003477 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003478
3479 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003480 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003481 domain: Domain::APP,
3482 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003483 alias: Some(TEST_ALIAS.to_string()),
3484 blob: None,
3485 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003486 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003487 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003488 |_, _| Ok(()),
3489 )
3490 .unwrap();
3491
3492 assert_eq!(
3493 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3494 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003495 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003496 domain: Domain::APP,
3497 nspace: 0,
3498 alias: Some(TEST_ALIAS.to_string()),
3499 blob: None,
3500 },
3501 KeyType::Client,
3502 KeyEntryLoadBits::NONE,
3503 1,
3504 |_k, _av| Ok(()),
3505 )
3506 .unwrap_err()
3507 .root_cause()
3508 .downcast_ref::<KsError>()
3509 );
3510
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003511 Ok(())
3512 }
3513
3514 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003515 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3516 let mut db = new_test_db()?;
3517
3518 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003519 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003520 domain: Domain::APP,
3521 nspace: 1,
3522 alias: Some(TEST_ALIAS.to_string()),
3523 blob: None,
3524 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003525 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003526 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003527 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003528 )
3529 .expect("Trying to insert cert.");
3530
3531 let (_key_guard, mut key_entry) = db
3532 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003533 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003534 domain: Domain::APP,
3535 nspace: 1,
3536 alias: Some(TEST_ALIAS.to_string()),
3537 blob: None,
3538 },
3539 KeyType::Client,
3540 KeyEntryLoadBits::PUBLIC,
3541 1,
3542 |_k, _av| Ok(()),
3543 )
3544 .expect("Trying to read certificate entry.");
3545
3546 assert!(key_entry.pure_cert());
3547 assert!(key_entry.cert().is_none());
3548 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3549
3550 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003551 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003552 domain: Domain::APP,
3553 nspace: 1,
3554 alias: Some(TEST_ALIAS.to_string()),
3555 blob: None,
3556 },
3557 KeyType::Client,
3558 1,
3559 |_, _| Ok(()),
3560 )
3561 .unwrap();
3562
3563 assert_eq!(
3564 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3565 db.load_key_entry(
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 KeyEntryLoadBits::NONE,
3574 1,
3575 |_k, _av| Ok(()),
3576 )
3577 .unwrap_err()
3578 .root_cause()
3579 .downcast_ref::<KsError>()
3580 );
3581
3582 Ok(())
3583 }
3584
3585 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003586 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3587 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003588 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003589 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3590 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003591 let (_key_guard, key_entry) = db
3592 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003593 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003594 domain: Domain::SELINUX,
3595 nspace: 1,
3596 alias: Some(TEST_ALIAS.to_string()),
3597 blob: None,
3598 },
3599 KeyType::Client,
3600 KeyEntryLoadBits::BOTH,
3601 1,
3602 |_k, _av| Ok(()),
3603 )
3604 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003605 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003606
3607 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003608 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003609 domain: Domain::SELINUX,
3610 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003611 alias: Some(TEST_ALIAS.to_string()),
3612 blob: None,
3613 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003614 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003615 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003616 |_, _| Ok(()),
3617 )
3618 .unwrap();
3619
3620 assert_eq!(
3621 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3622 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003623 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003624 domain: Domain::SELINUX,
3625 nspace: 1,
3626 alias: Some(TEST_ALIAS.to_string()),
3627 blob: None,
3628 },
3629 KeyType::Client,
3630 KeyEntryLoadBits::NONE,
3631 1,
3632 |_k, _av| Ok(()),
3633 )
3634 .unwrap_err()
3635 .root_cause()
3636 .downcast_ref::<KsError>()
3637 );
3638
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003639 Ok(())
3640 }
3641
3642 #[test]
3643 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3644 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003645 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003646 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3647 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003648 let (_, key_entry) = db
3649 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003650 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003651 KeyType::Client,
3652 KeyEntryLoadBits::BOTH,
3653 1,
3654 |_k, _av| Ok(()),
3655 )
3656 .unwrap();
3657
Qi Wub9433b52020-12-01 14:52:46 +08003658 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003659
3660 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003661 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003662 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003663 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003664 |_, _| Ok(()),
3665 )
3666 .unwrap();
3667
3668 assert_eq!(
3669 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3670 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003671 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003672 KeyType::Client,
3673 KeyEntryLoadBits::NONE,
3674 1,
3675 |_k, _av| Ok(()),
3676 )
3677 .unwrap_err()
3678 .root_cause()
3679 .downcast_ref::<KsError>()
3680 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003681
3682 Ok(())
3683 }
3684
3685 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003686 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3687 let mut db = new_test_db()?;
3688 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3689 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3690 .0;
3691 // Update the usage count of the limited use key.
3692 db.check_and_update_key_usage_count(key_id)?;
3693
3694 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003695 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003696 KeyType::Client,
3697 KeyEntryLoadBits::BOTH,
3698 1,
3699 |_k, _av| Ok(()),
3700 )?;
3701
3702 // The usage count is decremented now.
3703 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3704
3705 Ok(())
3706 }
3707
3708 #[test]
3709 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3710 let mut db = new_test_db()?;
3711 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3712 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3713 .0;
3714 // Update the usage count of the limited use key.
3715 db.check_and_update_key_usage_count(key_id).expect(concat!(
3716 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3717 "This should succeed."
3718 ));
3719
3720 // Try to update the exhausted limited use key.
3721 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3722 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3723 "This should fail."
3724 ));
3725 assert_eq!(
3726 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3727 e.root_cause().downcast_ref::<KsError>().unwrap()
3728 );
3729
3730 Ok(())
3731 }
3732
3733 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003734 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3735 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003736 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003737 .context("test_insert_and_load_full_keyentry_from_grant")?
3738 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003739
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003740 let granted_key = db
3741 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003742 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003743 domain: Domain::APP,
3744 nspace: 0,
3745 alias: Some(TEST_ALIAS.to_string()),
3746 blob: None,
3747 },
3748 1,
3749 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003750 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003751 |_k, _av| Ok(()),
3752 )
3753 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754
3755 debug_dump_grant_table(&mut db)?;
3756
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003757 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003758 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3759 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003760 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003761 Ok(())
3762 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003763 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003764
Qi Wub9433b52020-12-01 14:52:46 +08003765 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766
Janis Danisevskis66784c42021-01-27 08:40:25 -08003767 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003768
3769 assert_eq!(
3770 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3771 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003772 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003773 KeyType::Client,
3774 KeyEntryLoadBits::NONE,
3775 2,
3776 |_k, _av| Ok(()),
3777 )
3778 .unwrap_err()
3779 .root_cause()
3780 .downcast_ref::<KsError>()
3781 );
3782
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003783 Ok(())
3784 }
3785
Janis Danisevskis45760022021-01-19 16:34:10 -08003786 // This test attempts to load a key by key id while the caller is not the owner
3787 // but a grant exists for the given key and the caller.
3788 #[test]
3789 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3790 let mut db = new_test_db()?;
3791 const OWNER_UID: u32 = 1u32;
3792 const GRANTEE_UID: u32 = 2u32;
3793 const SOMEONE_ELSE_UID: u32 = 3u32;
3794 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3795 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3796 .0;
3797
3798 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003799 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003800 domain: Domain::APP,
3801 nspace: 0,
3802 alias: Some(TEST_ALIAS.to_string()),
3803 blob: None,
3804 },
3805 OWNER_UID,
3806 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003807 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003808 |_k, _av| Ok(()),
3809 )
3810 .unwrap();
3811
3812 debug_dump_grant_table(&mut db)?;
3813
3814 let id_descriptor =
3815 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3816
3817 let (_, key_entry) = db
3818 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003819 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003820 KeyType::Client,
3821 KeyEntryLoadBits::BOTH,
3822 GRANTEE_UID,
3823 |k, av| {
3824 assert_eq!(Domain::APP, k.domain);
3825 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003826 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003827 Ok(())
3828 },
3829 )
3830 .unwrap();
3831
3832 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3833
3834 let (_, key_entry) = db
3835 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003836 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003837 KeyType::Client,
3838 KeyEntryLoadBits::BOTH,
3839 SOMEONE_ELSE_UID,
3840 |k, av| {
3841 assert_eq!(Domain::APP, k.domain);
3842 assert_eq!(OWNER_UID as i64, k.nspace);
3843 assert!(av.is_none());
3844 Ok(())
3845 },
3846 )
3847 .unwrap();
3848
3849 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3850
Janis Danisevskis66784c42021-01-27 08:40:25 -08003851 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003852
3853 assert_eq!(
3854 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3855 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003856 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003857 KeyType::Client,
3858 KeyEntryLoadBits::NONE,
3859 GRANTEE_UID,
3860 |_k, _av| Ok(()),
3861 )
3862 .unwrap_err()
3863 .root_cause()
3864 .downcast_ref::<KsError>()
3865 );
3866
3867 Ok(())
3868 }
3869
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003870 // Creates a key migrates it to a different location and then tries to access it by the old
3871 // and new location.
3872 #[test]
3873 fn test_migrate_key_app_to_app() -> Result<()> {
3874 let mut db = new_test_db()?;
3875 const SOURCE_UID: u32 = 1u32;
3876 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003877 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3878 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003879 let key_id_guard =
3880 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3881 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3882
3883 let source_descriptor: KeyDescriptor = KeyDescriptor {
3884 domain: Domain::APP,
3885 nspace: -1,
3886 alias: Some(SOURCE_ALIAS.to_string()),
3887 blob: None,
3888 };
3889
3890 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3891 domain: Domain::APP,
3892 nspace: -1,
3893 alias: Some(DESTINATION_ALIAS.to_string()),
3894 blob: None,
3895 };
3896
3897 let key_id = key_id_guard.id();
3898
3899 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3900 Ok(())
3901 })
3902 .unwrap();
3903
3904 let (_, key_entry) = db
3905 .load_key_entry(
3906 &destination_descriptor,
3907 KeyType::Client,
3908 KeyEntryLoadBits::BOTH,
3909 DESTINATION_UID,
3910 |k, av| {
3911 assert_eq!(Domain::APP, k.domain);
3912 assert_eq!(DESTINATION_UID as i64, k.nspace);
3913 assert!(av.is_none());
3914 Ok(())
3915 },
3916 )
3917 .unwrap();
3918
3919 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3920
3921 assert_eq!(
3922 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3923 db.load_key_entry(
3924 &source_descriptor,
3925 KeyType::Client,
3926 KeyEntryLoadBits::NONE,
3927 SOURCE_UID,
3928 |_k, _av| Ok(()),
3929 )
3930 .unwrap_err()
3931 .root_cause()
3932 .downcast_ref::<KsError>()
3933 );
3934
3935 Ok(())
3936 }
3937
3938 // Creates a key migrates it to a different location and then tries to access it by the old
3939 // and new location.
3940 #[test]
3941 fn test_migrate_key_app_to_selinux() -> Result<()> {
3942 let mut db = new_test_db()?;
3943 const SOURCE_UID: u32 = 1u32;
3944 const DESTINATION_UID: u32 = 2u32;
3945 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003946 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3947 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003948 let key_id_guard =
3949 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3950 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3951
3952 let source_descriptor: KeyDescriptor = KeyDescriptor {
3953 domain: Domain::APP,
3954 nspace: -1,
3955 alias: Some(SOURCE_ALIAS.to_string()),
3956 blob: None,
3957 };
3958
3959 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3960 domain: Domain::SELINUX,
3961 nspace: DESTINATION_NAMESPACE,
3962 alias: Some(DESTINATION_ALIAS.to_string()),
3963 blob: None,
3964 };
3965
3966 let key_id = key_id_guard.id();
3967
3968 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3969 Ok(())
3970 })
3971 .unwrap();
3972
3973 let (_, key_entry) = db
3974 .load_key_entry(
3975 &destination_descriptor,
3976 KeyType::Client,
3977 KeyEntryLoadBits::BOTH,
3978 DESTINATION_UID,
3979 |k, av| {
3980 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003981 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003982 assert!(av.is_none());
3983 Ok(())
3984 },
3985 )
3986 .unwrap();
3987
3988 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3989
3990 assert_eq!(
3991 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3992 db.load_key_entry(
3993 &source_descriptor,
3994 KeyType::Client,
3995 KeyEntryLoadBits::NONE,
3996 SOURCE_UID,
3997 |_k, _av| Ok(()),
3998 )
3999 .unwrap_err()
4000 .root_cause()
4001 .downcast_ref::<KsError>()
4002 );
4003
4004 Ok(())
4005 }
4006
4007 // Creates two keys and tries to migrate the first to the location of the second which
4008 // is expected to fail.
4009 #[test]
4010 fn test_migrate_key_destination_occupied() -> Result<()> {
4011 let mut db = new_test_db()?;
4012 const SOURCE_UID: u32 = 1u32;
4013 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004014 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4015 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004016 let key_id_guard =
4017 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4018 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4019 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4020 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4021
4022 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4023 domain: Domain::APP,
4024 nspace: -1,
4025 alias: Some(DESTINATION_ALIAS.to_string()),
4026 blob: None,
4027 };
4028
4029 assert_eq!(
4030 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4031 db.migrate_key_namespace(
4032 key_id_guard,
4033 &destination_descriptor,
4034 DESTINATION_UID,
4035 |_k| Ok(())
4036 )
4037 .unwrap_err()
4038 .root_cause()
4039 .downcast_ref::<KsError>()
4040 );
4041
4042 Ok(())
4043 }
4044
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004045 #[test]
4046 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004047 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4048 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4049 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004050 const UID: u32 = 33;
4051 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4052 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4053 let key_id_untouched1 =
4054 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4055 let key_id_untouched2 =
4056 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4057 let key_id_deleted =
4058 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4059
4060 let (_, key_entry) = db
4061 .load_key_entry(
4062 &KeyDescriptor {
4063 domain: Domain::APP,
4064 nspace: -1,
4065 alias: Some(ALIAS1.to_string()),
4066 blob: None,
4067 },
4068 KeyType::Client,
4069 KeyEntryLoadBits::BOTH,
4070 UID,
4071 |k, av| {
4072 assert_eq!(Domain::APP, k.domain);
4073 assert_eq!(UID as i64, k.nspace);
4074 assert!(av.is_none());
4075 Ok(())
4076 },
4077 )
4078 .unwrap();
4079 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4080 let (_, key_entry) = db
4081 .load_key_entry(
4082 &KeyDescriptor {
4083 domain: Domain::APP,
4084 nspace: -1,
4085 alias: Some(ALIAS2.to_string()),
4086 blob: None,
4087 },
4088 KeyType::Client,
4089 KeyEntryLoadBits::BOTH,
4090 UID,
4091 |k, av| {
4092 assert_eq!(Domain::APP, k.domain);
4093 assert_eq!(UID as i64, k.nspace);
4094 assert!(av.is_none());
4095 Ok(())
4096 },
4097 )
4098 .unwrap();
4099 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4100 let (_, key_entry) = db
4101 .load_key_entry(
4102 &KeyDescriptor {
4103 domain: Domain::APP,
4104 nspace: -1,
4105 alias: Some(ALIAS3.to_string()),
4106 blob: None,
4107 },
4108 KeyType::Client,
4109 KeyEntryLoadBits::BOTH,
4110 UID,
4111 |k, av| {
4112 assert_eq!(Domain::APP, k.domain);
4113 assert_eq!(UID as i64, k.nspace);
4114 assert!(av.is_none());
4115 Ok(())
4116 },
4117 )
4118 .unwrap();
4119 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4120
4121 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4122 KeystoreDB::from_0_to_1(tx).no_gc()
4123 })
4124 .unwrap();
4125
4126 let (_, key_entry) = db
4127 .load_key_entry(
4128 &KeyDescriptor {
4129 domain: Domain::APP,
4130 nspace: -1,
4131 alias: Some(ALIAS1.to_string()),
4132 blob: None,
4133 },
4134 KeyType::Client,
4135 KeyEntryLoadBits::BOTH,
4136 UID,
4137 |k, av| {
4138 assert_eq!(Domain::APP, k.domain);
4139 assert_eq!(UID as i64, k.nspace);
4140 assert!(av.is_none());
4141 Ok(())
4142 },
4143 )
4144 .unwrap();
4145 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4146 let (_, key_entry) = db
4147 .load_key_entry(
4148 &KeyDescriptor {
4149 domain: Domain::APP,
4150 nspace: -1,
4151 alias: Some(ALIAS2.to_string()),
4152 blob: None,
4153 },
4154 KeyType::Client,
4155 KeyEntryLoadBits::BOTH,
4156 UID,
4157 |k, av| {
4158 assert_eq!(Domain::APP, k.domain);
4159 assert_eq!(UID as i64, k.nspace);
4160 assert!(av.is_none());
4161 Ok(())
4162 },
4163 )
4164 .unwrap();
4165 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4166 assert_eq!(
4167 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4168 db.load_key_entry(
4169 &KeyDescriptor {
4170 domain: Domain::APP,
4171 nspace: -1,
4172 alias: Some(ALIAS3.to_string()),
4173 blob: None,
4174 },
4175 KeyType::Client,
4176 KeyEntryLoadBits::BOTH,
4177 UID,
4178 |k, av| {
4179 assert_eq!(Domain::APP, k.domain);
4180 assert_eq!(UID as i64, k.nspace);
4181 assert!(av.is_none());
4182 Ok(())
4183 },
4184 )
4185 .unwrap_err()
4186 .root_cause()
4187 .downcast_ref::<KsError>()
4188 );
4189 }
4190
Janis Danisevskisaec14592020-11-12 09:41:49 -08004191 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4192
Janis Danisevskisaec14592020-11-12 09:41:49 -08004193 #[test]
4194 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4195 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004196 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4197 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004198 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004199 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004200 .context("test_insert_and_load_full_keyentry_domain_app")?
4201 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004202 let (_key_guard, key_entry) = db
4203 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004204 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004205 domain: Domain::APP,
4206 nspace: 0,
4207 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4208 blob: None,
4209 },
4210 KeyType::Client,
4211 KeyEntryLoadBits::BOTH,
4212 33,
4213 |_k, _av| Ok(()),
4214 )
4215 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004216 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004217 let state = Arc::new(AtomicU8::new(1));
4218 let state2 = state.clone();
4219
4220 // Spawning a second thread that attempts to acquire the key id lock
4221 // for the same key as the primary thread. The primary thread then
4222 // waits, thereby forcing the secondary thread into the second stage
4223 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4224 // The test succeeds if the secondary thread observes the transition
4225 // of `state` from 1 to 2, despite having a whole second to overtake
4226 // the primary thread.
4227 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004228 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004229 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004230 assert!(db
4231 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004232 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004233 domain: Domain::APP,
4234 nspace: 0,
4235 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4236 blob: None,
4237 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004238 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004239 KeyEntryLoadBits::BOTH,
4240 33,
4241 |_k, _av| Ok(()),
4242 )
4243 .is_ok());
4244 // We should only see a 2 here because we can only return
4245 // from load_key_entry when the `_key_guard` expires,
4246 // which happens at the end of the scope.
4247 assert_eq!(2, state2.load(Ordering::Relaxed));
4248 });
4249
4250 thread::sleep(std::time::Duration::from_millis(1000));
4251
4252 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4253
4254 // Return the handle from this scope so we can join with the
4255 // secondary thread after the key id lock has expired.
4256 handle
4257 // This is where the `_key_guard` goes out of scope,
4258 // which is the reason for concurrent load_key_entry on the same key
4259 // to unblock.
4260 };
4261 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4262 // main test thread. We will not see failing asserts in secondary threads otherwise.
4263 handle.join().unwrap();
4264 Ok(())
4265 }
4266
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004267 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004268 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004269 let temp_dir =
4270 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4271
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004272 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4273 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004274
4275 let _tx1 = db1
4276 .conn
4277 .transaction_with_behavior(TransactionBehavior::Immediate)
4278 .expect("Failed to create first transaction.");
4279
4280 let error = db2
4281 .conn
4282 .transaction_with_behavior(TransactionBehavior::Immediate)
4283 .context("Transaction begin failed.")
4284 .expect_err("This should fail.");
4285 let root_cause = error.root_cause();
4286 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4287 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4288 {
4289 return;
4290 }
4291 panic!(
4292 "Unexpected error {:?} \n{:?} \n{:?}",
4293 error,
4294 root_cause,
4295 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4296 )
4297 }
4298
4299 #[cfg(disabled)]
4300 #[test]
4301 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4302 let temp_dir = Arc::new(
4303 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4304 .expect("Failed to create temp dir."),
4305 );
4306
4307 let test_begin = Instant::now();
4308
Janis Danisevskis66784c42021-01-27 08:40:25 -08004309 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004310 let mut db =
4311 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004312 const OPEN_DB_COUNT: u32 = 50u32;
4313
4314 let mut actual_key_count = KEY_COUNT;
4315 // First insert KEY_COUNT keys.
4316 for count in 0..KEY_COUNT {
4317 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4318 actual_key_count = count;
4319 break;
4320 }
4321 let alias = format!("test_alias_{}", count);
4322 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4323 .expect("Failed to make key entry.");
4324 }
4325
4326 // Insert more keys from a different thread and into a different namespace.
4327 let temp_dir1 = temp_dir.clone();
4328 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004329 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4330 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004331
4332 for count in 0..actual_key_count {
4333 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4334 return;
4335 }
4336 let alias = format!("test_alias_{}", count);
4337 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4338 .expect("Failed to make key entry.");
4339 }
4340
4341 // then unbind them again.
4342 for count in 0..actual_key_count {
4343 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4344 return;
4345 }
4346 let key = KeyDescriptor {
4347 domain: Domain::APP,
4348 nspace: -1,
4349 alias: Some(format!("test_alias_{}", count)),
4350 blob: None,
4351 };
4352 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4353 }
4354 });
4355
4356 // And start unbinding the first set of keys.
4357 let temp_dir2 = temp_dir.clone();
4358 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004359 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4360 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004361
4362 for count in 0..actual_key_count {
4363 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4364 return;
4365 }
4366 let key = KeyDescriptor {
4367 domain: Domain::APP,
4368 nspace: -1,
4369 alias: Some(format!("test_alias_{}", count)),
4370 blob: None,
4371 };
4372 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4373 }
4374 });
4375
Janis Danisevskis66784c42021-01-27 08:40:25 -08004376 // While a lot of inserting and deleting is going on we have to open database connections
4377 // successfully and use them.
4378 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4379 // out of scope.
4380 #[allow(clippy::redundant_clone)]
4381 let temp_dir4 = temp_dir.clone();
4382 let handle4 = thread::spawn(move || {
4383 for count in 0..OPEN_DB_COUNT {
4384 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4385 return;
4386 }
Seth Moore444b51a2021-06-11 09:49:49 -07004387 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4388 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004389
4390 let alias = format!("test_alias_{}", count);
4391 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4392 .expect("Failed to make key entry.");
4393 let key = KeyDescriptor {
4394 domain: Domain::APP,
4395 nspace: -1,
4396 alias: Some(alias),
4397 blob: None,
4398 };
4399 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4400 }
4401 });
4402
4403 handle1.join().expect("Thread 1 panicked.");
4404 handle2.join().expect("Thread 2 panicked.");
4405 handle4.join().expect("Thread 4 panicked.");
4406
Janis Danisevskis66784c42021-01-27 08:40:25 -08004407 Ok(())
4408 }
4409
4410 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004411 fn list() -> Result<()> {
4412 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004413 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004414 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4415 (Domain::APP, 1, "test1"),
4416 (Domain::APP, 1, "test2"),
4417 (Domain::APP, 1, "test3"),
4418 (Domain::APP, 1, "test4"),
4419 (Domain::APP, 1, "test5"),
4420 (Domain::APP, 1, "test6"),
4421 (Domain::APP, 1, "test7"),
4422 (Domain::APP, 2, "test1"),
4423 (Domain::APP, 2, "test2"),
4424 (Domain::APP, 2, "test3"),
4425 (Domain::APP, 2, "test4"),
4426 (Domain::APP, 2, "test5"),
4427 (Domain::APP, 2, "test6"),
4428 (Domain::APP, 2, "test8"),
4429 (Domain::SELINUX, 100, "test1"),
4430 (Domain::SELINUX, 100, "test2"),
4431 (Domain::SELINUX, 100, "test3"),
4432 (Domain::SELINUX, 100, "test4"),
4433 (Domain::SELINUX, 100, "test5"),
4434 (Domain::SELINUX, 100, "test6"),
4435 (Domain::SELINUX, 100, "test9"),
4436 ];
4437
4438 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4439 .iter()
4440 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004441 let entry =
4442 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004443 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4444 });
4445 (entry.id(), *ns)
4446 })
4447 .collect();
4448
4449 for (domain, namespace) in
4450 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4451 {
4452 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4453 .iter()
4454 .filter_map(|(domain, ns, alias)| match ns {
4455 ns if *ns == *namespace => Some(KeyDescriptor {
4456 domain: *domain,
4457 nspace: *ns,
4458 alias: Some(alias.to_string()),
4459 blob: None,
4460 }),
4461 _ => None,
4462 })
4463 .collect();
4464 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004465 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004466 list_result.sort();
4467 assert_eq!(list_o_descriptors, list_result);
4468
4469 let mut list_o_ids: Vec<i64> = list_o_descriptors
4470 .into_iter()
4471 .map(|d| {
4472 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004473 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004474 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004475 KeyType::Client,
4476 KeyEntryLoadBits::NONE,
4477 *namespace as u32,
4478 |_, _| Ok(()),
4479 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004480 .unwrap();
4481 entry.id()
4482 })
4483 .collect();
4484 list_o_ids.sort_unstable();
4485 let mut loaded_entries: Vec<i64> = list_o_keys
4486 .iter()
4487 .filter_map(|(id, ns)| match ns {
4488 ns if *ns == *namespace => Some(*id),
4489 _ => None,
4490 })
4491 .collect();
4492 loaded_entries.sort_unstable();
4493 assert_eq!(list_o_ids, loaded_entries);
4494 }
Eran Messeri24f31972023-01-25 17:00:33 +00004495 assert_eq!(
4496 Vec::<KeyDescriptor>::new(),
4497 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4498 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004499
4500 Ok(())
4501 }
4502
Joel Galenson0891bc12020-07-20 10:37:03 -07004503 // Helpers
4504
4505 // Checks that the given result is an error containing the given string.
4506 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4507 let error_str = format!(
4508 "{:#?}",
4509 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4510 );
4511 assert!(
4512 error_str.contains(target),
4513 "The string \"{}\" should contain \"{}\"",
4514 error_str,
4515 target
4516 );
4517 }
4518
Joel Galenson2aab4432020-07-22 15:27:57 -07004519 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004520 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004521 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004522 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004523 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004524 namespace: Option<i64>,
4525 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004526 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004527 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004528 }
4529
4530 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4531 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004532 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004533 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004534 Ok(KeyEntryRow {
4535 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004536 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004537 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004538 namespace: row.get(3)?,
4539 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004540 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004541 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004542 })
4543 })?
4544 .map(|r| r.context("Could not read keyentry row."))
4545 .collect::<Result<Vec<_>>>()
4546 }
4547
Eran Messeri4dc27b52024-01-09 12:43:31 +00004548 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4549 make_test_params_with_sids(max_usage_count, &[42])
4550 }
4551
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004552 // Note: The parameters and SecurityLevel associations are nonsensical. This
4553 // collection is only used to check if the parameters are preserved as expected by the
4554 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004555 fn make_test_params_with_sids(
4556 max_usage_count: Option<i32>,
4557 user_secure_ids: &[i64],
4558 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004559 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004560 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4561 KeyParameter::new(
4562 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4563 SecurityLevel::TRUSTED_ENVIRONMENT,
4564 ),
4565 KeyParameter::new(
4566 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4567 SecurityLevel::TRUSTED_ENVIRONMENT,
4568 ),
4569 KeyParameter::new(
4570 KeyParameterValue::Algorithm(Algorithm::RSA),
4571 SecurityLevel::TRUSTED_ENVIRONMENT,
4572 ),
4573 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4574 KeyParameter::new(
4575 KeyParameterValue::BlockMode(BlockMode::ECB),
4576 SecurityLevel::TRUSTED_ENVIRONMENT,
4577 ),
4578 KeyParameter::new(
4579 KeyParameterValue::BlockMode(BlockMode::GCM),
4580 SecurityLevel::TRUSTED_ENVIRONMENT,
4581 ),
4582 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4583 KeyParameter::new(
4584 KeyParameterValue::Digest(Digest::MD5),
4585 SecurityLevel::TRUSTED_ENVIRONMENT,
4586 ),
4587 KeyParameter::new(
4588 KeyParameterValue::Digest(Digest::SHA_2_224),
4589 SecurityLevel::TRUSTED_ENVIRONMENT,
4590 ),
4591 KeyParameter::new(
4592 KeyParameterValue::Digest(Digest::SHA_2_256),
4593 SecurityLevel::STRONGBOX,
4594 ),
4595 KeyParameter::new(
4596 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4597 SecurityLevel::TRUSTED_ENVIRONMENT,
4598 ),
4599 KeyParameter::new(
4600 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4601 SecurityLevel::TRUSTED_ENVIRONMENT,
4602 ),
4603 KeyParameter::new(
4604 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4605 SecurityLevel::STRONGBOX,
4606 ),
4607 KeyParameter::new(
4608 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4609 SecurityLevel::TRUSTED_ENVIRONMENT,
4610 ),
4611 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4612 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4613 KeyParameter::new(
4614 KeyParameterValue::EcCurve(EcCurve::P_224),
4615 SecurityLevel::TRUSTED_ENVIRONMENT,
4616 ),
4617 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4618 KeyParameter::new(
4619 KeyParameterValue::EcCurve(EcCurve::P_384),
4620 SecurityLevel::TRUSTED_ENVIRONMENT,
4621 ),
4622 KeyParameter::new(
4623 KeyParameterValue::EcCurve(EcCurve::P_521),
4624 SecurityLevel::TRUSTED_ENVIRONMENT,
4625 ),
4626 KeyParameter::new(
4627 KeyParameterValue::RSAPublicExponent(3),
4628 SecurityLevel::TRUSTED_ENVIRONMENT,
4629 ),
4630 KeyParameter::new(
4631 KeyParameterValue::IncludeUniqueID,
4632 SecurityLevel::TRUSTED_ENVIRONMENT,
4633 ),
4634 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4635 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4636 KeyParameter::new(
4637 KeyParameterValue::ActiveDateTime(1234567890),
4638 SecurityLevel::STRONGBOX,
4639 ),
4640 KeyParameter::new(
4641 KeyParameterValue::OriginationExpireDateTime(1234567890),
4642 SecurityLevel::TRUSTED_ENVIRONMENT,
4643 ),
4644 KeyParameter::new(
4645 KeyParameterValue::UsageExpireDateTime(1234567890),
4646 SecurityLevel::TRUSTED_ENVIRONMENT,
4647 ),
4648 KeyParameter::new(
4649 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4650 SecurityLevel::TRUSTED_ENVIRONMENT,
4651 ),
4652 KeyParameter::new(
4653 KeyParameterValue::MaxUsesPerBoot(1234567890),
4654 SecurityLevel::TRUSTED_ENVIRONMENT,
4655 ),
4656 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004657 KeyParameter::new(
4658 KeyParameterValue::NoAuthRequired,
4659 SecurityLevel::TRUSTED_ENVIRONMENT,
4660 ),
4661 KeyParameter::new(
4662 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4663 SecurityLevel::TRUSTED_ENVIRONMENT,
4664 ),
4665 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4666 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4667 KeyParameter::new(
4668 KeyParameterValue::TrustedUserPresenceRequired,
4669 SecurityLevel::TRUSTED_ENVIRONMENT,
4670 ),
4671 KeyParameter::new(
4672 KeyParameterValue::TrustedConfirmationRequired,
4673 SecurityLevel::TRUSTED_ENVIRONMENT,
4674 ),
4675 KeyParameter::new(
4676 KeyParameterValue::UnlockedDeviceRequired,
4677 SecurityLevel::TRUSTED_ENVIRONMENT,
4678 ),
4679 KeyParameter::new(
4680 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4681 SecurityLevel::SOFTWARE,
4682 ),
4683 KeyParameter::new(
4684 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4685 SecurityLevel::SOFTWARE,
4686 ),
4687 KeyParameter::new(
4688 KeyParameterValue::CreationDateTime(12345677890),
4689 SecurityLevel::SOFTWARE,
4690 ),
4691 KeyParameter::new(
4692 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4693 SecurityLevel::TRUSTED_ENVIRONMENT,
4694 ),
4695 KeyParameter::new(
4696 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4697 SecurityLevel::TRUSTED_ENVIRONMENT,
4698 ),
4699 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4700 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4701 KeyParameter::new(
4702 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4703 SecurityLevel::SOFTWARE,
4704 ),
4705 KeyParameter::new(
4706 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4707 SecurityLevel::TRUSTED_ENVIRONMENT,
4708 ),
4709 KeyParameter::new(
4710 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4711 SecurityLevel::TRUSTED_ENVIRONMENT,
4712 ),
4713 KeyParameter::new(
4714 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4715 SecurityLevel::TRUSTED_ENVIRONMENT,
4716 ),
4717 KeyParameter::new(
4718 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4719 SecurityLevel::TRUSTED_ENVIRONMENT,
4720 ),
4721 KeyParameter::new(
4722 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4723 SecurityLevel::TRUSTED_ENVIRONMENT,
4724 ),
4725 KeyParameter::new(
4726 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4727 SecurityLevel::TRUSTED_ENVIRONMENT,
4728 ),
4729 KeyParameter::new(
4730 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4731 SecurityLevel::TRUSTED_ENVIRONMENT,
4732 ),
4733 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004734 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4735 SecurityLevel::TRUSTED_ENVIRONMENT,
4736 ),
4737 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004738 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4739 SecurityLevel::TRUSTED_ENVIRONMENT,
4740 ),
4741 KeyParameter::new(
4742 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4743 SecurityLevel::TRUSTED_ENVIRONMENT,
4744 ),
4745 KeyParameter::new(
4746 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4747 SecurityLevel::TRUSTED_ENVIRONMENT,
4748 ),
4749 KeyParameter::new(
4750 KeyParameterValue::VendorPatchLevel(3),
4751 SecurityLevel::TRUSTED_ENVIRONMENT,
4752 ),
4753 KeyParameter::new(
4754 KeyParameterValue::BootPatchLevel(4),
4755 SecurityLevel::TRUSTED_ENVIRONMENT,
4756 ),
4757 KeyParameter::new(
4758 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4759 SecurityLevel::TRUSTED_ENVIRONMENT,
4760 ),
4761 KeyParameter::new(
4762 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4763 SecurityLevel::TRUSTED_ENVIRONMENT,
4764 ),
4765 KeyParameter::new(
4766 KeyParameterValue::MacLength(256),
4767 SecurityLevel::TRUSTED_ENVIRONMENT,
4768 ),
4769 KeyParameter::new(
4770 KeyParameterValue::ResetSinceIdRotation,
4771 SecurityLevel::TRUSTED_ENVIRONMENT,
4772 ),
4773 KeyParameter::new(
4774 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4775 SecurityLevel::TRUSTED_ENVIRONMENT,
4776 ),
Qi Wub9433b52020-12-01 14:52:46 +08004777 ];
4778 if let Some(value) = max_usage_count {
4779 params.push(KeyParameter::new(
4780 KeyParameterValue::UsageCountLimit(value),
4781 SecurityLevel::SOFTWARE,
4782 ));
4783 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004784
4785 for sid in user_secure_ids.iter() {
4786 params.push(KeyParameter::new(
4787 KeyParameterValue::UserSecureID(*sid),
4788 SecurityLevel::STRONGBOX,
4789 ));
4790 }
Qi Wub9433b52020-12-01 14:52:46 +08004791 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004792 }
4793
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004794 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004795 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004796 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004797 namespace: i64,
4798 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004799 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004800 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004801 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4802 }
4803
4804 pub fn make_test_key_entry_with_sids(
4805 db: &mut KeystoreDB,
4806 domain: Domain,
4807 namespace: i64,
4808 alias: &str,
4809 max_usage_count: Option<i32>,
4810 sids: &[i64],
4811 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004812 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004813 let mut blob_metadata = BlobMetaData::new();
4814 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4815 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4816 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4817 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4818 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4819
4820 db.set_blob(
4821 &key_id,
4822 SubComponentType::KEY_BLOB,
4823 Some(TEST_KEY_BLOB),
4824 Some(&blob_metadata),
4825 )?;
4826 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4827 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004828
Eran Messeri4dc27b52024-01-09 12:43:31 +00004829 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004830 db.insert_keyparameter(&key_id, &params)?;
4831
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004832 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004833 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004834 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004835 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004836 Ok(key_id)
4837 }
4838
Qi Wub9433b52020-12-01 14:52:46 +08004839 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4840 let params = make_test_params(max_usage_count);
4841
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004842 let mut blob_metadata = BlobMetaData::new();
4843 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4844 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4845 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4846 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4847 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4848
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004849 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004850 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004851
4852 KeyEntry {
4853 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004854 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004855 cert: Some(TEST_CERT_BLOB.to_vec()),
4856 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004857 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004858 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004859 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004860 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004861 }
4862 }
4863
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004864 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004865 db: &mut KeystoreDB,
4866 domain: Domain,
4867 namespace: i64,
4868 alias: &str,
4869 logical_only: bool,
4870 ) -> Result<KeyIdGuard> {
4871 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4872 let mut blob_metadata = BlobMetaData::new();
4873 if !logical_only {
4874 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4875 }
4876 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4877
4878 db.set_blob(
4879 &key_id,
4880 SubComponentType::KEY_BLOB,
4881 Some(TEST_KEY_BLOB),
4882 Some(&blob_metadata),
4883 )?;
4884 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4885 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4886
4887 let mut params = make_test_params(None);
4888 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4889
4890 db.insert_keyparameter(&key_id, &params)?;
4891
4892 let mut metadata = KeyMetaData::new();
4893 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4894 db.insert_key_metadata(&key_id, &metadata)?;
4895 rebind_alias(db, &key_id, alias, domain, namespace)?;
4896 Ok(key_id)
4897 }
4898
Eric Biggersb0478cf2023-10-27 03:55:29 +00004899 // Creates an app key that is marked as being superencrypted by the given
4900 // super key ID and that has the given authentication and unlocked device
4901 // parameters. This does not actually superencrypt the key blob.
4902 fn make_superencrypted_key_entry(
4903 db: &mut KeystoreDB,
4904 namespace: i64,
4905 alias: &str,
4906 requires_authentication: bool,
4907 requires_unlocked_device: bool,
4908 super_key_id: i64,
4909 ) -> Result<KeyIdGuard> {
4910 let domain = Domain::APP;
4911 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4912
4913 let mut blob_metadata = BlobMetaData::new();
4914 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4915 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4916 db.set_blob(
4917 &key_id,
4918 SubComponentType::KEY_BLOB,
4919 Some(TEST_KEY_BLOB),
4920 Some(&blob_metadata),
4921 )?;
4922
4923 let mut params = vec![];
4924 if requires_unlocked_device {
4925 params.push(KeyParameter::new(
4926 KeyParameterValue::UnlockedDeviceRequired,
4927 SecurityLevel::TRUSTED_ENVIRONMENT,
4928 ));
4929 }
4930 if requires_authentication {
4931 params.push(KeyParameter::new(
4932 KeyParameterValue::UserSecureID(42),
4933 SecurityLevel::TRUSTED_ENVIRONMENT,
4934 ));
4935 }
4936 db.insert_keyparameter(&key_id, &params)?;
4937
4938 let mut metadata = KeyMetaData::new();
4939 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4940 db.insert_key_metadata(&key_id, &metadata)?;
4941
4942 rebind_alias(db, &key_id, alias, domain, namespace)?;
4943 Ok(key_id)
4944 }
4945
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004946 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4947 let mut params = make_test_params(None);
4948 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4949
4950 let mut blob_metadata = BlobMetaData::new();
4951 if !logical_only {
4952 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4953 }
4954 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4955
4956 let mut metadata = KeyMetaData::new();
4957 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4958
4959 KeyEntry {
4960 id: key_id,
4961 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4962 cert: Some(TEST_CERT_BLOB.to_vec()),
4963 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4964 km_uuid: KEYSTORE_UUID,
4965 parameters: params,
4966 metadata,
4967 pure_cert: false,
4968 }
4969 }
4970
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004971 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004972 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004973 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004974 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004975 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004976 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004977 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004978 Ok((
4979 row.get(0)?,
4980 row.get(1)?,
4981 row.get(2)?,
4982 row.get(3)?,
4983 row.get(4)?,
4984 row.get(5)?,
4985 row.get(6)?,
4986 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004987 },
4988 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004989
4990 println!("Key entry table rows:");
4991 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004992 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004993 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004994 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4995 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004996 );
4997 }
4998 Ok(())
4999 }
5000
5001 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005002 let mut stmt = db
5003 .conn
5004 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005005 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005006 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5007 })?;
5008
5009 println!("Grant table rows:");
5010 for r in rows {
5011 let (id, gt, ki, av) = r.unwrap();
5012 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5013 }
5014 Ok(())
5015 }
5016
Joel Galenson0891bc12020-07-20 10:37:03 -07005017 // Use a custom random number generator that repeats each number once.
5018 // This allows us to test repeated elements.
5019
5020 thread_local! {
5021 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5022 }
5023
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005024 fn reset_random() {
5025 RANDOM_COUNTER.with(|counter| {
5026 *counter.borrow_mut() = 0;
5027 })
5028 }
5029
Joel Galenson0891bc12020-07-20 10:37:03 -07005030 pub fn random() -> i64 {
5031 RANDOM_COUNTER.with(|counter| {
5032 let result = *counter.borrow() / 2;
5033 *counter.borrow_mut() += 1;
5034 result
5035 })
5036 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005037
5038 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005039 fn test_unbind_keys_for_user() -> Result<()> {
5040 let mut db = new_test_db()?;
5041 db.unbind_keys_for_user(1, false)?;
5042
5043 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5044 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5045 db.unbind_keys_for_user(2, false)?;
5046
Eran Messeri24f31972023-01-25 17:00:33 +00005047 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
5048 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005049
5050 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00005051 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005052
5053 Ok(())
5054 }
5055
5056 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005057 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5058 let mut db = new_test_db()?;
5059 let super_key = keystore2_crypto::generate_aes256_key()?;
5060 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5061 let (encrypted_super_key, metadata) =
5062 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5063
5064 let key_name_enc = SuperKeyType {
5065 alias: "test_super_key_1",
5066 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005067 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005068 };
5069
5070 let key_name_nonenc = SuperKeyType {
5071 alias: "test_super_key_2",
5072 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005073 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005074 };
5075
5076 // Install two super keys.
5077 db.store_super_key(
5078 1,
5079 &key_name_nonenc,
5080 &super_key,
5081 &BlobMetaData::new(),
5082 &KeyMetaData::new(),
5083 )?;
5084 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5085
5086 // Check that both can be found in the database.
5087 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5088 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5089
5090 // Install the same keys for a different user.
5091 db.store_super_key(
5092 2,
5093 &key_name_nonenc,
5094 &super_key,
5095 &BlobMetaData::new(),
5096 &KeyMetaData::new(),
5097 )?;
5098 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5099
5100 // Check that the second pair of keys can be found in the database.
5101 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5102 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5103
5104 // Delete only encrypted keys.
5105 db.unbind_keys_for_user(1, true)?;
5106
5107 // The encrypted superkey should be gone now.
5108 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5109 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5110
5111 // Reinsert the encrypted key.
5112 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5113
5114 // Check that both can be found in the database, again..
5115 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5116 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5117
5118 // Delete all even unencrypted keys.
5119 db.unbind_keys_for_user(1, false)?;
5120
5121 // Both should be gone now.
5122 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5123 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5124
5125 // Check that the second pair of keys was untouched.
5126 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5127 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5128
5129 Ok(())
5130 }
5131
Eric Biggersb0478cf2023-10-27 03:55:29 +00005132 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5133 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5134 }
5135
5136 // Tests the unbind_auth_bound_keys_for_user() function.
5137 #[test]
5138 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5139 let mut db = new_test_db()?;
5140 let user_id = 1;
5141 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5142 let other_user_id = 2;
5143 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5144 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5145
5146 // Create a superencryption key.
5147 let super_key = keystore2_crypto::generate_aes256_key()?;
5148 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5149 let (encrypted_super_key, blob_metadata) =
5150 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5151 db.store_super_key(
5152 user_id,
5153 super_key_type,
5154 &encrypted_super_key,
5155 &blob_metadata,
5156 &KeyMetaData::new(),
5157 )?;
5158 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5159
5160 // Store 4 superencrypted app keys, one for each possible combination of
5161 // (authentication required, unlocked device required).
5162 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5163 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5164 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5165 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5166 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5167 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5168 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5169 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5170
5171 // Also store a key for a different user that requires authentication.
5172 make_superencrypted_key_entry(
5173 &mut db,
5174 other_user_nspace,
5175 "auth_ud",
5176 true,
5177 true,
5178 super_key_id,
5179 )?;
5180
5181 db.unbind_auth_bound_keys_for_user(user_id)?;
5182
5183 // Verify that only the user's app keys that require authentication were
5184 // deleted. Keys that require an unlocked device but not authentication
5185 // should *not* have been deleted, nor should the super key have been
5186 // deleted, nor should other users' keys have been deleted.
5187 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5188 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5189 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5190 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5191 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5192 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5193
5194 Ok(())
5195 }
5196
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005197 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005198 fn test_store_super_key() -> Result<()> {
5199 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005200 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005201 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005202 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005203 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005204 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005205
5206 let (encrypted_super_key, metadata) =
5207 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005208 db.store_super_key(
5209 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005210 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005211 &encrypted_super_key,
5212 &metadata,
5213 &KeyMetaData::new(),
5214 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005215
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005216 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005217 assert!(db.key_exists(
5218 Domain::APP,
5219 1,
5220 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5221 KeyType::Super
5222 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005223
Eric Biggers673d34a2023-10-18 01:54:18 +00005224 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005225 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005226 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005227 key_entry,
5228 &pw,
5229 None,
5230 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005231
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005232 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005233 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005234
Hasini Gunasingheda895552021-01-27 19:34:37 +00005235 Ok(())
5236 }
Seth Moore78c091f2021-04-09 21:38:30 +00005237
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005238 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005239 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005240 MetricsStorage::KEY_ENTRY,
5241 MetricsStorage::KEY_ENTRY_ID_INDEX,
5242 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5243 MetricsStorage::BLOB_ENTRY,
5244 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5245 MetricsStorage::KEY_PARAMETER,
5246 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5247 MetricsStorage::KEY_METADATA,
5248 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5249 MetricsStorage::GRANT,
5250 MetricsStorage::AUTH_TOKEN,
5251 MetricsStorage::BLOB_METADATA,
5252 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005253 ]
5254 }
5255
5256 /// Perform a simple check to ensure that we can query all the storage types
5257 /// that are supported by the DB. Check for reasonable values.
5258 #[test]
5259 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005260 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005261
5262 let mut db = new_test_db()?;
5263
5264 for t in get_valid_statsd_storage_types() {
5265 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005266 // AuthToken can be less than a page since it's in a btree, not sqlite
5267 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005268 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005269 } else {
5270 assert!(stat.size >= PAGE_SIZE);
5271 }
Seth Moore78c091f2021-04-09 21:38:30 +00005272 assert!(stat.size >= stat.unused_size);
5273 }
5274
5275 Ok(())
5276 }
5277
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005278 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005279 get_valid_statsd_storage_types()
5280 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005281 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005282 .collect()
5283 }
5284
5285 fn assert_storage_increased(
5286 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005287 increased_storage_types: Vec<MetricsStorage>,
5288 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005289 ) {
5290 for storage in increased_storage_types {
5291 // Verify the expected storage increased.
5292 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005293 let old = &baseline[&storage.0];
5294 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005295 assert!(
5296 new.unused_size <= old.unused_size,
5297 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005298 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005299 new.unused_size,
5300 old.unused_size
5301 );
5302
5303 // Update the baseline with the new value so that it succeeds in the
5304 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005305 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005306 }
5307
5308 // Get an updated map of the storage and verify there were no unexpected changes.
5309 let updated_stats = get_storage_stats_map(db);
5310 assert_eq!(updated_stats.len(), baseline.len());
5311
5312 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005313 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005314 let mut s = String::new();
5315 for &k in map.keys() {
5316 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5317 .expect("string concat failed");
5318 }
5319 s
5320 };
5321
5322 assert!(
5323 updated_stats[&k].size == baseline[&k].size
5324 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5325 "updated_stats:\n{}\nbaseline:\n{}",
5326 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005327 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005328 );
5329 }
5330 }
5331
5332 #[test]
5333 fn test_verify_key_table_size_reporting() -> Result<()> {
5334 let mut db = new_test_db()?;
5335 let mut working_stats = get_storage_stats_map(&mut db);
5336
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005337 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005338 assert_storage_increased(
5339 &mut db,
5340 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005341 MetricsStorage::KEY_ENTRY,
5342 MetricsStorage::KEY_ENTRY_ID_INDEX,
5343 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005344 ],
5345 &mut working_stats,
5346 );
5347
5348 let mut blob_metadata = BlobMetaData::new();
5349 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5350 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5351 assert_storage_increased(
5352 &mut db,
5353 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005354 MetricsStorage::BLOB_ENTRY,
5355 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5356 MetricsStorage::BLOB_METADATA,
5357 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005358 ],
5359 &mut working_stats,
5360 );
5361
5362 let params = make_test_params(None);
5363 db.insert_keyparameter(&key_id, &params)?;
5364 assert_storage_increased(
5365 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005366 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005367 &mut working_stats,
5368 );
5369
5370 let mut metadata = KeyMetaData::new();
5371 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5372 db.insert_key_metadata(&key_id, &metadata)?;
5373 assert_storage_increased(
5374 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005375 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005376 &mut working_stats,
5377 );
5378
5379 let mut sum = 0;
5380 for stat in working_stats.values() {
5381 sum += stat.size;
5382 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005383 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005384 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5385
5386 Ok(())
5387 }
5388
5389 #[test]
5390 fn test_verify_auth_table_size_reporting() -> Result<()> {
5391 let mut db = new_test_db()?;
5392 let mut working_stats = get_storage_stats_map(&mut db);
5393 db.insert_auth_token(&HardwareAuthToken {
5394 challenge: 123,
5395 userId: 456,
5396 authenticatorId: 789,
5397 authenticatorType: kmhw_authenticator_type::ANY,
5398 timestamp: Timestamp { milliSeconds: 10 },
5399 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005400 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005401 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005402 Ok(())
5403 }
5404
5405 #[test]
5406 fn test_verify_grant_table_size_reporting() -> Result<()> {
5407 const OWNER: i64 = 1;
5408 let mut db = new_test_db()?;
5409 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5410
5411 let mut working_stats = get_storage_stats_map(&mut db);
5412 db.grant(
5413 &KeyDescriptor {
5414 domain: Domain::APP,
5415 nspace: 0,
5416 alias: Some(TEST_ALIAS.to_string()),
5417 blob: None,
5418 },
5419 OWNER as u32,
5420 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005421 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005422 |_, _| Ok(()),
5423 )?;
5424
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005425 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005426
5427 Ok(())
5428 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005429
5430 #[test]
5431 fn find_auth_token_entry_returns_latest() -> Result<()> {
5432 let mut db = new_test_db()?;
5433 db.insert_auth_token(&HardwareAuthToken {
5434 challenge: 123,
5435 userId: 456,
5436 authenticatorId: 789,
5437 authenticatorType: kmhw_authenticator_type::ANY,
5438 timestamp: Timestamp { milliSeconds: 10 },
5439 mac: b"mac0".to_vec(),
5440 });
5441 std::thread::sleep(std::time::Duration::from_millis(1));
5442 db.insert_auth_token(&HardwareAuthToken {
5443 challenge: 123,
5444 userId: 457,
5445 authenticatorId: 789,
5446 authenticatorType: kmhw_authenticator_type::ANY,
5447 timestamp: Timestamp { milliSeconds: 12 },
5448 mac: b"mac1".to_vec(),
5449 });
5450 std::thread::sleep(std::time::Duration::from_millis(1));
5451 db.insert_auth_token(&HardwareAuthToken {
5452 challenge: 123,
5453 userId: 458,
5454 authenticatorId: 789,
5455 authenticatorType: kmhw_authenticator_type::ANY,
5456 timestamp: Timestamp { milliSeconds: 3 },
5457 mac: b"mac2".to_vec(),
5458 });
5459 // All three entries are in the database
5460 assert_eq!(db.perboot.auth_tokens_len(), 3);
5461 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005462 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005463 Ok(())
5464 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005465
5466 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005467 fn test_load_key_descriptor() -> Result<()> {
5468 let mut db = new_test_db()?;
5469 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5470
5471 let key = db.load_key_descriptor(key_id)?.unwrap();
5472
5473 assert_eq!(key.domain, Domain::APP);
5474 assert_eq!(key.nspace, 1);
5475 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5476
5477 // No such id
5478 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5479 Ok(())
5480 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005481
5482 #[test]
5483 fn test_get_list_app_uids_for_sid() -> Result<()> {
5484 let uid: i32 = 1;
5485 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5486 let first_sid = 667;
5487 let second_sid = 669;
5488 let first_app_id: i64 = 123 + uid_offset;
5489 let second_app_id: i64 = 456 + uid_offset;
5490 let third_app_id: i64 = 789 + uid_offset;
5491 let unrelated_app_id: i64 = 1011 + uid_offset;
5492 let mut db = new_test_db()?;
5493 make_test_key_entry_with_sids(
5494 &mut db,
5495 Domain::APP,
5496 first_app_id,
5497 TEST_ALIAS,
5498 None,
5499 &[first_sid],
5500 )
5501 .context("test_get_list_app_uids_for_sid")?;
5502 make_test_key_entry_with_sids(
5503 &mut db,
5504 Domain::APP,
5505 second_app_id,
5506 "alias2",
5507 None,
5508 &[first_sid],
5509 )
5510 .context("test_get_list_app_uids_for_sid")?;
5511 make_test_key_entry_with_sids(
5512 &mut db,
5513 Domain::APP,
5514 second_app_id,
5515 TEST_ALIAS,
5516 None,
5517 &[second_sid],
5518 )
5519 .context("test_get_list_app_uids_for_sid")?;
5520 make_test_key_entry_with_sids(
5521 &mut db,
5522 Domain::APP,
5523 third_app_id,
5524 "alias3",
5525 None,
5526 &[second_sid],
5527 )
5528 .context("test_get_list_app_uids_for_sid")?;
5529 make_test_key_entry_with_sids(
5530 &mut db,
5531 Domain::APP,
5532 unrelated_app_id,
5533 TEST_ALIAS,
5534 None,
5535 &[],
5536 )
5537 .context("test_get_list_app_uids_for_sid")?;
5538
5539 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5540 first_sid_apps.sort();
5541 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5542 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5543 second_sid_apps.sort();
5544 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5545 Ok(())
5546 }
5547
5548 #[test]
5549 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5550 let uid: i32 = 1;
5551 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5552 let first_sid = 667;
5553 let second_sid = 669;
5554 let third_sid = 772;
5555 let first_app_id: i64 = 123 + uid_offset;
5556 let second_app_id: i64 = 456 + uid_offset;
5557 let mut db = new_test_db()?;
5558 make_test_key_entry_with_sids(
5559 &mut db,
5560 Domain::APP,
5561 first_app_id,
5562 TEST_ALIAS,
5563 None,
5564 &[first_sid, second_sid],
5565 )
5566 .context("test_get_list_app_uids_for_sid")?;
5567 make_test_key_entry_with_sids(
5568 &mut db,
5569 Domain::APP,
5570 second_app_id,
5571 "alias2",
5572 None,
5573 &[second_sid, third_sid],
5574 )
5575 .context("test_get_list_app_uids_for_sid")?;
5576
5577 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5578 assert_eq!(first_sid_apps, vec![first_app_id]);
5579
5580 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5581 second_sid_apps.sort();
5582 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5583
5584 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5585 assert_eq!(third_sid_apps, vec![second_app_id]);
5586 Ok(())
5587 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005588}