blob: 0a1c54712bdefe16e7738613a495d645c01baec1 [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
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000764/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000765#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
766pub struct MonotonicRawTime(i64);
767
768impl MonotonicRawTime {
769 /// Constructs a new MonotonicRawTime
770 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
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000774 /// Returns the value of MonotonicRawTime in milliseconds as i64
775 pub fn milliseconds(&self) -> i64 {
776 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000777 }
778
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000779 /// Returns the integer value of MonotonicRawTime as i64
780 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
790impl ToSql for MonotonicRawTime {
791 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
792 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
793 }
794}
795
796impl FromSql for MonotonicRawTime {
797 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
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000808 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000809}
810
811impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000812 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> 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.
835 pub fn time_received(&self) -> MonotonicRawTime {
836 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 )
1170 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001171 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1172 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001173 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001174
1175 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1176
Janis Danisevskis3395f862021-05-06 10:54:17 -07001177 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1178 let result: Vec<(i64, Vec<u8>)> = {
1179 let mut stmt = tx
1180 .prepare(
1181 "SELECT id, blob FROM persistent.blobentry
1182 WHERE subcomponent_type = ?
1183 AND (
1184 id NOT IN (
1185 SELECT MAX(id) FROM persistent.blobentry
1186 WHERE subcomponent_type = ?
1187 GROUP BY keyentryid, subcomponent_type
1188 )
1189 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1190 ) LIMIT ?;",
1191 )
1192 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001193
Janis Danisevskis3395f862021-05-06 10:54:17 -07001194 let rows = stmt
1195 .query_map(
1196 params![
1197 SubComponentType::KEY_BLOB,
1198 SubComponentType::KEY_BLOB,
1199 max_blobs as i64,
1200 ],
1201 |row| Ok((row.get(0)?, row.get(1)?)),
1202 )
1203 .context("Trying to query superseded blob.")?;
1204
1205 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1206 .context("Trying to extract superseded blobs.")?
1207 };
1208
1209 let result = result
1210 .into_iter()
1211 .map(|(blob_id, blob)| {
1212 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1213 })
1214 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1215 .context("Trying to load blob metadata.")?;
1216 if !result.is_empty() {
1217 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001218 }
1219
1220 // We did not find any superseded key blob, so let's remove other superseded blob in
1221 // one transaction.
1222 tx.execute(
1223 "DELETE FROM persistent.blobentry
1224 WHERE NOT subcomponent_type = ?
1225 AND (
1226 id NOT IN (
1227 SELECT MAX(id) FROM persistent.blobentry
1228 WHERE NOT subcomponent_type = ?
1229 GROUP BY keyentryid, subcomponent_type
1230 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1231 );",
1232 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1233 )
1234 .context("Trying to purge superseded blobs.")?;
1235
Janis Danisevskis3395f862021-05-06 10:54:17 -07001236 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001237 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001238 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001239 }
1240
1241 /// This maintenance function should be called only once before the database is used for the
1242 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1243 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1244 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1245 /// Keystore crashed at some point during key generation. Callers may want to log such
1246 /// occurrences.
1247 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1248 /// it to `KeyLifeCycle::Live` may have grants.
1249 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001250 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1251
Janis Danisevskis66784c42021-01-27 08:40:25 -08001252 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1253 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001254 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1255 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1256 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001257 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001258 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001259 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001260 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001261 }
1262
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001263 /// Checks if a key exists with given key type and key descriptor properties.
1264 pub fn key_exists(
1265 &mut self,
1266 domain: Domain,
1267 nspace: i64,
1268 alias: &str,
1269 key_type: KeyType,
1270 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001271 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1272
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001273 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1274 let key_descriptor =
1275 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001276 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001277 match result {
1278 Ok(_) => Ok(true),
1279 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1280 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001281 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001282 },
1283 }
1284 .no_gc()
1285 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001286 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001287 }
1288
Hasini Gunasingheda895552021-01-27 19:34:37 +00001289 /// Stores a super key in the database.
1290 pub fn store_super_key(
1291 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001292 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001293 key_type: &SuperKeyType,
1294 blob: &[u8],
1295 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001296 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001297 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001298 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1299
Hasini Gunasingheda895552021-01-27 19:34:37 +00001300 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1301 let key_id = Self::insert_with_retry(|id| {
1302 tx.execute(
1303 "INSERT into persistent.keyentry
1304 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001305 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001306 params![
1307 id,
1308 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001309 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001310 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001311 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001312 KeyLifeCycle::Live,
1313 &KEYSTORE_UUID,
1314 ],
1315 )
1316 })
1317 .context("Failed to insert into keyentry table.")?;
1318
Paul Crowley8d5b2532021-03-19 10:53:07 -07001319 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1320
Hasini Gunasingheda895552021-01-27 19:34:37 +00001321 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001322 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001323 key_id,
1324 SubComponentType::KEY_BLOB,
1325 Some(blob),
1326 Some(blob_metadata),
1327 )
1328 .context("Failed to store key blob.")?;
1329
1330 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1331 .context("Trying to load key components.")
1332 .no_gc()
1333 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001334 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001335 }
1336
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001337 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001338 pub fn load_super_key(
1339 &mut self,
1340 key_type: &SuperKeyType,
1341 user_id: u32,
1342 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001343 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1344
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001345 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1346 let key_descriptor = KeyDescriptor {
1347 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001348 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001349 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001350 blob: None,
1351 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001352 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001353 match id {
1354 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001355 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001356 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001357 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1358 }
1359 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1360 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001361 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001362 },
1363 }
1364 .no_gc()
1365 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001366 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001367 }
1368
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001369 /// Atomically loads a key entry and associated metadata or creates it using the
1370 /// callback create_new_key callback. The callback is called during a database
1371 /// transaction. This means that implementers should be mindful about using
1372 /// blocking operations such as IPC or grabbing mutexes.
1373 pub fn get_or_create_key_with<F>(
1374 &mut self,
1375 domain: Domain,
1376 namespace: i64,
1377 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001378 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001379 create_new_key: F,
1380 ) -> Result<(KeyIdGuard, KeyEntry)>
1381 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001382 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001383 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001384 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1385
Janis Danisevskis66784c42021-01-27 08:40:25 -08001386 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1387 let id = {
1388 let mut stmt = tx
1389 .prepare(
1390 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001391 WHERE
1392 key_type = ?
1393 AND domain = ?
1394 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001395 AND alias = ?
1396 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001398 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001399 let mut rows = stmt
1400 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001401 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001402
Janis Danisevskis66784c42021-01-27 08:40:25 -08001403 db_utils::with_rows_extract_one(&mut rows, |row| {
1404 Ok(match row {
1405 Some(r) => r.get(0).context("Failed to unpack id.")?,
1406 None => None,
1407 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001408 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001409 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001410 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001411
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 let (id, entry) = match id {
1413 Some(id) => (
1414 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001415 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001417
Janis Danisevskis66784c42021-01-27 08:40:25 -08001418 None => {
1419 let id = Self::insert_with_retry(|id| {
1420 tx.execute(
1421 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001422 (id, key_type, domain, namespace, alias, state, km_uuid)
1423 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 params![
1425 id,
1426 KeyType::Super,
1427 domain.0,
1428 namespace,
1429 alias,
1430 KeyLifeCycle::Live,
1431 km_uuid,
1432 ],
1433 )
1434 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001435 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001436
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001437 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001438 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001439 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001440 id,
1441 SubComponentType::KEY_BLOB,
1442 Some(&blob),
1443 Some(&metadata),
1444 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001445 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001446 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001447 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001448 KeyEntry {
1449 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001450 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001451 pure_cert: false,
1452 ..Default::default()
1453 },
1454 )
1455 }
1456 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001457 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001458 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001459 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001460 }
1461
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001462 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001463 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1464 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001465 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1466 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001467 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001468 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001469 loop {
1470 match self
1471 .conn
1472 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001473 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001474 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1475 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001476 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001477 Ok(result)
1478 }) {
1479 Ok(result) => break Ok(result),
1480 Err(e) => {
1481 if Self::is_locked_error(&e) {
1482 std::thread::sleep(std::time::Duration::from_micros(500));
1483 continue;
1484 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001485 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001486 }
1487 }
1488 }
1489 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001490 .map(|(need_gc, result)| {
1491 if need_gc {
1492 if let Some(ref gc) = self.gc {
1493 gc.notify_gc();
1494 }
1495 }
1496 result
1497 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001498 }
1499
1500 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001501 matches!(
1502 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1503 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1504 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1505 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001506 }
1507
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001508 /// Creates a new key entry and allocates a new randomized id for the new key.
1509 /// The key id gets associated with a domain and namespace but not with an alias.
1510 /// To complete key generation `rebind_alias` should be called after all of the
1511 /// key artifacts, i.e., blobs and parameters have been associated with the new
1512 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1513 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001514 pub fn create_key_entry(
1515 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001516 domain: &Domain,
1517 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001518 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001519 km_uuid: &Uuid,
1520 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001521 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1522
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001523 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001524 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001526 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001527 }
1528
1529 fn create_key_entry_internal(
1530 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001531 domain: &Domain,
1532 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001533 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001534 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001535 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001536 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001537 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001538 _ => {
1539 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001540 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001541 }
1542 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001543 Ok(KEY_ID_LOCK.get(
1544 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001545 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001546 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001547 (id, key_type, domain, namespace, alias, state, km_uuid)
1548 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 params![
1550 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001551 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001553 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001554 KeyLifeCycle::Existing,
1555 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001556 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001557 )
1558 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001559 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001560 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001561 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001562
Janis Danisevskis377d1002021-01-27 19:07:48 -08001563 /// Set a new blob and associates it with the given key id. Each blob
1564 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001565 /// Each key can have one of each sub component type associated. If more
1566 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001567 /// will get garbage collected.
1568 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1569 /// removed by setting blob to None.
1570 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001571 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001572 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001573 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001574 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001575 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001576 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001577 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1578
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001579 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001580 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001581 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001582 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001583 }
1584
Janis Danisevskiseed69842021-02-18 20:04:10 -08001585 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1586 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1587 /// We use this to insert key blobs into the database which can then be garbage collected
1588 /// lazily by the key garbage collector.
1589 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001590 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1591
Janis Danisevskiseed69842021-02-18 20:04:10 -08001592 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1593 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001594 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001595 Self::UNASSIGNED_KEY_ID,
1596 SubComponentType::KEY_BLOB,
1597 Some(blob),
1598 Some(blob_metadata),
1599 )
1600 .need_gc()
1601 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001602 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001603 }
1604
Janis Danisevskis377d1002021-01-27 19:07:48 -08001605 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001606 tx: &Transaction,
1607 key_id: i64,
1608 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001609 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001610 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001611 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001612 match (blob, sc_type) {
1613 (Some(blob), _) => {
1614 tx.execute(
1615 "INSERT INTO persistent.blobentry
1616 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1617 params![sc_type, key_id, blob],
1618 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001619 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001620 if let Some(blob_metadata) = blob_metadata {
1621 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001622 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001623 row.get(0)
1624 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001625 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 blob_metadata
1627 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001628 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001629 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001630 }
1631 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1632 tx.execute(
1633 "DELETE FROM persistent.blobentry
1634 WHERE subcomponent_type = ? AND keyentryid = ?;",
1635 params![sc_type, key_id],
1636 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001637 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001638 }
1639 (None, _) => {
1640 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001641 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001642 }
1643 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001644 Ok(())
1645 }
1646
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001647 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1648 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001649 #[cfg(test)]
1650 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001651 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001652 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001653 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001654 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001655 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001656
Janis Danisevskis66784c42021-01-27 08:40:25 -08001657 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001658 tx: &Transaction,
1659 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001660 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001661 ) -> Result<()> {
1662 let mut stmt = tx
1663 .prepare(
1664 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1665 VALUES (?, ?, ?, ?);",
1666 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001667 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001668
Janis Danisevskis66784c42021-01-27 08:40:25 -08001669 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001670 stmt.insert(params![
1671 key_id.0,
1672 p.get_tag().0,
1673 p.key_parameter_value(),
1674 p.security_level().0
1675 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001676 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001677 }
1678 Ok(())
1679 }
1680
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001681 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001682 #[cfg(test)]
1683 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001684 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001685 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001686 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001687 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001688 }
1689
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001690 /// Updates the alias column of the given key id `newid` with the given alias,
1691 /// and atomically, removes the alias, domain, and namespace from another row
1692 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001693 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1694 /// collector.
1695 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001696 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001697 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001698 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001699 domain: &Domain,
1700 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001701 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001702 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001703 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001704 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001705 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001706 return Err(KsError::sys())
1707 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001708 }
1709 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001710 let updated = tx
1711 .execute(
1712 "UPDATE persistent.keyentry
1713 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001714 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1715 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001716 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001717 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001718 let result = tx
1719 .execute(
1720 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001721 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001722 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001723 params![
1724 alias,
1725 KeyLifeCycle::Live,
1726 newid.0,
1727 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001728 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001729 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001730 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001731 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001732 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001733 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001734 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001735 return Err(KsError::sys()).context(ks_err!(
1736 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001737 result
1738 ));
1739 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001740 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001741 }
1742
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001743 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1744 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1745 pub fn migrate_key_namespace(
1746 &mut self,
1747 key_id_guard: KeyIdGuard,
1748 destination: &KeyDescriptor,
1749 caller_uid: u32,
1750 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1751 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001752 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1753
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001754 let destination = match destination.domain {
1755 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1756 Domain::SELINUX => (*destination).clone(),
1757 domain => {
1758 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1759 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1760 }
1761 };
1762
1763 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001764 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001765
1766 let alias = destination
1767 .alias
1768 .as_ref()
1769 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001770 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001771
1772 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1773 // Query the destination location. If there is a key, the migration request fails.
1774 if tx
1775 .query_row(
1776 "SELECT id FROM persistent.keyentry
1777 WHERE alias = ? AND domain = ? AND namespace = ?;",
1778 params![alias, destination.domain.0, destination.nspace],
1779 |_| Ok(()),
1780 )
1781 .optional()
1782 .context("Failed to query destination.")?
1783 .is_some()
1784 {
1785 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1786 .context("Target already exists.");
1787 }
1788
1789 let updated = tx
1790 .execute(
1791 "UPDATE persistent.keyentry
1792 SET alias = ?, domain = ?, namespace = ?
1793 WHERE id = ?;",
1794 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1795 )
1796 .context("Failed to update key entry.")?;
1797
1798 if updated != 1 {
1799 return Err(KsError::sys())
1800 .context(format!("Update succeeded, but {} rows were updated.", updated));
1801 }
1802 Ok(()).no_gc()
1803 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001804 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001805 }
1806
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001807 /// Store a new key in a single transaction.
1808 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1809 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001810 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1811 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001812 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001813 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001814 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001815 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001816 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001817 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001818 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001819 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001820 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001821 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001822 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001823 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1824
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001825 let (alias, domain, namespace) = match key {
1826 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1827 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1828 (alias, key.domain, nspace)
1829 }
1830 _ => {
1831 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001832 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001833 }
1834 };
1835 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001836 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001837 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001838 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1839
1840 // In some occasions the key blob is already upgraded during the import.
1841 // In order to make sure it gets properly deleted it is inserted into the
1842 // database here and then immediately replaced by the superseding blob.
1843 // The garbage collector will then subject the blob to deleteKey of the
1844 // KM back end to permanently invalidate the key.
1845 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1846 Self::set_blob_internal(
1847 tx,
1848 key_id.id(),
1849 SubComponentType::KEY_BLOB,
1850 Some(blob),
1851 Some(blob_metadata),
1852 )
1853 .context("Trying to insert superseded key blob.")?;
1854 true
1855 } else {
1856 false
1857 };
1858
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001859 Self::set_blob_internal(
1860 tx,
1861 key_id.id(),
1862 SubComponentType::KEY_BLOB,
1863 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001864 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001865 )
1866 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001867 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001868 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001869 .context("Trying to insert the certificate.")?;
1870 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001871 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001872 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001873 tx,
1874 key_id.id(),
1875 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001876 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001877 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001878 )
1879 .context("Trying to insert the certificate chain.")?;
1880 }
1881 Self::insert_keyparameter_internal(tx, &key_id, params)
1882 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001883 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001884 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001885 .context("Trying to rebind alias.")?
1886 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001887 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001888 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001889 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001890 }
1891
Janis Danisevskis377d1002021-01-27 19:07:48 -08001892 /// Store a new certificate
1893 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1894 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001895 pub fn store_new_certificate(
1896 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001897 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001898 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001899 cert: &[u8],
1900 km_uuid: &Uuid,
1901 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001902 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1903
Janis Danisevskis377d1002021-01-27 19:07:48 -08001904 let (alias, domain, namespace) = match key {
1905 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1906 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1907 (alias, key.domain, nspace)
1908 }
1909 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001910 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1911 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001912 }
1913 };
1914 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001915 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001916 .context("Trying to create new key entry.")?;
1917
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001918 Self::set_blob_internal(
1919 tx,
1920 key_id.id(),
1921 SubComponentType::CERT_CHAIN,
1922 Some(cert),
1923 None,
1924 )
1925 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001926
1927 let mut metadata = KeyMetaData::new();
1928 metadata.add(KeyMetaEntry::CreationDate(
1929 DateTime::now().context("Trying to make creation time.")?,
1930 ));
1931
1932 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1933
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001934 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001935 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001936 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001937 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001938 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001939 }
1940
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001941 // Helper function loading the key_id given the key descriptor
1942 // tuple comprising domain, namespace, and alias.
1943 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001944 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001945 let alias = key
1946 .alias
1947 .as_ref()
1948 .map_or_else(|| Err(KsError::sys()), Ok)
1949 .context("In load_key_entry_id: Alias must be specified.")?;
1950 let mut stmt = tx
1951 .prepare(
1952 "SELECT id FROM persistent.keyentry
1953 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001954 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001955 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001956 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001957 AND alias = ?
1958 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001959 )
1960 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1961 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001962 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001963 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001964 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001965 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001966 .get(0)
1967 .context("Failed to unpack id.")
1968 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001969 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001970 }
1971
1972 /// This helper function completes the access tuple of a key, which is required
1973 /// to perform access control. The strategy depends on the `domain` field in the
1974 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001975 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001976 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001977 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001978 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001979 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001980 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001981 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001982 /// `namespace`.
1983 /// In each case the information returned is sufficient to perform the access
1984 /// check and the key id can be used to load further key artifacts.
1985 fn load_access_tuple(
1986 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001987 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001988 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001989 caller_uid: u32,
1990 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1991 match key.domain {
1992 // Domain App or SELinux. In this case we load the key_id from
1993 // the keyentry database for further loading of key components.
1994 // We already have the full access tuple to perform access control.
1995 // The only distinction is that we use the caller_uid instead
1996 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001997 // Domain::APP.
1998 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001999 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002000 if access_key.domain == Domain::APP {
2001 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002002 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002003 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002004 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002005
2006 Ok((key_id, access_key, None))
2007 }
2008
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002009 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002010 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002011 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002012 let mut stmt = tx
2013 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002014 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002015 WHERE grantee = ? AND id = ? AND
2016 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002017 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002018 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002019 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002020 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002021 .context("Domain:Grant: query failed.")?;
2022 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002023 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002024 let r =
2025 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002026 Ok((
2027 r.get(0).context("Failed to unpack key_id.")?,
2028 r.get(1).context("Failed to unpack access_vector.")?,
2029 ))
2030 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002031 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002032 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002033 }
2034
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002035 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002036 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002037 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002038 let (domain, namespace): (Domain, i64) = {
2039 let mut stmt = tx
2040 .prepare(
2041 "SELECT domain, namespace FROM persistent.keyentry
2042 WHERE
2043 id = ?
2044 AND state = ?;",
2045 )
2046 .context("Domain::KEY_ID: prepare statement failed")?;
2047 let mut rows = stmt
2048 .query(params![key.nspace, KeyLifeCycle::Live])
2049 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002050 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002051 let r =
2052 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002053 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002054 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002055 r.get(1).context("Failed to unpack namespace.")?,
2056 ))
2057 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002058 .context("Domain::KEY_ID.")?
2059 };
2060
2061 // We may use a key by id after loading it by grant.
2062 // In this case we have to check if the caller has a grant for this particular
2063 // key. We can skip this if we already know that the caller is the owner.
2064 // But we cannot know this if domain is anything but App. E.g. in the case
2065 // of Domain::SELINUX we have to speculatively check for grants because we have to
2066 // consult the SEPolicy before we know if the caller is the owner.
2067 let access_vector: Option<KeyPermSet> =
2068 if domain != Domain::APP || namespace != caller_uid as i64 {
2069 let access_vector: Option<i32> = tx
2070 .query_row(
2071 "SELECT access_vector FROM persistent.grant
2072 WHERE grantee = ? AND keyentryid = ?;",
2073 params![caller_uid as i64, key.nspace],
2074 |row| row.get(0),
2075 )
2076 .optional()
2077 .context("Domain::KEY_ID: query grant failed.")?;
2078 access_vector.map(|p| p.into())
2079 } else {
2080 None
2081 };
2082
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002083 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002084 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002085 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002086 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002087
Janis Danisevskis45760022021-01-19 16:34:10 -08002088 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002089 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002090 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002091 }
2092 }
2093
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002094 fn load_blob_components(
2095 key_id: i64,
2096 load_bits: KeyEntryLoadBits,
2097 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002098 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002099 let mut stmt = tx
2100 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002102 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2103 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002104 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002105
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002106 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002107
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002108 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002109 let mut cert_blob: Option<Vec<u8>> = None;
2110 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002111 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002112 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002113 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002114 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002115 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002116 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2117 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002118 key_blob = Some((
2119 row.get(0).context("Failed to extract key blob id.")?,
2120 row.get(2).context("Failed to extract key blob.")?,
2121 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002122 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002123 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002124 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002126 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002128 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002129 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002130 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002131 (SubComponentType::CERT, _, _)
2132 | (SubComponentType::CERT_CHAIN, _, _)
2133 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002134 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2135 }
2136 Ok(())
2137 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002138 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002139
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002140 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2141 Ok(Some((
2142 blob,
2143 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002144 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002145 )))
2146 })?;
2147
2148 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002149 }
2150
2151 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2152 let mut stmt = tx
2153 .prepare(
2154 "SELECT tag, data, security_level from persistent.keyparameter
2155 WHERE keyentryid = ?;",
2156 )
2157 .context("In load_key_parameters: prepare statement failed.")?;
2158
2159 let mut parameters: Vec<KeyParameter> = Vec::new();
2160
2161 let mut rows =
2162 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002163 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002164 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2165 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002166 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002167 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002168 .context("Failed to read KeyParameter.")?,
2169 );
2170 Ok(())
2171 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002172 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002173
2174 Ok(parameters)
2175 }
2176
Qi Wub9433b52020-12-01 14:52:46 +08002177 /// Decrements the usage count of a limited use key. This function first checks whether the
2178 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2179 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2180 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002181 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002182 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2183
Qi Wub9433b52020-12-01 14:52:46 +08002184 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2185 let limit: Option<i32> = tx
2186 .query_row(
2187 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2188 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2189 |row| row.get(0),
2190 )
2191 .optional()
2192 .context("Trying to load usage count")?;
2193
2194 let limit = limit
2195 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2196 .context("The Key no longer exists. Key is exhausted.")?;
2197
2198 tx.execute(
2199 "UPDATE persistent.keyparameter
2200 SET data = data - 1
2201 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2202 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2203 )
2204 .context("Failed to update key usage count.")?;
2205
2206 match limit {
2207 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002208 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002209 .context("Trying to mark limited use key for deletion."),
2210 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002211 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002212 }
2213 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002214 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002215 }
2216
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002217 /// Load a key entry by the given key descriptor.
2218 /// It uses the `check_permission` callback to verify if the access is allowed
2219 /// given the key access tuple read from the database using `load_access_tuple`.
2220 /// With `load_bits` the caller may specify which blobs shall be loaded from
2221 /// the blob database.
2222 pub fn load_key_entry(
2223 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002224 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002225 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002226 load_bits: KeyEntryLoadBits,
2227 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002228 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2229 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002230 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2231
Janis Danisevskis66784c42021-01-27 08:40:25 -08002232 loop {
2233 match self.load_key_entry_internal(
2234 key,
2235 key_type,
2236 load_bits,
2237 caller_uid,
2238 &check_permission,
2239 ) {
2240 Ok(result) => break Ok(result),
2241 Err(e) => {
2242 if Self::is_locked_error(&e) {
2243 std::thread::sleep(std::time::Duration::from_micros(500));
2244 continue;
2245 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002246 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002247 }
2248 }
2249 }
2250 }
2251 }
2252
2253 fn load_key_entry_internal(
2254 &mut self,
2255 key: &KeyDescriptor,
2256 key_type: KeyType,
2257 load_bits: KeyEntryLoadBits,
2258 caller_uid: u32,
2259 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002260 ) -> Result<(KeyIdGuard, KeyEntry)> {
2261 // KEY ID LOCK 1/2
2262 // If we got a key descriptor with a key id we can get the lock right away.
2263 // Otherwise we have to defer it until we know the key id.
2264 let key_id_guard = match key.domain {
2265 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2266 _ => None,
2267 };
2268
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002269 let tx = self
2270 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002271 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002272 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273
2274 // Load the key_id and complete the access control tuple.
2275 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002276 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002277
2278 // Perform access control. It is vital that we return here if the permission is denied.
2279 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002280 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002281
Janis Danisevskisaec14592020-11-12 09:41:49 -08002282 // KEY ID LOCK 2/2
2283 // If we did not get a key id lock by now, it was because we got a key descriptor
2284 // without a key id. At this point we got the key id, so we can try and get a lock.
2285 // However, we cannot block here, because we are in the middle of the transaction.
2286 // So first we try to get the lock non blocking. If that fails, we roll back the
2287 // transaction and block until we get the lock. After we successfully got the lock,
2288 // we start a new transaction and load the access tuple again.
2289 //
2290 // We don't need to perform access control again, because we already established
2291 // that the caller had access to the given key. But we need to make sure that the
2292 // key id still exists. So we have to load the key entry by key id this time.
2293 let (key_id_guard, tx) = match key_id_guard {
2294 None => match KEY_ID_LOCK.try_get(key_id) {
2295 None => {
2296 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002297 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002298
Janis Danisevskisaec14592020-11-12 09:41:49 -08002299 // Block until we have a key id lock.
2300 let key_id_guard = KEY_ID_LOCK.get(key_id);
2301
2302 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002303 let tx = self
2304 .conn
2305 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002306 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002307
2308 Self::load_access_tuple(
2309 &tx,
2310 // This time we have to load the key by the retrieved key id, because the
2311 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002312 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002313 domain: Domain::KEY_ID,
2314 nspace: key_id,
2315 ..Default::default()
2316 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002317 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002318 caller_uid,
2319 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002320 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002321 (key_id_guard, tx)
2322 }
2323 Some(l) => (l, tx),
2324 },
2325 Some(key_id_guard) => (key_id_guard, tx),
2326 };
2327
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002328 let key_entry =
2329 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002330
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002331 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002332
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002333 Ok((key_id_guard, key_entry))
2334 }
2335
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002336 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002337 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002338 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2339 .context("Trying to delete keyentry.")?;
2340 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2341 .context("Trying to delete keymetadata.")?;
2342 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2343 .context("Trying to delete keyparameters.")?;
2344 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2345 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002346 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002347 }
2348
2349 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002350 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002351 pub fn unbind_key(
2352 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002353 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002354 key_type: KeyType,
2355 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002356 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002357 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002358 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2359
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002360 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2361 let (key_id, access_key_descriptor, access_vector) =
2362 Self::load_access_tuple(tx, key, key_type, caller_uid)
2363 .context("Trying to get access tuple.")?;
2364
2365 // Perform access control. It is vital that we return here if the permission is denied.
2366 // So do not touch that '?' at the end.
2367 check_permission(&access_key_descriptor, access_vector)
2368 .context("While checking permission.")?;
2369
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002370 Self::mark_unreferenced(tx, key_id)
2371 .map(|need_gc| (need_gc, ()))
2372 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002373 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002374 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002375 }
2376
Max Bires8e93d2b2021-01-14 13:17:59 -08002377 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2378 tx.query_row(
2379 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2380 params![key_id],
2381 |row| row.get(0),
2382 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002383 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002384 }
2385
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002386 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2387 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2388 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002389 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2390
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002391 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002392 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002393 }
2394 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2395 tx.execute(
2396 "DELETE FROM persistent.keymetadata
2397 WHERE keyentryid IN (
2398 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002399 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002400 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002401 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002402 )
2403 .context("Trying to delete keymetadata.")?;
2404 tx.execute(
2405 "DELETE FROM persistent.keyparameter
2406 WHERE keyentryid IN (
2407 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002408 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002409 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002410 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002411 )
2412 .context("Trying to delete keyparameters.")?;
2413 tx.execute(
2414 "DELETE FROM persistent.grant
2415 WHERE keyentryid IN (
2416 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002417 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002418 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002419 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002420 )
2421 .context("Trying to delete grants.")?;
2422 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002423 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002424 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2425 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002426 )
2427 .context("Trying to delete keyentry.")?;
2428 Ok(()).need_gc()
2429 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002430 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002431 }
2432
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002433 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2434 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2435 {
2436 tx.execute(
2437 "DELETE FROM persistent.keymetadata
2438 WHERE keyentryid IN (
2439 SELECT id FROM persistent.keyentry
2440 WHERE state = ?
2441 );",
2442 params![KeyLifeCycle::Unreferenced],
2443 )
2444 .context("Trying to delete keymetadata.")?;
2445 tx.execute(
2446 "DELETE FROM persistent.keyparameter
2447 WHERE keyentryid IN (
2448 SELECT id FROM persistent.keyentry
2449 WHERE state = ?
2450 );",
2451 params![KeyLifeCycle::Unreferenced],
2452 )
2453 .context("Trying to delete keyparameters.")?;
2454 tx.execute(
2455 "DELETE FROM persistent.grant
2456 WHERE keyentryid IN (
2457 SELECT id FROM persistent.keyentry
2458 WHERE state = ?
2459 );",
2460 params![KeyLifeCycle::Unreferenced],
2461 )
2462 .context("Trying to delete grants.")?;
2463 tx.execute(
2464 "DELETE FROM persistent.keyentry
2465 WHERE state = ?;",
2466 params![KeyLifeCycle::Unreferenced],
2467 )
2468 .context("Trying to delete keyentry.")?;
2469 Result::<()>::Ok(())
2470 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002471 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002472 }
2473
Hasini Gunasingheda895552021-01-27 19:34:37 +00002474 /// Delete the keys created on behalf of the user, denoted by the user id.
2475 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2476 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2477 /// The caller of this function should notify the gc if the returned value is true.
2478 pub fn unbind_keys_for_user(
2479 &mut self,
2480 user_id: u32,
2481 keep_non_super_encrypted_keys: bool,
2482 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002483 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2484
Hasini Gunasingheda895552021-01-27 19:34:37 +00002485 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2486 let mut stmt = tx
2487 .prepare(&format!(
2488 "SELECT id from persistent.keyentry
2489 WHERE (
2490 key_type = ?
2491 AND domain = ?
2492 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2493 AND state = ?
2494 ) OR (
2495 key_type = ?
2496 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002497 AND state = ?
2498 );",
2499 aid_user_offset = AID_USER_OFFSET
2500 ))
2501 .context(concat!(
2502 "In unbind_keys_for_user. ",
2503 "Failed to prepare the query to find the keys created by apps."
2504 ))?;
2505
2506 let mut rows = stmt
2507 .query(params![
2508 // WHERE client key:
2509 KeyType::Client,
2510 Domain::APP.0 as u32,
2511 user_id,
2512 KeyLifeCycle::Live,
2513 // OR super key:
2514 KeyType::Super,
2515 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002516 KeyLifeCycle::Live
2517 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002518 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002519
2520 let mut key_ids: Vec<i64> = Vec::new();
2521 db_utils::with_rows_extract_all(&mut rows, |row| {
2522 key_ids
2523 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2524 Ok(())
2525 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002526 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002527
2528 let mut notify_gc = false;
2529 for key_id in key_ids {
2530 if keep_non_super_encrypted_keys {
2531 // Load metadata and filter out non-super-encrypted keys.
2532 if let (_, Some((_, blob_metadata)), _, _) =
2533 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002534 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002535 {
2536 if blob_metadata.encrypted_by().is_none() {
2537 continue;
2538 }
2539 }
2540 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002541 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002542 .context("In unbind_keys_for_user.")?
2543 || notify_gc;
2544 }
2545 Ok(()).do_gc(notify_gc)
2546 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002547 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002548 }
2549
Eric Biggersb0478cf2023-10-27 03:55:29 +00002550 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2551 /// This runs when the user's lock screen is being changed to Swipe or None.
2552 ///
2553 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2554 /// such keys also require user authentication. Keystore's concept of user authentication is
2555 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2556 /// authentication is no longer possible. In contrast, keys that just require that the device
2557 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2558 /// is always considered "unlocked" in that case.
2559 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2560 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2561
2562 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2563 let mut stmt = tx
2564 .prepare(&format!(
2565 "SELECT id from persistent.keyentry
2566 WHERE key_type = ?
2567 AND domain = ?
2568 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2569 AND state = ?;",
2570 aid_user_offset = AID_USER_OFFSET
2571 ))
2572 .context(concat!(
2573 "In unbind_auth_bound_keys_for_user. ",
2574 "Failed to prepare the query to find the keys created by apps."
2575 ))?;
2576
2577 let mut rows = stmt
2578 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2579 .context(ks_err!("Failed to query the keys created by apps."))?;
2580
2581 let mut key_ids: Vec<i64> = Vec::new();
2582 db_utils::with_rows_extract_all(&mut rows, |row| {
2583 key_ids
2584 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2585 Ok(())
2586 })
2587 .context(ks_err!())?;
2588
2589 let mut notify_gc = false;
2590 let mut num_unbound = 0;
2591 for key_id in key_ids {
2592 // Load the key parameters and filter out non-auth-bound keys. To identify
2593 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2594 // could also be used, but UserSecureID is what Keystore treats as authoritative
2595 // when actually enforcing the key parameters (it might not matter, though).
2596 let params = Self::load_key_parameters(key_id, tx)
2597 .context("Failed to load key parameters.")?;
2598 let is_auth_bound_key = params.iter().any(|kp| {
2599 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2600 });
2601 if is_auth_bound_key {
2602 notify_gc = Self::mark_unreferenced(tx, key_id)
2603 .context("In unbind_auth_bound_keys_for_user.")?
2604 || notify_gc;
2605 num_unbound += 1;
2606 }
2607 }
2608 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2609 Ok(()).do_gc(notify_gc)
2610 })
2611 .context(ks_err!())
2612 }
2613
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002614 fn load_key_components(
2615 tx: &Transaction,
2616 load_bits: KeyEntryLoadBits,
2617 key_id: i64,
2618 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002619 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002620
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002621 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002622 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002623
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002624 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002625 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002626
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002627 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002628 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002629
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002630 Ok(KeyEntry {
2631 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002632 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002633 cert: cert_blob,
2634 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002635 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002636 parameters,
2637 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002638 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002639 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002640 }
2641
Eran Messeri24f31972023-01-25 17:00:33 +00002642 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2643 /// aliases are greater than the specified 'start_past_alias'. If no value
2644 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002645 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002646 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002647 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002648 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002649 &mut self,
2650 domain: Domain,
2651 namespace: i64,
2652 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002653 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002654 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002655 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002656
Eran Messeri24f31972023-01-25 17:00:33 +00002657 let query = format!(
2658 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002659 WHERE domain = ?
2660 AND namespace = ?
2661 AND alias IS NOT NULL
2662 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002663 AND key_type = ?
2664 {}
2665 ORDER BY alias ASC;",
2666 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2667 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002668
Eran Messeri24f31972023-01-25 17:00:33 +00002669 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2670 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2671
2672 let mut rows = match start_past_alias {
2673 Some(past_alias) => stmt
2674 .query(params![
2675 domain.0 as u32,
2676 namespace,
2677 KeyLifeCycle::Live,
2678 key_type,
2679 past_alias
2680 ])
2681 .context(ks_err!("Failed to query."))?,
2682 None => stmt
2683 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2684 .context(ks_err!("Failed to query."))?,
2685 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002686
Janis Danisevskis66784c42021-01-27 08:40:25 -08002687 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2688 db_utils::with_rows_extract_all(&mut rows, |row| {
2689 descriptors.push(KeyDescriptor {
2690 domain,
2691 nspace: namespace,
2692 alias: Some(row.get(0).context("Trying to extract alias.")?),
2693 blob: None,
2694 });
2695 Ok(())
2696 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002697 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002698 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002699 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002700 }
2701
Eran Messeri24f31972023-01-25 17:00:33 +00002702 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2703 /// Domain must be APP or SELINUX, the caller must make sure of that.
2704 pub fn count_keys(
2705 &mut self,
2706 domain: Domain,
2707 namespace: i64,
2708 key_type: KeyType,
2709 ) -> Result<usize> {
2710 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2711
2712 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2713 tx.query_row(
2714 "SELECT COUNT(alias) FROM persistent.keyentry
2715 WHERE domain = ?
2716 AND namespace = ?
2717 AND alias IS NOT NULL
2718 AND state = ?
2719 AND key_type = ?;",
2720 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2721 |row| row.get(0),
2722 )
2723 .context(ks_err!("Failed to count number of keys."))
2724 .no_gc()
2725 })?;
2726 Ok(num_keys)
2727 }
2728
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002729 /// Adds a grant to the grant table.
2730 /// Like `load_key_entry` this function loads the access tuple before
2731 /// it uses the callback for a permission check. Upon success,
2732 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2733 /// grant table. The new row will have a randomized id, which is used as
2734 /// grant id in the namespace field of the resulting KeyDescriptor.
2735 pub fn grant(
2736 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002737 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002738 caller_uid: u32,
2739 grantee_uid: u32,
2740 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002741 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002742 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002743 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2744
Janis Danisevskis66784c42021-01-27 08:40:25 -08002745 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2746 // Load the key_id and complete the access control tuple.
2747 // We ignore the access vector here because grants cannot be granted.
2748 // The access vector returned here expresses the permissions the
2749 // grantee has if key.domain == Domain::GRANT. But this vector
2750 // cannot include the grant permission by design, so there is no way the
2751 // subsequent permission check can pass.
2752 // We could check key.domain == Domain::GRANT and fail early.
2753 // But even if we load the access tuple by grant here, the permission
2754 // check denies the attempt to create a grant by grant descriptor.
2755 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002756 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002757
Janis Danisevskis66784c42021-01-27 08:40:25 -08002758 // Perform access control. It is vital that we return here if the permission
2759 // was denied. So do not touch that '?' at the end of the line.
2760 // This permission check checks if the caller has the grant permission
2761 // for the given key and in addition to all of the permissions
2762 // expressed in `access_vector`.
2763 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002764 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002765
Janis Danisevskis66784c42021-01-27 08:40:25 -08002766 let grant_id = if let Some(grant_id) = tx
2767 .query_row(
2768 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002769 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002770 params![key_id, grantee_uid],
2771 |row| row.get(0),
2772 )
2773 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002774 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002775 {
2776 tx.execute(
2777 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002778 SET access_vector = ?
2779 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002780 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002781 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002782 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002783 grant_id
2784 } else {
2785 Self::insert_with_retry(|id| {
2786 tx.execute(
2787 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2788 VALUES (?, ?, ?, ?);",
2789 params![id, grantee_uid, key_id, i32::from(access_vector)],
2790 )
2791 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002792 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002793 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002794
Janis Danisevskis66784c42021-01-27 08:40:25 -08002795 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002796 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002797 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002798 }
2799
2800 /// This function checks permissions like `grant` and `load_key_entry`
2801 /// before removing a grant from the grant table.
2802 pub fn ungrant(
2803 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002804 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002805 caller_uid: u32,
2806 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002807 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002808 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002809 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2810
Janis Danisevskis66784c42021-01-27 08:40:25 -08002811 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2812 // Load the key_id and complete the access control tuple.
2813 // We ignore the access vector here because grants cannot be granted.
2814 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002815 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002816
Janis Danisevskis66784c42021-01-27 08:40:25 -08002817 // Perform access control. We must return here if the permission
2818 // was denied. So do not touch the '?' at the end of this line.
2819 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002820 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002821
Janis Danisevskis66784c42021-01-27 08:40:25 -08002822 tx.execute(
2823 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002824 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002825 params![key_id, grantee_uid],
2826 )
2827 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002828
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002829 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002830 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002831 }
2832
Joel Galenson845f74b2020-09-09 14:11:55 -07002833 // Generates a random id and passes it to the given function, which will
2834 // try to insert it into a database. If that insertion fails, retry;
2835 // otherwise return the id.
2836 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2837 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002838 let newid: i64 = match random() {
2839 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2840 i => i,
2841 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002842 match inserter(newid) {
2843 // If the id already existed, try again.
2844 Err(rusqlite::Error::SqliteFailure(
2845 libsqlite3_sys::Error {
2846 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2847 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2848 },
2849 _,
2850 )) => (),
2851 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002852 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002853 }
2854 _ => return Ok(newid),
2855 }
2856 }
2857 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002858
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002859 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2860 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
2861 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
2862 auth_token.clone(),
2863 MonotonicRawTime::now(),
2864 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002865 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002866
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002867 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002868 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002869 where
2870 F: Fn(&AuthTokenEntry) -> bool,
2871 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002872 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002873 }
2874
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002875 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002876 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
2877 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002878 }
2879
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002880 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002881 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
2882 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002883 }
2884
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002885 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002886 fn get_last_off_body(&self) -> MonotonicRawTime {
2887 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002888 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002889
2890 /// Load descriptor of a key by key id
2891 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2892 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2893
2894 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2895 tx.query_row(
2896 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2897 params![key_id],
2898 |row| {
2899 Ok(KeyDescriptor {
2900 domain: Domain(row.get(0)?),
2901 nspace: row.get(1)?,
2902 alias: row.get(2)?,
2903 blob: None,
2904 })
2905 },
2906 )
2907 .optional()
2908 .context("Trying to load key descriptor")
2909 .no_gc()
2910 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002911 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002912 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002913
2914 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2915 /// (for the given user_id).
2916 /// This is helpful for finding out which apps will have their keys invalidated when
2917 /// the user changes biometrics enrollment or removes their LSKF.
2918 pub fn get_app_uids_affected_by_sid(
2919 &mut self,
2920 user_id: i32,
2921 secure_user_id: i64,
2922 ) -> Result<Vec<i64>> {
2923 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2924
2925 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2926 let mut stmt = tx
2927 .prepare(&format!(
2928 "SELECT id, namespace from persistent.keyentry
2929 WHERE key_type = ?
2930 AND domain = ?
2931 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2932 AND state = ?;",
2933 ))
2934 .context(concat!(
2935 "In get_app_uids_affected_by_sid, ",
2936 "failed to prepare the query to find the keys created by apps."
2937 ))?;
2938
2939 let mut rows = stmt
2940 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2941 .context(ks_err!("Failed to query the keys created by apps."))?;
2942
2943 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2944 db_utils::with_rows_extract_all(&mut rows, |row| {
2945 key_ids_and_app_uids.insert(
2946 row.get(0).context("Failed to read key id of a key created by an app.")?,
2947 row.get(1).context("Failed to read the app uid")?,
2948 );
2949 Ok(())
2950 })?;
2951 Ok(key_ids_and_app_uids).no_gc()
2952 })?;
2953 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2954 for (key_id, app_uid) in key_ids_and_app_uids {
2955 // Read the key parameters for each key in its own transaction. It is OK to ignore
2956 // an error to get the properties of a particular key since it might have been deleted
2957 // under our feet after the previous transaction concluded. If the key was deleted
2958 // then it is no longer applicable if it was auth-bound or not.
2959 if let Ok(is_key_bound_to_sid) =
2960 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2961 let params = Self::load_key_parameters(key_id, tx)
2962 .context("Failed to load key parameters.")?;
2963 // Check if the key is bound to this secure user ID.
2964 let is_key_bound_to_sid = params.iter().any(|kp| {
2965 matches!(
2966 kp.key_parameter_value(),
2967 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2968 )
2969 });
2970 Ok(is_key_bound_to_sid).no_gc()
2971 })
2972 {
2973 if is_key_bound_to_sid {
2974 app_uids_affected_by_sid.insert(app_uid);
2975 }
2976 }
2977 }
2978
2979 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2980 Ok(app_uids_vec)
2981 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002982}
2983
2984#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002985pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002986
2987 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002988 use crate::key_parameter::{
2989 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2990 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2991 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002992 use crate::key_perm_set;
2993 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002994 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002995 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002996 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2997 HardwareAuthToken::HardwareAuthToken,
2998 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002999 };
3000 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003001 Timestamp::Timestamp,
3002 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003003 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003004 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003005 use std::collections::BTreeMap;
3006 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003007 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04003008 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003009 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003010 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003011 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003012 #[cfg(disabled)]
3013 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003014
Seth Moore7ee79f92021-12-07 11:42:49 -08003015 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003016 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003017
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003018 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003019 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003020 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003021 })?;
3022 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003023 }
3024
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003025 fn rebind_alias(
3026 db: &mut KeystoreDB,
3027 newid: &KeyIdGuard,
3028 alias: &str,
3029 domain: Domain,
3030 namespace: i64,
3031 ) -> Result<bool> {
3032 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003033 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003034 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003035 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003036 }
3037
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003038 #[test]
3039 fn datetime() -> Result<()> {
3040 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003041 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003042 let now = SystemTime::now();
3043 let duration = Duration::from_secs(1000);
3044 let then = now.checked_sub(duration).unwrap();
3045 let soon = now.checked_add(duration).unwrap();
3046 conn.execute(
3047 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3048 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3049 )?;
3050 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003051 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003052 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3053 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3054 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3055 assert!(rows.next()?.is_none());
3056 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3057 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3058 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3059 Ok(())
3060 }
3061
Joel Galenson0891bc12020-07-20 10:37:03 -07003062 // Ensure that we're using the "injected" random function, not the real one.
3063 #[test]
3064 fn test_mocked_random() {
3065 let rand1 = random();
3066 let rand2 = random();
3067 let rand3 = random();
3068 if rand1 == rand2 {
3069 assert_eq!(rand2 + 1, rand3);
3070 } else {
3071 assert_eq!(rand1 + 1, rand2);
3072 assert_eq!(rand2, rand3);
3073 }
3074 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003075
Joel Galenson26f4d012020-07-17 14:57:21 -07003076 // Test that we have the correct tables.
3077 #[test]
3078 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003079 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003080 let tables = db
3081 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003082 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003083 .query_map(params![], |row| row.get(0))?
3084 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003085 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003086 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003087 assert_eq!(tables[1], "blobmetadata");
3088 assert_eq!(tables[2], "grant");
3089 assert_eq!(tables[3], "keyentry");
3090 assert_eq!(tables[4], "keymetadata");
3091 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003092 Ok(())
3093 }
3094
3095 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003096 fn test_auth_token_table_invariant() -> Result<()> {
3097 let mut db = new_test_db()?;
3098 let auth_token1 = HardwareAuthToken {
3099 challenge: i64::MAX,
3100 userId: 200,
3101 authenticatorId: 200,
3102 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3103 timestamp: Timestamp { milliSeconds: 500 },
3104 mac: String::from("mac").into_bytes(),
3105 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003106 db.insert_auth_token(&auth_token1);
3107 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003108 assert_eq!(auth_tokens_returned.len(), 1);
3109
3110 // insert another auth token with the same values for the columns in the UNIQUE constraint
3111 // of the auth token table and different value for timestamp
3112 let auth_token2 = HardwareAuthToken {
3113 challenge: i64::MAX,
3114 userId: 200,
3115 authenticatorId: 200,
3116 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3117 timestamp: Timestamp { milliSeconds: 600 },
3118 mac: String::from("mac").into_bytes(),
3119 };
3120
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003121 db.insert_auth_token(&auth_token2);
3122 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003123 assert_eq!(auth_tokens_returned.len(), 1);
3124
3125 if let Some(auth_token) = auth_tokens_returned.pop() {
3126 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3127 }
3128
3129 // insert another auth token with the different values for the columns in the UNIQUE
3130 // constraint of the auth token table
3131 let auth_token3 = HardwareAuthToken {
3132 challenge: i64::MAX,
3133 userId: 201,
3134 authenticatorId: 200,
3135 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3136 timestamp: Timestamp { milliSeconds: 600 },
3137 mac: String::from("mac").into_bytes(),
3138 };
3139
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003140 db.insert_auth_token(&auth_token3);
3141 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003142 assert_eq!(auth_tokens_returned.len(), 2);
3143
3144 Ok(())
3145 }
3146
3147 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003148 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3149 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003150 }
3151
3152 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003153 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003154 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003155 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003156
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003157 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003158 let entries = get_keyentry(&db)?;
3159 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003160
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003161 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003162
3163 let entries_new = get_keyentry(&db)?;
3164 assert_eq!(entries, entries_new);
3165 Ok(())
3166 }
3167
3168 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003169 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003170 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3171 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003172 }
3173
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003174 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003175
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003176 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3177 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003178
3179 let entries = get_keyentry(&db)?;
3180 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003181 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3182 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003183
3184 // Test that we must pass in a valid Domain.
3185 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003186 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003187 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003188 );
3189 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003190 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003191 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003192 );
3193 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003194 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003195 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003196 );
3197
3198 Ok(())
3199 }
3200
Joel Galenson33c04ad2020-08-03 11:04:38 -07003201 #[test]
3202 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003203 fn extractor(
3204 ke: &KeyEntryRow,
3205 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3206 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003207 }
3208
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003209 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003210 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3211 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003212 let entries = get_keyentry(&db)?;
3213 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003214 assert_eq!(
3215 extractor(&entries[0]),
3216 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3217 );
3218 assert_eq!(
3219 extractor(&entries[1]),
3220 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3221 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003222
3223 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003224 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003225 let entries = get_keyentry(&db)?;
3226 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003227 assert_eq!(
3228 extractor(&entries[0]),
3229 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3230 );
3231 assert_eq!(
3232 extractor(&entries[1]),
3233 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3234 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003235
3236 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003237 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003238 let entries = get_keyentry(&db)?;
3239 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003240 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3241 assert_eq!(
3242 extractor(&entries[1]),
3243 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3244 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003245
3246 // Test that we must pass in a valid Domain.
3247 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003248 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003249 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003250 );
3251 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003252 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003253 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003254 );
3255 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003256 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003257 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003258 );
3259
3260 // Test that we correctly handle setting an alias for something that does not exist.
3261 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003262 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003263 "Expected to update a single entry but instead updated 0",
3264 );
3265 // Test that we correctly abort the transaction in this case.
3266 let entries = get_keyentry(&db)?;
3267 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003268 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3269 assert_eq!(
3270 extractor(&entries[1]),
3271 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3272 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003273
3274 Ok(())
3275 }
3276
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003277 #[test]
3278 fn test_grant_ungrant() -> Result<()> {
3279 const CALLER_UID: u32 = 15;
3280 const GRANTEE_UID: u32 = 12;
3281 const SELINUX_NAMESPACE: i64 = 7;
3282
3283 let mut db = new_test_db()?;
3284 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003285 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3286 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3287 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003288 )?;
3289 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003290 domain: super::Domain::APP,
3291 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003292 alias: Some("key".to_string()),
3293 blob: None,
3294 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003295 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3296 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003297
3298 // Reset totally predictable random number generator in case we
3299 // are not the first test running on this thread.
3300 reset_random();
3301 let next_random = 0i64;
3302
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003303 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003304 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003305 assert_eq!(*a, PVEC1);
3306 assert_eq!(
3307 *k,
3308 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003309 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003310 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003311 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003312 alias: Some("key".to_string()),
3313 blob: None,
3314 }
3315 );
3316 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003317 })
3318 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003319
3320 assert_eq!(
3321 app_granted_key,
3322 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003323 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003324 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003325 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003326 alias: None,
3327 blob: None,
3328 }
3329 );
3330
3331 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003332 domain: super::Domain::SELINUX,
3333 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003334 alias: Some("yek".to_string()),
3335 blob: None,
3336 };
3337
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003338 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003339 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003340 assert_eq!(*a, PVEC1);
3341 assert_eq!(
3342 *k,
3343 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003344 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003345 // namespace must be the supplied SELinux
3346 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003347 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003348 alias: Some("yek".to_string()),
3349 blob: None,
3350 }
3351 );
3352 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003353 })
3354 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003355
3356 assert_eq!(
3357 selinux_granted_key,
3358 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003359 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003360 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003361 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003362 alias: None,
3363 blob: None,
3364 }
3365 );
3366
3367 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003368 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003369 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003370 assert_eq!(*a, PVEC2);
3371 assert_eq!(
3372 *k,
3373 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003374 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003375 // namespace must be the supplied SELinux
3376 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003377 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003378 alias: Some("yek".to_string()),
3379 blob: None,
3380 }
3381 );
3382 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003383 })
3384 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003385
3386 assert_eq!(
3387 selinux_granted_key,
3388 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003389 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003390 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003391 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003392 alias: None,
3393 blob: None,
3394 }
3395 );
3396
3397 {
3398 // Limiting scope of stmt, because it borrows db.
3399 let mut stmt = db
3400 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003401 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003402 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3403 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3404 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003405
3406 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003407 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003408 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003409 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003410 assert!(rows.next().is_none());
3411 }
3412
3413 debug_dump_keyentry_table(&mut db)?;
3414 println!("app_key {:?}", app_key);
3415 println!("selinux_key {:?}", selinux_key);
3416
Janis Danisevskis66784c42021-01-27 08:40:25 -08003417 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3418 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003419
3420 Ok(())
3421 }
3422
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003423 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003424 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3425 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3426
3427 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003428 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003429 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003430 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003431 let mut blob_metadata = BlobMetaData::new();
3432 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3433 db.set_blob(
3434 &key_id,
3435 SubComponentType::KEY_BLOB,
3436 Some(TEST_KEY_BLOB),
3437 Some(&blob_metadata),
3438 )?;
3439 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3440 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003441 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003442
3443 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003444 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003445 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003446 )?;
3447 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003448 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003449 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003450 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003451 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003452 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003453 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003454 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003455 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003456 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003457
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003458 drop(rows);
3459 drop(stmt);
3460
3461 assert_eq!(
3462 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3463 BlobMetaData::load_from_db(id, tx).no_gc()
3464 })
3465 .expect("Should find blob metadata."),
3466 blob_metadata
3467 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003468 Ok(())
3469 }
3470
3471 static TEST_ALIAS: &str = "my super duper key";
3472
3473 #[test]
3474 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3475 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003476 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003477 .context("test_insert_and_load_full_keyentry_domain_app")?
3478 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003479 let (_key_guard, key_entry) = db
3480 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003481 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003482 domain: Domain::APP,
3483 nspace: 0,
3484 alias: Some(TEST_ALIAS.to_string()),
3485 blob: None,
3486 },
3487 KeyType::Client,
3488 KeyEntryLoadBits::BOTH,
3489 1,
3490 |_k, _av| Ok(()),
3491 )
3492 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003493 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003494
3495 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003496 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003497 domain: Domain::APP,
3498 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003499 alias: Some(TEST_ALIAS.to_string()),
3500 blob: None,
3501 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003502 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003503 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003504 |_, _| Ok(()),
3505 )
3506 .unwrap();
3507
3508 assert_eq!(
3509 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3510 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003511 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003512 domain: Domain::APP,
3513 nspace: 0,
3514 alias: Some(TEST_ALIAS.to_string()),
3515 blob: None,
3516 },
3517 KeyType::Client,
3518 KeyEntryLoadBits::NONE,
3519 1,
3520 |_k, _av| Ok(()),
3521 )
3522 .unwrap_err()
3523 .root_cause()
3524 .downcast_ref::<KsError>()
3525 );
3526
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003527 Ok(())
3528 }
3529
3530 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003531 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3532 let mut db = new_test_db()?;
3533
3534 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003535 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003536 domain: Domain::APP,
3537 nspace: 1,
3538 alias: Some(TEST_ALIAS.to_string()),
3539 blob: None,
3540 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003541 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003542 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003543 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003544 )
3545 .expect("Trying to insert cert.");
3546
3547 let (_key_guard, mut key_entry) = db
3548 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003549 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003550 domain: Domain::APP,
3551 nspace: 1,
3552 alias: Some(TEST_ALIAS.to_string()),
3553 blob: None,
3554 },
3555 KeyType::Client,
3556 KeyEntryLoadBits::PUBLIC,
3557 1,
3558 |_k, _av| Ok(()),
3559 )
3560 .expect("Trying to read certificate entry.");
3561
3562 assert!(key_entry.pure_cert());
3563 assert!(key_entry.cert().is_none());
3564 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3565
3566 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003567 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003568 domain: Domain::APP,
3569 nspace: 1,
3570 alias: Some(TEST_ALIAS.to_string()),
3571 blob: None,
3572 },
3573 KeyType::Client,
3574 1,
3575 |_, _| Ok(()),
3576 )
3577 .unwrap();
3578
3579 assert_eq!(
3580 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3581 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003582 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003583 domain: Domain::APP,
3584 nspace: 1,
3585 alias: Some(TEST_ALIAS.to_string()),
3586 blob: None,
3587 },
3588 KeyType::Client,
3589 KeyEntryLoadBits::NONE,
3590 1,
3591 |_k, _av| Ok(()),
3592 )
3593 .unwrap_err()
3594 .root_cause()
3595 .downcast_ref::<KsError>()
3596 );
3597
3598 Ok(())
3599 }
3600
3601 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003602 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3603 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003604 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003605 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3606 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003607 let (_key_guard, key_entry) = db
3608 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003609 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003610 domain: Domain::SELINUX,
3611 nspace: 1,
3612 alias: Some(TEST_ALIAS.to_string()),
3613 blob: None,
3614 },
3615 KeyType::Client,
3616 KeyEntryLoadBits::BOTH,
3617 1,
3618 |_k, _av| Ok(()),
3619 )
3620 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003621 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003622
3623 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003624 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003625 domain: Domain::SELINUX,
3626 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003627 alias: Some(TEST_ALIAS.to_string()),
3628 blob: None,
3629 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003630 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003631 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003632 |_, _| Ok(()),
3633 )
3634 .unwrap();
3635
3636 assert_eq!(
3637 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3638 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003639 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003640 domain: Domain::SELINUX,
3641 nspace: 1,
3642 alias: Some(TEST_ALIAS.to_string()),
3643 blob: None,
3644 },
3645 KeyType::Client,
3646 KeyEntryLoadBits::NONE,
3647 1,
3648 |_k, _av| Ok(()),
3649 )
3650 .unwrap_err()
3651 .root_cause()
3652 .downcast_ref::<KsError>()
3653 );
3654
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003655 Ok(())
3656 }
3657
3658 #[test]
3659 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3660 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003661 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003662 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3663 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003664 let (_, key_entry) = db
3665 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003666 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003667 KeyType::Client,
3668 KeyEntryLoadBits::BOTH,
3669 1,
3670 |_k, _av| Ok(()),
3671 )
3672 .unwrap();
3673
Qi Wub9433b52020-12-01 14:52:46 +08003674 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003675
3676 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003677 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003678 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003679 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003680 |_, _| Ok(()),
3681 )
3682 .unwrap();
3683
3684 assert_eq!(
3685 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3686 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003687 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003688 KeyType::Client,
3689 KeyEntryLoadBits::NONE,
3690 1,
3691 |_k, _av| Ok(()),
3692 )
3693 .unwrap_err()
3694 .root_cause()
3695 .downcast_ref::<KsError>()
3696 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003697
3698 Ok(())
3699 }
3700
3701 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003702 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3703 let mut db = new_test_db()?;
3704 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3705 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3706 .0;
3707 // Update the usage count of the limited use key.
3708 db.check_and_update_key_usage_count(key_id)?;
3709
3710 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003711 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003712 KeyType::Client,
3713 KeyEntryLoadBits::BOTH,
3714 1,
3715 |_k, _av| Ok(()),
3716 )?;
3717
3718 // The usage count is decremented now.
3719 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3720
3721 Ok(())
3722 }
3723
3724 #[test]
3725 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3726 let mut db = new_test_db()?;
3727 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3728 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3729 .0;
3730 // Update the usage count of the limited use key.
3731 db.check_and_update_key_usage_count(key_id).expect(concat!(
3732 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3733 "This should succeed."
3734 ));
3735
3736 // Try to update the exhausted limited use key.
3737 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3738 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3739 "This should fail."
3740 ));
3741 assert_eq!(
3742 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3743 e.root_cause().downcast_ref::<KsError>().unwrap()
3744 );
3745
3746 Ok(())
3747 }
3748
3749 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003750 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3751 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003752 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003753 .context("test_insert_and_load_full_keyentry_from_grant")?
3754 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003756 let granted_key = db
3757 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003758 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003759 domain: Domain::APP,
3760 nspace: 0,
3761 alias: Some(TEST_ALIAS.to_string()),
3762 blob: None,
3763 },
3764 1,
3765 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003766 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003767 |_k, _av| Ok(()),
3768 )
3769 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003770
3771 debug_dump_grant_table(&mut db)?;
3772
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003773 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003774 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3775 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003776 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003777 Ok(())
3778 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003779 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003780
Qi Wub9433b52020-12-01 14:52:46 +08003781 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003782
Janis Danisevskis66784c42021-01-27 08:40:25 -08003783 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003784
3785 assert_eq!(
3786 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3787 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003788 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003789 KeyType::Client,
3790 KeyEntryLoadBits::NONE,
3791 2,
3792 |_k, _av| Ok(()),
3793 )
3794 .unwrap_err()
3795 .root_cause()
3796 .downcast_ref::<KsError>()
3797 );
3798
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003799 Ok(())
3800 }
3801
Janis Danisevskis45760022021-01-19 16:34:10 -08003802 // This test attempts to load a key by key id while the caller is not the owner
3803 // but a grant exists for the given key and the caller.
3804 #[test]
3805 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3806 let mut db = new_test_db()?;
3807 const OWNER_UID: u32 = 1u32;
3808 const GRANTEE_UID: u32 = 2u32;
3809 const SOMEONE_ELSE_UID: u32 = 3u32;
3810 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3811 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3812 .0;
3813
3814 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003815 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003816 domain: Domain::APP,
3817 nspace: 0,
3818 alias: Some(TEST_ALIAS.to_string()),
3819 blob: None,
3820 },
3821 OWNER_UID,
3822 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003823 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003824 |_k, _av| Ok(()),
3825 )
3826 .unwrap();
3827
3828 debug_dump_grant_table(&mut db)?;
3829
3830 let id_descriptor =
3831 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3832
3833 let (_, key_entry) = db
3834 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003835 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003836 KeyType::Client,
3837 KeyEntryLoadBits::BOTH,
3838 GRANTEE_UID,
3839 |k, av| {
3840 assert_eq!(Domain::APP, k.domain);
3841 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003842 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003843 Ok(())
3844 },
3845 )
3846 .unwrap();
3847
3848 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3849
3850 let (_, key_entry) = db
3851 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003852 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003853 KeyType::Client,
3854 KeyEntryLoadBits::BOTH,
3855 SOMEONE_ELSE_UID,
3856 |k, av| {
3857 assert_eq!(Domain::APP, k.domain);
3858 assert_eq!(OWNER_UID as i64, k.nspace);
3859 assert!(av.is_none());
3860 Ok(())
3861 },
3862 )
3863 .unwrap();
3864
3865 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3866
Janis Danisevskis66784c42021-01-27 08:40:25 -08003867 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003868
3869 assert_eq!(
3870 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3871 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003872 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003873 KeyType::Client,
3874 KeyEntryLoadBits::NONE,
3875 GRANTEE_UID,
3876 |_k, _av| Ok(()),
3877 )
3878 .unwrap_err()
3879 .root_cause()
3880 .downcast_ref::<KsError>()
3881 );
3882
3883 Ok(())
3884 }
3885
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003886 // Creates a key migrates it to a different location and then tries to access it by the old
3887 // and new location.
3888 #[test]
3889 fn test_migrate_key_app_to_app() -> Result<()> {
3890 let mut db = new_test_db()?;
3891 const SOURCE_UID: u32 = 1u32;
3892 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003893 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3894 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003895 let key_id_guard =
3896 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3897 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3898
3899 let source_descriptor: KeyDescriptor = KeyDescriptor {
3900 domain: Domain::APP,
3901 nspace: -1,
3902 alias: Some(SOURCE_ALIAS.to_string()),
3903 blob: None,
3904 };
3905
3906 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3907 domain: Domain::APP,
3908 nspace: -1,
3909 alias: Some(DESTINATION_ALIAS.to_string()),
3910 blob: None,
3911 };
3912
3913 let key_id = key_id_guard.id();
3914
3915 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3916 Ok(())
3917 })
3918 .unwrap();
3919
3920 let (_, key_entry) = db
3921 .load_key_entry(
3922 &destination_descriptor,
3923 KeyType::Client,
3924 KeyEntryLoadBits::BOTH,
3925 DESTINATION_UID,
3926 |k, av| {
3927 assert_eq!(Domain::APP, k.domain);
3928 assert_eq!(DESTINATION_UID as i64, k.nspace);
3929 assert!(av.is_none());
3930 Ok(())
3931 },
3932 )
3933 .unwrap();
3934
3935 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3936
3937 assert_eq!(
3938 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3939 db.load_key_entry(
3940 &source_descriptor,
3941 KeyType::Client,
3942 KeyEntryLoadBits::NONE,
3943 SOURCE_UID,
3944 |_k, _av| Ok(()),
3945 )
3946 .unwrap_err()
3947 .root_cause()
3948 .downcast_ref::<KsError>()
3949 );
3950
3951 Ok(())
3952 }
3953
3954 // Creates a key migrates it to a different location and then tries to access it by the old
3955 // and new location.
3956 #[test]
3957 fn test_migrate_key_app_to_selinux() -> Result<()> {
3958 let mut db = new_test_db()?;
3959 const SOURCE_UID: u32 = 1u32;
3960 const DESTINATION_UID: u32 = 2u32;
3961 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003962 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3963 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003964 let key_id_guard =
3965 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3966 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3967
3968 let source_descriptor: KeyDescriptor = KeyDescriptor {
3969 domain: Domain::APP,
3970 nspace: -1,
3971 alias: Some(SOURCE_ALIAS.to_string()),
3972 blob: None,
3973 };
3974
3975 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3976 domain: Domain::SELINUX,
3977 nspace: DESTINATION_NAMESPACE,
3978 alias: Some(DESTINATION_ALIAS.to_string()),
3979 blob: None,
3980 };
3981
3982 let key_id = key_id_guard.id();
3983
3984 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3985 Ok(())
3986 })
3987 .unwrap();
3988
3989 let (_, key_entry) = db
3990 .load_key_entry(
3991 &destination_descriptor,
3992 KeyType::Client,
3993 KeyEntryLoadBits::BOTH,
3994 DESTINATION_UID,
3995 |k, av| {
3996 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003997 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003998 assert!(av.is_none());
3999 Ok(())
4000 },
4001 )
4002 .unwrap();
4003
4004 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4005
4006 assert_eq!(
4007 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4008 db.load_key_entry(
4009 &source_descriptor,
4010 KeyType::Client,
4011 KeyEntryLoadBits::NONE,
4012 SOURCE_UID,
4013 |_k, _av| Ok(()),
4014 )
4015 .unwrap_err()
4016 .root_cause()
4017 .downcast_ref::<KsError>()
4018 );
4019
4020 Ok(())
4021 }
4022
4023 // Creates two keys and tries to migrate the first to the location of the second which
4024 // is expected to fail.
4025 #[test]
4026 fn test_migrate_key_destination_occupied() -> Result<()> {
4027 let mut db = new_test_db()?;
4028 const SOURCE_UID: u32 = 1u32;
4029 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004030 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4031 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004032 let key_id_guard =
4033 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4034 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4035 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4036 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4037
4038 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4039 domain: Domain::APP,
4040 nspace: -1,
4041 alias: Some(DESTINATION_ALIAS.to_string()),
4042 blob: None,
4043 };
4044
4045 assert_eq!(
4046 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4047 db.migrate_key_namespace(
4048 key_id_guard,
4049 &destination_descriptor,
4050 DESTINATION_UID,
4051 |_k| Ok(())
4052 )
4053 .unwrap_err()
4054 .root_cause()
4055 .downcast_ref::<KsError>()
4056 );
4057
4058 Ok(())
4059 }
4060
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004061 #[test]
4062 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004063 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4064 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4065 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004066 const UID: u32 = 33;
4067 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4068 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4069 let key_id_untouched1 =
4070 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4071 let key_id_untouched2 =
4072 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4073 let key_id_deleted =
4074 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4075
4076 let (_, key_entry) = db
4077 .load_key_entry(
4078 &KeyDescriptor {
4079 domain: Domain::APP,
4080 nspace: -1,
4081 alias: Some(ALIAS1.to_string()),
4082 blob: None,
4083 },
4084 KeyType::Client,
4085 KeyEntryLoadBits::BOTH,
4086 UID,
4087 |k, av| {
4088 assert_eq!(Domain::APP, k.domain);
4089 assert_eq!(UID as i64, k.nspace);
4090 assert!(av.is_none());
4091 Ok(())
4092 },
4093 )
4094 .unwrap();
4095 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4096 let (_, key_entry) = db
4097 .load_key_entry(
4098 &KeyDescriptor {
4099 domain: Domain::APP,
4100 nspace: -1,
4101 alias: Some(ALIAS2.to_string()),
4102 blob: None,
4103 },
4104 KeyType::Client,
4105 KeyEntryLoadBits::BOTH,
4106 UID,
4107 |k, av| {
4108 assert_eq!(Domain::APP, k.domain);
4109 assert_eq!(UID as i64, k.nspace);
4110 assert!(av.is_none());
4111 Ok(())
4112 },
4113 )
4114 .unwrap();
4115 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4116 let (_, key_entry) = db
4117 .load_key_entry(
4118 &KeyDescriptor {
4119 domain: Domain::APP,
4120 nspace: -1,
4121 alias: Some(ALIAS3.to_string()),
4122 blob: None,
4123 },
4124 KeyType::Client,
4125 KeyEntryLoadBits::BOTH,
4126 UID,
4127 |k, av| {
4128 assert_eq!(Domain::APP, k.domain);
4129 assert_eq!(UID as i64, k.nspace);
4130 assert!(av.is_none());
4131 Ok(())
4132 },
4133 )
4134 .unwrap();
4135 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4136
4137 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4138 KeystoreDB::from_0_to_1(tx).no_gc()
4139 })
4140 .unwrap();
4141
4142 let (_, key_entry) = db
4143 .load_key_entry(
4144 &KeyDescriptor {
4145 domain: Domain::APP,
4146 nspace: -1,
4147 alias: Some(ALIAS1.to_string()),
4148 blob: None,
4149 },
4150 KeyType::Client,
4151 KeyEntryLoadBits::BOTH,
4152 UID,
4153 |k, av| {
4154 assert_eq!(Domain::APP, k.domain);
4155 assert_eq!(UID as i64, k.nspace);
4156 assert!(av.is_none());
4157 Ok(())
4158 },
4159 )
4160 .unwrap();
4161 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4162 let (_, key_entry) = db
4163 .load_key_entry(
4164 &KeyDescriptor {
4165 domain: Domain::APP,
4166 nspace: -1,
4167 alias: Some(ALIAS2.to_string()),
4168 blob: None,
4169 },
4170 KeyType::Client,
4171 KeyEntryLoadBits::BOTH,
4172 UID,
4173 |k, av| {
4174 assert_eq!(Domain::APP, k.domain);
4175 assert_eq!(UID as i64, k.nspace);
4176 assert!(av.is_none());
4177 Ok(())
4178 },
4179 )
4180 .unwrap();
4181 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4182 assert_eq!(
4183 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4184 db.load_key_entry(
4185 &KeyDescriptor {
4186 domain: Domain::APP,
4187 nspace: -1,
4188 alias: Some(ALIAS3.to_string()),
4189 blob: None,
4190 },
4191 KeyType::Client,
4192 KeyEntryLoadBits::BOTH,
4193 UID,
4194 |k, av| {
4195 assert_eq!(Domain::APP, k.domain);
4196 assert_eq!(UID as i64, k.nspace);
4197 assert!(av.is_none());
4198 Ok(())
4199 },
4200 )
4201 .unwrap_err()
4202 .root_cause()
4203 .downcast_ref::<KsError>()
4204 );
4205 }
4206
Janis Danisevskisaec14592020-11-12 09:41:49 -08004207 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4208
Janis Danisevskisaec14592020-11-12 09:41:49 -08004209 #[test]
4210 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4211 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004212 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4213 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004214 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004215 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004216 .context("test_insert_and_load_full_keyentry_domain_app")?
4217 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004218 let (_key_guard, key_entry) = db
4219 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004220 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004221 domain: Domain::APP,
4222 nspace: 0,
4223 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4224 blob: None,
4225 },
4226 KeyType::Client,
4227 KeyEntryLoadBits::BOTH,
4228 33,
4229 |_k, _av| Ok(()),
4230 )
4231 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004232 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004233 let state = Arc::new(AtomicU8::new(1));
4234 let state2 = state.clone();
4235
4236 // Spawning a second thread that attempts to acquire the key id lock
4237 // for the same key as the primary thread. The primary thread then
4238 // waits, thereby forcing the secondary thread into the second stage
4239 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4240 // The test succeeds if the secondary thread observes the transition
4241 // of `state` from 1 to 2, despite having a whole second to overtake
4242 // the primary thread.
4243 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004244 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004245 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004246 assert!(db
4247 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004248 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004249 domain: Domain::APP,
4250 nspace: 0,
4251 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4252 blob: None,
4253 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004254 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004255 KeyEntryLoadBits::BOTH,
4256 33,
4257 |_k, _av| Ok(()),
4258 )
4259 .is_ok());
4260 // We should only see a 2 here because we can only return
4261 // from load_key_entry when the `_key_guard` expires,
4262 // which happens at the end of the scope.
4263 assert_eq!(2, state2.load(Ordering::Relaxed));
4264 });
4265
4266 thread::sleep(std::time::Duration::from_millis(1000));
4267
4268 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4269
4270 // Return the handle from this scope so we can join with the
4271 // secondary thread after the key id lock has expired.
4272 handle
4273 // This is where the `_key_guard` goes out of scope,
4274 // which is the reason for concurrent load_key_entry on the same key
4275 // to unblock.
4276 };
4277 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4278 // main test thread. We will not see failing asserts in secondary threads otherwise.
4279 handle.join().unwrap();
4280 Ok(())
4281 }
4282
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004283 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004284 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004285 let temp_dir =
4286 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4287
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004288 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4289 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004290
4291 let _tx1 = db1
4292 .conn
4293 .transaction_with_behavior(TransactionBehavior::Immediate)
4294 .expect("Failed to create first transaction.");
4295
4296 let error = db2
4297 .conn
4298 .transaction_with_behavior(TransactionBehavior::Immediate)
4299 .context("Transaction begin failed.")
4300 .expect_err("This should fail.");
4301 let root_cause = error.root_cause();
4302 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4303 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4304 {
4305 return;
4306 }
4307 panic!(
4308 "Unexpected error {:?} \n{:?} \n{:?}",
4309 error,
4310 root_cause,
4311 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4312 )
4313 }
4314
4315 #[cfg(disabled)]
4316 #[test]
4317 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4318 let temp_dir = Arc::new(
4319 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4320 .expect("Failed to create temp dir."),
4321 );
4322
4323 let test_begin = Instant::now();
4324
Janis Danisevskis66784c42021-01-27 08:40:25 -08004325 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004326 let mut db =
4327 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004328 const OPEN_DB_COUNT: u32 = 50u32;
4329
4330 let mut actual_key_count = KEY_COUNT;
4331 // First insert KEY_COUNT keys.
4332 for count in 0..KEY_COUNT {
4333 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4334 actual_key_count = count;
4335 break;
4336 }
4337 let alias = format!("test_alias_{}", count);
4338 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4339 .expect("Failed to make key entry.");
4340 }
4341
4342 // Insert more keys from a different thread and into a different namespace.
4343 let temp_dir1 = temp_dir.clone();
4344 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004345 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4346 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004347
4348 for count in 0..actual_key_count {
4349 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4350 return;
4351 }
4352 let alias = format!("test_alias_{}", count);
4353 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4354 .expect("Failed to make key entry.");
4355 }
4356
4357 // then unbind them again.
4358 for count in 0..actual_key_count {
4359 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4360 return;
4361 }
4362 let key = KeyDescriptor {
4363 domain: Domain::APP,
4364 nspace: -1,
4365 alias: Some(format!("test_alias_{}", count)),
4366 blob: None,
4367 };
4368 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4369 }
4370 });
4371
4372 // And start unbinding the first set of keys.
4373 let temp_dir2 = temp_dir.clone();
4374 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004375 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4376 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004377
4378 for count in 0..actual_key_count {
4379 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4380 return;
4381 }
4382 let key = KeyDescriptor {
4383 domain: Domain::APP,
4384 nspace: -1,
4385 alias: Some(format!("test_alias_{}", count)),
4386 blob: None,
4387 };
4388 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4389 }
4390 });
4391
Janis Danisevskis66784c42021-01-27 08:40:25 -08004392 // While a lot of inserting and deleting is going on we have to open database connections
4393 // successfully and use them.
4394 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4395 // out of scope.
4396 #[allow(clippy::redundant_clone)]
4397 let temp_dir4 = temp_dir.clone();
4398 let handle4 = thread::spawn(move || {
4399 for count in 0..OPEN_DB_COUNT {
4400 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4401 return;
4402 }
Seth Moore444b51a2021-06-11 09:49:49 -07004403 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4404 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004405
4406 let alias = format!("test_alias_{}", count);
4407 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4408 .expect("Failed to make key entry.");
4409 let key = KeyDescriptor {
4410 domain: Domain::APP,
4411 nspace: -1,
4412 alias: Some(alias),
4413 blob: None,
4414 };
4415 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4416 }
4417 });
4418
4419 handle1.join().expect("Thread 1 panicked.");
4420 handle2.join().expect("Thread 2 panicked.");
4421 handle4.join().expect("Thread 4 panicked.");
4422
Janis Danisevskis66784c42021-01-27 08:40:25 -08004423 Ok(())
4424 }
4425
4426 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004427 fn list() -> Result<()> {
4428 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004429 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004430 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4431 (Domain::APP, 1, "test1"),
4432 (Domain::APP, 1, "test2"),
4433 (Domain::APP, 1, "test3"),
4434 (Domain::APP, 1, "test4"),
4435 (Domain::APP, 1, "test5"),
4436 (Domain::APP, 1, "test6"),
4437 (Domain::APP, 1, "test7"),
4438 (Domain::APP, 2, "test1"),
4439 (Domain::APP, 2, "test2"),
4440 (Domain::APP, 2, "test3"),
4441 (Domain::APP, 2, "test4"),
4442 (Domain::APP, 2, "test5"),
4443 (Domain::APP, 2, "test6"),
4444 (Domain::APP, 2, "test8"),
4445 (Domain::SELINUX, 100, "test1"),
4446 (Domain::SELINUX, 100, "test2"),
4447 (Domain::SELINUX, 100, "test3"),
4448 (Domain::SELINUX, 100, "test4"),
4449 (Domain::SELINUX, 100, "test5"),
4450 (Domain::SELINUX, 100, "test6"),
4451 (Domain::SELINUX, 100, "test9"),
4452 ];
4453
4454 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4455 .iter()
4456 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004457 let entry =
4458 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004459 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4460 });
4461 (entry.id(), *ns)
4462 })
4463 .collect();
4464
4465 for (domain, namespace) in
4466 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4467 {
4468 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4469 .iter()
4470 .filter_map(|(domain, ns, alias)| match ns {
4471 ns if *ns == *namespace => Some(KeyDescriptor {
4472 domain: *domain,
4473 nspace: *ns,
4474 alias: Some(alias.to_string()),
4475 blob: None,
4476 }),
4477 _ => None,
4478 })
4479 .collect();
4480 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004481 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004482 list_result.sort();
4483 assert_eq!(list_o_descriptors, list_result);
4484
4485 let mut list_o_ids: Vec<i64> = list_o_descriptors
4486 .into_iter()
4487 .map(|d| {
4488 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004489 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004490 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004491 KeyType::Client,
4492 KeyEntryLoadBits::NONE,
4493 *namespace as u32,
4494 |_, _| Ok(()),
4495 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004496 .unwrap();
4497 entry.id()
4498 })
4499 .collect();
4500 list_o_ids.sort_unstable();
4501 let mut loaded_entries: Vec<i64> = list_o_keys
4502 .iter()
4503 .filter_map(|(id, ns)| match ns {
4504 ns if *ns == *namespace => Some(*id),
4505 _ => None,
4506 })
4507 .collect();
4508 loaded_entries.sort_unstable();
4509 assert_eq!(list_o_ids, loaded_entries);
4510 }
Eran Messeri24f31972023-01-25 17:00:33 +00004511 assert_eq!(
4512 Vec::<KeyDescriptor>::new(),
4513 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4514 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004515
4516 Ok(())
4517 }
4518
Joel Galenson0891bc12020-07-20 10:37:03 -07004519 // Helpers
4520
4521 // Checks that the given result is an error containing the given string.
4522 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4523 let error_str = format!(
4524 "{:#?}",
4525 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4526 );
4527 assert!(
4528 error_str.contains(target),
4529 "The string \"{}\" should contain \"{}\"",
4530 error_str,
4531 target
4532 );
4533 }
4534
Joel Galenson2aab4432020-07-22 15:27:57 -07004535 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004536 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004537 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004538 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004539 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004540 namespace: Option<i64>,
4541 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004542 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004543 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004544 }
4545
4546 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4547 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004548 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004549 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004550 Ok(KeyEntryRow {
4551 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004552 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004553 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004554 namespace: row.get(3)?,
4555 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004556 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004557 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004558 })
4559 })?
4560 .map(|r| r.context("Could not read keyentry row."))
4561 .collect::<Result<Vec<_>>>()
4562 }
4563
Eran Messeri4dc27b52024-01-09 12:43:31 +00004564 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4565 make_test_params_with_sids(max_usage_count, &[42])
4566 }
4567
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004568 // Note: The parameters and SecurityLevel associations are nonsensical. This
4569 // collection is only used to check if the parameters are preserved as expected by the
4570 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004571 fn make_test_params_with_sids(
4572 max_usage_count: Option<i32>,
4573 user_secure_ids: &[i64],
4574 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004575 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004576 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4577 KeyParameter::new(
4578 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4579 SecurityLevel::TRUSTED_ENVIRONMENT,
4580 ),
4581 KeyParameter::new(
4582 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4583 SecurityLevel::TRUSTED_ENVIRONMENT,
4584 ),
4585 KeyParameter::new(
4586 KeyParameterValue::Algorithm(Algorithm::RSA),
4587 SecurityLevel::TRUSTED_ENVIRONMENT,
4588 ),
4589 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4590 KeyParameter::new(
4591 KeyParameterValue::BlockMode(BlockMode::ECB),
4592 SecurityLevel::TRUSTED_ENVIRONMENT,
4593 ),
4594 KeyParameter::new(
4595 KeyParameterValue::BlockMode(BlockMode::GCM),
4596 SecurityLevel::TRUSTED_ENVIRONMENT,
4597 ),
4598 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4599 KeyParameter::new(
4600 KeyParameterValue::Digest(Digest::MD5),
4601 SecurityLevel::TRUSTED_ENVIRONMENT,
4602 ),
4603 KeyParameter::new(
4604 KeyParameterValue::Digest(Digest::SHA_2_224),
4605 SecurityLevel::TRUSTED_ENVIRONMENT,
4606 ),
4607 KeyParameter::new(
4608 KeyParameterValue::Digest(Digest::SHA_2_256),
4609 SecurityLevel::STRONGBOX,
4610 ),
4611 KeyParameter::new(
4612 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4613 SecurityLevel::TRUSTED_ENVIRONMENT,
4614 ),
4615 KeyParameter::new(
4616 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4617 SecurityLevel::TRUSTED_ENVIRONMENT,
4618 ),
4619 KeyParameter::new(
4620 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4621 SecurityLevel::STRONGBOX,
4622 ),
4623 KeyParameter::new(
4624 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4625 SecurityLevel::TRUSTED_ENVIRONMENT,
4626 ),
4627 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4628 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4629 KeyParameter::new(
4630 KeyParameterValue::EcCurve(EcCurve::P_224),
4631 SecurityLevel::TRUSTED_ENVIRONMENT,
4632 ),
4633 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4634 KeyParameter::new(
4635 KeyParameterValue::EcCurve(EcCurve::P_384),
4636 SecurityLevel::TRUSTED_ENVIRONMENT,
4637 ),
4638 KeyParameter::new(
4639 KeyParameterValue::EcCurve(EcCurve::P_521),
4640 SecurityLevel::TRUSTED_ENVIRONMENT,
4641 ),
4642 KeyParameter::new(
4643 KeyParameterValue::RSAPublicExponent(3),
4644 SecurityLevel::TRUSTED_ENVIRONMENT,
4645 ),
4646 KeyParameter::new(
4647 KeyParameterValue::IncludeUniqueID,
4648 SecurityLevel::TRUSTED_ENVIRONMENT,
4649 ),
4650 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4651 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4652 KeyParameter::new(
4653 KeyParameterValue::ActiveDateTime(1234567890),
4654 SecurityLevel::STRONGBOX,
4655 ),
4656 KeyParameter::new(
4657 KeyParameterValue::OriginationExpireDateTime(1234567890),
4658 SecurityLevel::TRUSTED_ENVIRONMENT,
4659 ),
4660 KeyParameter::new(
4661 KeyParameterValue::UsageExpireDateTime(1234567890),
4662 SecurityLevel::TRUSTED_ENVIRONMENT,
4663 ),
4664 KeyParameter::new(
4665 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4666 SecurityLevel::TRUSTED_ENVIRONMENT,
4667 ),
4668 KeyParameter::new(
4669 KeyParameterValue::MaxUsesPerBoot(1234567890),
4670 SecurityLevel::TRUSTED_ENVIRONMENT,
4671 ),
4672 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004673 KeyParameter::new(
4674 KeyParameterValue::NoAuthRequired,
4675 SecurityLevel::TRUSTED_ENVIRONMENT,
4676 ),
4677 KeyParameter::new(
4678 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4679 SecurityLevel::TRUSTED_ENVIRONMENT,
4680 ),
4681 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4682 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4683 KeyParameter::new(
4684 KeyParameterValue::TrustedUserPresenceRequired,
4685 SecurityLevel::TRUSTED_ENVIRONMENT,
4686 ),
4687 KeyParameter::new(
4688 KeyParameterValue::TrustedConfirmationRequired,
4689 SecurityLevel::TRUSTED_ENVIRONMENT,
4690 ),
4691 KeyParameter::new(
4692 KeyParameterValue::UnlockedDeviceRequired,
4693 SecurityLevel::TRUSTED_ENVIRONMENT,
4694 ),
4695 KeyParameter::new(
4696 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4697 SecurityLevel::SOFTWARE,
4698 ),
4699 KeyParameter::new(
4700 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4701 SecurityLevel::SOFTWARE,
4702 ),
4703 KeyParameter::new(
4704 KeyParameterValue::CreationDateTime(12345677890),
4705 SecurityLevel::SOFTWARE,
4706 ),
4707 KeyParameter::new(
4708 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4709 SecurityLevel::TRUSTED_ENVIRONMENT,
4710 ),
4711 KeyParameter::new(
4712 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4713 SecurityLevel::TRUSTED_ENVIRONMENT,
4714 ),
4715 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4716 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4717 KeyParameter::new(
4718 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4719 SecurityLevel::SOFTWARE,
4720 ),
4721 KeyParameter::new(
4722 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4723 SecurityLevel::TRUSTED_ENVIRONMENT,
4724 ),
4725 KeyParameter::new(
4726 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4727 SecurityLevel::TRUSTED_ENVIRONMENT,
4728 ),
4729 KeyParameter::new(
4730 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4731 SecurityLevel::TRUSTED_ENVIRONMENT,
4732 ),
4733 KeyParameter::new(
4734 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4735 SecurityLevel::TRUSTED_ENVIRONMENT,
4736 ),
4737 KeyParameter::new(
4738 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4739 SecurityLevel::TRUSTED_ENVIRONMENT,
4740 ),
4741 KeyParameter::new(
4742 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4743 SecurityLevel::TRUSTED_ENVIRONMENT,
4744 ),
4745 KeyParameter::new(
4746 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4747 SecurityLevel::TRUSTED_ENVIRONMENT,
4748 ),
4749 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004750 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4751 SecurityLevel::TRUSTED_ENVIRONMENT,
4752 ),
4753 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004754 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4755 SecurityLevel::TRUSTED_ENVIRONMENT,
4756 ),
4757 KeyParameter::new(
4758 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4759 SecurityLevel::TRUSTED_ENVIRONMENT,
4760 ),
4761 KeyParameter::new(
4762 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4763 SecurityLevel::TRUSTED_ENVIRONMENT,
4764 ),
4765 KeyParameter::new(
4766 KeyParameterValue::VendorPatchLevel(3),
4767 SecurityLevel::TRUSTED_ENVIRONMENT,
4768 ),
4769 KeyParameter::new(
4770 KeyParameterValue::BootPatchLevel(4),
4771 SecurityLevel::TRUSTED_ENVIRONMENT,
4772 ),
4773 KeyParameter::new(
4774 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4775 SecurityLevel::TRUSTED_ENVIRONMENT,
4776 ),
4777 KeyParameter::new(
4778 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4779 SecurityLevel::TRUSTED_ENVIRONMENT,
4780 ),
4781 KeyParameter::new(
4782 KeyParameterValue::MacLength(256),
4783 SecurityLevel::TRUSTED_ENVIRONMENT,
4784 ),
4785 KeyParameter::new(
4786 KeyParameterValue::ResetSinceIdRotation,
4787 SecurityLevel::TRUSTED_ENVIRONMENT,
4788 ),
4789 KeyParameter::new(
4790 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4791 SecurityLevel::TRUSTED_ENVIRONMENT,
4792 ),
Qi Wub9433b52020-12-01 14:52:46 +08004793 ];
4794 if let Some(value) = max_usage_count {
4795 params.push(KeyParameter::new(
4796 KeyParameterValue::UsageCountLimit(value),
4797 SecurityLevel::SOFTWARE,
4798 ));
4799 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004800
4801 for sid in user_secure_ids.iter() {
4802 params.push(KeyParameter::new(
4803 KeyParameterValue::UserSecureID(*sid),
4804 SecurityLevel::STRONGBOX,
4805 ));
4806 }
Qi Wub9433b52020-12-01 14:52:46 +08004807 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004808 }
4809
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004810 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004811 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004812 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004813 namespace: i64,
4814 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004815 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004816 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004817 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4818 }
4819
4820 pub fn make_test_key_entry_with_sids(
4821 db: &mut KeystoreDB,
4822 domain: Domain,
4823 namespace: i64,
4824 alias: &str,
4825 max_usage_count: Option<i32>,
4826 sids: &[i64],
4827 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004828 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004829 let mut blob_metadata = BlobMetaData::new();
4830 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4831 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4832 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4833 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4834 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4835
4836 db.set_blob(
4837 &key_id,
4838 SubComponentType::KEY_BLOB,
4839 Some(TEST_KEY_BLOB),
4840 Some(&blob_metadata),
4841 )?;
4842 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4843 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004844
Eran Messeri4dc27b52024-01-09 12:43:31 +00004845 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004846 db.insert_keyparameter(&key_id, &params)?;
4847
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004848 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004849 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004850 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004851 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004852 Ok(key_id)
4853 }
4854
Qi Wub9433b52020-12-01 14:52:46 +08004855 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4856 let params = make_test_params(max_usage_count);
4857
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004858 let mut blob_metadata = BlobMetaData::new();
4859 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4860 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4861 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4862 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4863 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4864
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004865 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004866 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004867
4868 KeyEntry {
4869 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004870 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004871 cert: Some(TEST_CERT_BLOB.to_vec()),
4872 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004873 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004874 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004875 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004876 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004877 }
4878 }
4879
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004880 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004881 db: &mut KeystoreDB,
4882 domain: Domain,
4883 namespace: i64,
4884 alias: &str,
4885 logical_only: bool,
4886 ) -> Result<KeyIdGuard> {
4887 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4888 let mut blob_metadata = BlobMetaData::new();
4889 if !logical_only {
4890 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4891 }
4892 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4893
4894 db.set_blob(
4895 &key_id,
4896 SubComponentType::KEY_BLOB,
4897 Some(TEST_KEY_BLOB),
4898 Some(&blob_metadata),
4899 )?;
4900 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4901 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4902
4903 let mut params = make_test_params(None);
4904 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4905
4906 db.insert_keyparameter(&key_id, &params)?;
4907
4908 let mut metadata = KeyMetaData::new();
4909 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4910 db.insert_key_metadata(&key_id, &metadata)?;
4911 rebind_alias(db, &key_id, alias, domain, namespace)?;
4912 Ok(key_id)
4913 }
4914
Eric Biggersb0478cf2023-10-27 03:55:29 +00004915 // Creates an app key that is marked as being superencrypted by the given
4916 // super key ID and that has the given authentication and unlocked device
4917 // parameters. This does not actually superencrypt the key blob.
4918 fn make_superencrypted_key_entry(
4919 db: &mut KeystoreDB,
4920 namespace: i64,
4921 alias: &str,
4922 requires_authentication: bool,
4923 requires_unlocked_device: bool,
4924 super_key_id: i64,
4925 ) -> Result<KeyIdGuard> {
4926 let domain = Domain::APP;
4927 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4928
4929 let mut blob_metadata = BlobMetaData::new();
4930 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4931 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4932 db.set_blob(
4933 &key_id,
4934 SubComponentType::KEY_BLOB,
4935 Some(TEST_KEY_BLOB),
4936 Some(&blob_metadata),
4937 )?;
4938
4939 let mut params = vec![];
4940 if requires_unlocked_device {
4941 params.push(KeyParameter::new(
4942 KeyParameterValue::UnlockedDeviceRequired,
4943 SecurityLevel::TRUSTED_ENVIRONMENT,
4944 ));
4945 }
4946 if requires_authentication {
4947 params.push(KeyParameter::new(
4948 KeyParameterValue::UserSecureID(42),
4949 SecurityLevel::TRUSTED_ENVIRONMENT,
4950 ));
4951 }
4952 db.insert_keyparameter(&key_id, &params)?;
4953
4954 let mut metadata = KeyMetaData::new();
4955 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4956 db.insert_key_metadata(&key_id, &metadata)?;
4957
4958 rebind_alias(db, &key_id, alias, domain, namespace)?;
4959 Ok(key_id)
4960 }
4961
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004962 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4963 let mut params = make_test_params(None);
4964 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4965
4966 let mut blob_metadata = BlobMetaData::new();
4967 if !logical_only {
4968 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4969 }
4970 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4971
4972 let mut metadata = KeyMetaData::new();
4973 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4974
4975 KeyEntry {
4976 id: key_id,
4977 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4978 cert: Some(TEST_CERT_BLOB.to_vec()),
4979 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4980 km_uuid: KEYSTORE_UUID,
4981 parameters: params,
4982 metadata,
4983 pure_cert: false,
4984 }
4985 }
4986
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004987 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004988 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004989 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004990 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004991 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004992 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004993 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004994 Ok((
4995 row.get(0)?,
4996 row.get(1)?,
4997 row.get(2)?,
4998 row.get(3)?,
4999 row.get(4)?,
5000 row.get(5)?,
5001 row.get(6)?,
5002 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005003 },
5004 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005005
5006 println!("Key entry table rows:");
5007 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005008 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005009 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005010 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5011 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005012 );
5013 }
5014 Ok(())
5015 }
5016
5017 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005018 let mut stmt = db
5019 .conn
5020 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005021 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005022 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5023 })?;
5024
5025 println!("Grant table rows:");
5026 for r in rows {
5027 let (id, gt, ki, av) = r.unwrap();
5028 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5029 }
5030 Ok(())
5031 }
5032
Joel Galenson0891bc12020-07-20 10:37:03 -07005033 // Use a custom random number generator that repeats each number once.
5034 // This allows us to test repeated elements.
5035
5036 thread_local! {
5037 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5038 }
5039
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005040 fn reset_random() {
5041 RANDOM_COUNTER.with(|counter| {
5042 *counter.borrow_mut() = 0;
5043 })
5044 }
5045
Joel Galenson0891bc12020-07-20 10:37:03 -07005046 pub fn random() -> i64 {
5047 RANDOM_COUNTER.with(|counter| {
5048 let result = *counter.borrow() / 2;
5049 *counter.borrow_mut() += 1;
5050 result
5051 })
5052 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005053
5054 #[test]
5055 fn test_last_off_body() -> Result<()> {
5056 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005057 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005058 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005059 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005060 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005061 let one_second = Duration::from_secs(1);
5062 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005063 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005064 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005065 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005066 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005067 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005068 Ok(())
5069 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005070
5071 #[test]
5072 fn test_unbind_keys_for_user() -> Result<()> {
5073 let mut db = new_test_db()?;
5074 db.unbind_keys_for_user(1, false)?;
5075
5076 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5077 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5078 db.unbind_keys_for_user(2, false)?;
5079
Eran Messeri24f31972023-01-25 17:00:33 +00005080 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
5081 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005082
5083 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00005084 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005085
5086 Ok(())
5087 }
5088
5089 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005090 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5091 let mut db = new_test_db()?;
5092 let super_key = keystore2_crypto::generate_aes256_key()?;
5093 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5094 let (encrypted_super_key, metadata) =
5095 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5096
5097 let key_name_enc = SuperKeyType {
5098 alias: "test_super_key_1",
5099 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005100 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005101 };
5102
5103 let key_name_nonenc = SuperKeyType {
5104 alias: "test_super_key_2",
5105 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005106 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005107 };
5108
5109 // Install two super keys.
5110 db.store_super_key(
5111 1,
5112 &key_name_nonenc,
5113 &super_key,
5114 &BlobMetaData::new(),
5115 &KeyMetaData::new(),
5116 )?;
5117 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5118
5119 // Check that both can be found in the database.
5120 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5121 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5122
5123 // Install the same keys for a different user.
5124 db.store_super_key(
5125 2,
5126 &key_name_nonenc,
5127 &super_key,
5128 &BlobMetaData::new(),
5129 &KeyMetaData::new(),
5130 )?;
5131 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5132
5133 // Check that the second pair of keys can be found in the database.
5134 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5135 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5136
5137 // Delete only encrypted keys.
5138 db.unbind_keys_for_user(1, true)?;
5139
5140 // The encrypted superkey should be gone now.
5141 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5142 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5143
5144 // Reinsert the encrypted key.
5145 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5146
5147 // Check that both can be found in the database, again..
5148 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5149 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5150
5151 // Delete all even unencrypted keys.
5152 db.unbind_keys_for_user(1, false)?;
5153
5154 // Both should be gone now.
5155 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5156 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5157
5158 // Check that the second pair of keys was untouched.
5159 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5160 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5161
5162 Ok(())
5163 }
5164
Eric Biggersb0478cf2023-10-27 03:55:29 +00005165 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5166 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5167 }
5168
5169 // Tests the unbind_auth_bound_keys_for_user() function.
5170 #[test]
5171 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5172 let mut db = new_test_db()?;
5173 let user_id = 1;
5174 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5175 let other_user_id = 2;
5176 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5177 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5178
5179 // Create a superencryption key.
5180 let super_key = keystore2_crypto::generate_aes256_key()?;
5181 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5182 let (encrypted_super_key, blob_metadata) =
5183 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5184 db.store_super_key(
5185 user_id,
5186 super_key_type,
5187 &encrypted_super_key,
5188 &blob_metadata,
5189 &KeyMetaData::new(),
5190 )?;
5191 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5192
5193 // Store 4 superencrypted app keys, one for each possible combination of
5194 // (authentication required, unlocked device required).
5195 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5196 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5197 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5198 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5199 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5200 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5201 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5202 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5203
5204 // Also store a key for a different user that requires authentication.
5205 make_superencrypted_key_entry(
5206 &mut db,
5207 other_user_nspace,
5208 "auth_ud",
5209 true,
5210 true,
5211 super_key_id,
5212 )?;
5213
5214 db.unbind_auth_bound_keys_for_user(user_id)?;
5215
5216 // Verify that only the user's app keys that require authentication were
5217 // deleted. Keys that require an unlocked device but not authentication
5218 // should *not* have been deleted, nor should the super key have been
5219 // deleted, nor should other users' keys have been deleted.
5220 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5221 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5222 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5223 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5224 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5225 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5226
5227 Ok(())
5228 }
5229
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005230 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005231 fn test_store_super_key() -> Result<()> {
5232 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005233 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005234 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005235 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005236 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005237 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005238
5239 let (encrypted_super_key, metadata) =
5240 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005241 db.store_super_key(
5242 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005243 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005244 &encrypted_super_key,
5245 &metadata,
5246 &KeyMetaData::new(),
5247 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005248
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005249 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005250 assert!(db.key_exists(
5251 Domain::APP,
5252 1,
5253 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5254 KeyType::Super
5255 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005256
Eric Biggers673d34a2023-10-18 01:54:18 +00005257 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005258 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005259 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005260 key_entry,
5261 &pw,
5262 None,
5263 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005264
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005265 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005266 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005267
Hasini Gunasingheda895552021-01-27 19:34:37 +00005268 Ok(())
5269 }
Seth Moore78c091f2021-04-09 21:38:30 +00005270
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005271 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005272 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005273 MetricsStorage::KEY_ENTRY,
5274 MetricsStorage::KEY_ENTRY_ID_INDEX,
5275 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5276 MetricsStorage::BLOB_ENTRY,
5277 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5278 MetricsStorage::KEY_PARAMETER,
5279 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5280 MetricsStorage::KEY_METADATA,
5281 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5282 MetricsStorage::GRANT,
5283 MetricsStorage::AUTH_TOKEN,
5284 MetricsStorage::BLOB_METADATA,
5285 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005286 ]
5287 }
5288
5289 /// Perform a simple check to ensure that we can query all the storage types
5290 /// that are supported by the DB. Check for reasonable values.
5291 #[test]
5292 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005293 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005294
5295 let mut db = new_test_db()?;
5296
5297 for t in get_valid_statsd_storage_types() {
5298 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005299 // AuthToken can be less than a page since it's in a btree, not sqlite
5300 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005301 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005302 } else {
5303 assert!(stat.size >= PAGE_SIZE);
5304 }
Seth Moore78c091f2021-04-09 21:38:30 +00005305 assert!(stat.size >= stat.unused_size);
5306 }
5307
5308 Ok(())
5309 }
5310
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005311 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005312 get_valid_statsd_storage_types()
5313 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005314 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005315 .collect()
5316 }
5317
5318 fn assert_storage_increased(
5319 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005320 increased_storage_types: Vec<MetricsStorage>,
5321 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005322 ) {
5323 for storage in increased_storage_types {
5324 // Verify the expected storage increased.
5325 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005326 let old = &baseline[&storage.0];
5327 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005328 assert!(
5329 new.unused_size <= old.unused_size,
5330 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005331 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005332 new.unused_size,
5333 old.unused_size
5334 );
5335
5336 // Update the baseline with the new value so that it succeeds in the
5337 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005338 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005339 }
5340
5341 // Get an updated map of the storage and verify there were no unexpected changes.
5342 let updated_stats = get_storage_stats_map(db);
5343 assert_eq!(updated_stats.len(), baseline.len());
5344
5345 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005346 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005347 let mut s = String::new();
5348 for &k in map.keys() {
5349 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5350 .expect("string concat failed");
5351 }
5352 s
5353 };
5354
5355 assert!(
5356 updated_stats[&k].size == baseline[&k].size
5357 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5358 "updated_stats:\n{}\nbaseline:\n{}",
5359 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005360 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005361 );
5362 }
5363 }
5364
5365 #[test]
5366 fn test_verify_key_table_size_reporting() -> Result<()> {
5367 let mut db = new_test_db()?;
5368 let mut working_stats = get_storage_stats_map(&mut db);
5369
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005370 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005371 assert_storage_increased(
5372 &mut db,
5373 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005374 MetricsStorage::KEY_ENTRY,
5375 MetricsStorage::KEY_ENTRY_ID_INDEX,
5376 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005377 ],
5378 &mut working_stats,
5379 );
5380
5381 let mut blob_metadata = BlobMetaData::new();
5382 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5383 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5384 assert_storage_increased(
5385 &mut db,
5386 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005387 MetricsStorage::BLOB_ENTRY,
5388 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5389 MetricsStorage::BLOB_METADATA,
5390 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005391 ],
5392 &mut working_stats,
5393 );
5394
5395 let params = make_test_params(None);
5396 db.insert_keyparameter(&key_id, &params)?;
5397 assert_storage_increased(
5398 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005399 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005400 &mut working_stats,
5401 );
5402
5403 let mut metadata = KeyMetaData::new();
5404 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5405 db.insert_key_metadata(&key_id, &metadata)?;
5406 assert_storage_increased(
5407 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005408 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005409 &mut working_stats,
5410 );
5411
5412 let mut sum = 0;
5413 for stat in working_stats.values() {
5414 sum += stat.size;
5415 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005416 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005417 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5418
5419 Ok(())
5420 }
5421
5422 #[test]
5423 fn test_verify_auth_table_size_reporting() -> Result<()> {
5424 let mut db = new_test_db()?;
5425 let mut working_stats = get_storage_stats_map(&mut db);
5426 db.insert_auth_token(&HardwareAuthToken {
5427 challenge: 123,
5428 userId: 456,
5429 authenticatorId: 789,
5430 authenticatorType: kmhw_authenticator_type::ANY,
5431 timestamp: Timestamp { milliSeconds: 10 },
5432 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005433 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005434 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005435 Ok(())
5436 }
5437
5438 #[test]
5439 fn test_verify_grant_table_size_reporting() -> Result<()> {
5440 const OWNER: i64 = 1;
5441 let mut db = new_test_db()?;
5442 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5443
5444 let mut working_stats = get_storage_stats_map(&mut db);
5445 db.grant(
5446 &KeyDescriptor {
5447 domain: Domain::APP,
5448 nspace: 0,
5449 alias: Some(TEST_ALIAS.to_string()),
5450 blob: None,
5451 },
5452 OWNER as u32,
5453 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005454 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005455 |_, _| Ok(()),
5456 )?;
5457
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005458 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005459
5460 Ok(())
5461 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005462
5463 #[test]
5464 fn find_auth_token_entry_returns_latest() -> Result<()> {
5465 let mut db = new_test_db()?;
5466 db.insert_auth_token(&HardwareAuthToken {
5467 challenge: 123,
5468 userId: 456,
5469 authenticatorId: 789,
5470 authenticatorType: kmhw_authenticator_type::ANY,
5471 timestamp: Timestamp { milliSeconds: 10 },
5472 mac: b"mac0".to_vec(),
5473 });
5474 std::thread::sleep(std::time::Duration::from_millis(1));
5475 db.insert_auth_token(&HardwareAuthToken {
5476 challenge: 123,
5477 userId: 457,
5478 authenticatorId: 789,
5479 authenticatorType: kmhw_authenticator_type::ANY,
5480 timestamp: Timestamp { milliSeconds: 12 },
5481 mac: b"mac1".to_vec(),
5482 });
5483 std::thread::sleep(std::time::Duration::from_millis(1));
5484 db.insert_auth_token(&HardwareAuthToken {
5485 challenge: 123,
5486 userId: 458,
5487 authenticatorId: 789,
5488 authenticatorType: kmhw_authenticator_type::ANY,
5489 timestamp: Timestamp { milliSeconds: 3 },
5490 mac: b"mac2".to_vec(),
5491 });
5492 // All three entries are in the database
5493 assert_eq!(db.perboot.auth_tokens_len(), 3);
5494 // It selected the most recent timestamp
5495 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5496 Ok(())
5497 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005498
5499 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005500 fn test_load_key_descriptor() -> Result<()> {
5501 let mut db = new_test_db()?;
5502 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5503
5504 let key = db.load_key_descriptor(key_id)?.unwrap();
5505
5506 assert_eq!(key.domain, Domain::APP);
5507 assert_eq!(key.nspace, 1);
5508 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5509
5510 // No such id
5511 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5512 Ok(())
5513 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005514
5515 #[test]
5516 fn test_get_list_app_uids_for_sid() -> Result<()> {
5517 let uid: i32 = 1;
5518 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5519 let first_sid = 667;
5520 let second_sid = 669;
5521 let first_app_id: i64 = 123 + uid_offset;
5522 let second_app_id: i64 = 456 + uid_offset;
5523 let third_app_id: i64 = 789 + uid_offset;
5524 let unrelated_app_id: i64 = 1011 + uid_offset;
5525 let mut db = new_test_db()?;
5526 make_test_key_entry_with_sids(
5527 &mut db,
5528 Domain::APP,
5529 first_app_id,
5530 TEST_ALIAS,
5531 None,
5532 &[first_sid],
5533 )
5534 .context("test_get_list_app_uids_for_sid")?;
5535 make_test_key_entry_with_sids(
5536 &mut db,
5537 Domain::APP,
5538 second_app_id,
5539 "alias2",
5540 None,
5541 &[first_sid],
5542 )
5543 .context("test_get_list_app_uids_for_sid")?;
5544 make_test_key_entry_with_sids(
5545 &mut db,
5546 Domain::APP,
5547 second_app_id,
5548 TEST_ALIAS,
5549 None,
5550 &[second_sid],
5551 )
5552 .context("test_get_list_app_uids_for_sid")?;
5553 make_test_key_entry_with_sids(
5554 &mut db,
5555 Domain::APP,
5556 third_app_id,
5557 "alias3",
5558 None,
5559 &[second_sid],
5560 )
5561 .context("test_get_list_app_uids_for_sid")?;
5562 make_test_key_entry_with_sids(
5563 &mut db,
5564 Domain::APP,
5565 unrelated_app_id,
5566 TEST_ALIAS,
5567 None,
5568 &[],
5569 )
5570 .context("test_get_list_app_uids_for_sid")?;
5571
5572 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5573 first_sid_apps.sort();
5574 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5575 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5576 second_sid_apps.sort();
5577 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5578 Ok(())
5579 }
5580
5581 #[test]
5582 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5583 let uid: i32 = 1;
5584 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5585 let first_sid = 667;
5586 let second_sid = 669;
5587 let third_sid = 772;
5588 let first_app_id: i64 = 123 + uid_offset;
5589 let second_app_id: i64 = 456 + uid_offset;
5590 let mut db = new_test_db()?;
5591 make_test_key_entry_with_sids(
5592 &mut db,
5593 Domain::APP,
5594 first_app_id,
5595 TEST_ALIAS,
5596 None,
5597 &[first_sid, second_sid],
5598 )
5599 .context("test_get_list_app_uids_for_sid")?;
5600 make_test_key_entry_with_sids(
5601 &mut db,
5602 Domain::APP,
5603 second_app_id,
5604 "alias2",
5605 None,
5606 &[second_sid, third_sid],
5607 )
5608 .context("test_get_list_app_uids_for_sid")?;
5609
5610 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5611 assert_eq!(first_sid_apps, vec![first_app_id]);
5612
5613 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5614 second_sid_apps.sort();
5615 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5616
5617 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5618 assert_eq!(third_sid_apps, vec![second_app_id]);
5619 Ok(())
5620 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005621}