blob: 0cc982a8e63971c027f45e427b1ca4b38e8f727d [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
Janis Danisevskis030ba022021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskis11bd2592022-01-04 19:59:26 -080048use crate::gc::Gc;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use crate::impl_metadata; // This is in db_utils.rs
Eric Biggersb0478cf2023-10-27 03:55:29 +000050use crate::key_parameter::{KeyParameter, KeyParameterValue, Tag};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000051use crate::ks_err;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070052use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000053use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070055 error::{Error as KsError, ErrorCode, ResponseCode},
56 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080057};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000058use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Tri Voa1634bb2022-12-01 15:54:19 -080059 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
60 SecurityLevel::SecurityLevel,
61};
62use android_security_metrics::aidl::android::security::metrics::{
Tri Vo0346bbe2023-05-12 14:16:31 -040063 Storage::Storage as MetricsStorage, StorageStats::StorageStats,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080064};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070065use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070066 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070067};
Shaquille Johnson7f5a8152023-09-27 18:46:27 +010068use anyhow::{anyhow, Context, Result};
69use keystore2_flags;
70use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
71use utils as db_utils;
72use utils::SqlField;
Max Bires2b2e6562020-09-22 11:22:36 -070073
74use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080075use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000076use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070077#[cfg(not(test))]
78use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070079use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070080 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080081 types::FromSql,
82 types::FromSqlResult,
83 types::ToSqlOutput,
84 types::{FromSqlError, Value, ValueRef},
Andrew Walbran78abb1e2023-05-30 16:20:56 +000085 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070086};
Max Bires2b2e6562020-09-22 11:22:36 -070087
Janis Danisevskisaec14592020-11-12 09:41:49 -080088use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080089 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080090 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070091 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080093};
Max Bires2b2e6562020-09-22 11:22:36 -070094
Joel Galenson0891bc12020-07-20 10:37:03 -070095#[cfg(test)]
96use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070097
Janis Danisevskisb42fc182020-12-15 08:41:27 -080098impl_metadata!(
99 /// A set of metadata for key entries.
100 #[derive(Debug, Default, Eq, PartialEq)]
101 pub struct KeyMetaData;
102 /// A metadata entry for key entries.
103 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
104 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800105 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800106 CreationDate(DateTime) with accessor creation_date,
107 /// Expiration date for attestation keys.
108 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700109 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
110 /// provisioning
111 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
112 /// Vector representing the raw public key so results from the server can be matched
113 /// to the right entry
114 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700115 /// SEC1 public key for ECDH encryption
116 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800117 // --- ADD NEW META DATA FIELDS HERE ---
118 // For backwards compatibility add new entries only to
119 // end of this list and above this comment.
120 };
121);
122
123impl KeyMetaData {
124 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
125 let mut stmt = tx
126 .prepare(
127 "SELECT tag, data from persistent.keymetadata
128 WHERE keyentryid = ?;",
129 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000130 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800131
132 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
133
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000134 let mut rows = stmt
135 .query(params![key_id])
136 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 db_utils::with_rows_extract_all(&mut rows, |row| {
138 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
139 metadata.insert(
140 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700141 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142 .context("Failed to read KeyMetaEntry.")?,
143 );
144 Ok(())
145 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000146 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800147
148 Ok(Self { data: metadata })
149 }
150
151 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
152 let mut stmt = tx
153 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000154 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800155 VALUES (?, ?, ?);",
156 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000157 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158
159 let iter = self.data.iter();
160 for (tag, entry) in iter {
161 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000162 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800163 })?;
164 }
165 Ok(())
166 }
167}
168
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800169impl_metadata!(
170 /// A set of metadata for key blobs.
171 #[derive(Debug, Default, Eq, PartialEq)]
172 pub struct BlobMetaData;
173 /// A metadata entry for key blobs.
174 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
175 pub enum BlobMetaEntry {
176 /// If present, indicates that the blob is encrypted with another key or a key derived
177 /// from a password.
178 EncryptedBy(EncryptedBy) with accessor encrypted_by,
179 /// If the blob is password encrypted this field is set to the
180 /// salt used for the key derivation.
181 Salt(Vec<u8>) with accessor salt,
182 /// If the blob is encrypted, this field is set to the initialization vector.
183 Iv(Vec<u8>) with accessor iv,
184 /// If the blob is encrypted, this field holds the AEAD TAG.
185 AeadTag(Vec<u8>) with accessor aead_tag,
186 /// The uuid of the owning KeyMint instance.
187 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700188 /// If the key is ECDH encrypted, this is the ephemeral public key
189 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000190 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
191 /// of that key
192 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800193 // --- ADD NEW META DATA FIELDS HERE ---
194 // For backwards compatibility add new entries only to
195 // end of this list and above this comment.
196 };
197);
198
199impl BlobMetaData {
200 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
201 let mut stmt = tx
202 .prepare(
203 "SELECT tag, data from persistent.blobmetadata
204 WHERE blobentryid = ?;",
205 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000206 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800207
208 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
209
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000210 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800211 db_utils::with_rows_extract_all(&mut rows, |row| {
212 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
213 metadata.insert(
214 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700215 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800216 .context("Failed to read BlobMetaEntry.")?,
217 );
218 Ok(())
219 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000220 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221
222 Ok(Self { data: metadata })
223 }
224
225 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
226 let mut stmt = tx
227 .prepare(
228 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
229 VALUES (?, ?, ?);",
230 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000231 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800232
233 let iter = self.data.iter();
234 for (tag, entry) in iter {
235 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000236 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800237 })?;
238 }
239 Ok(())
240 }
241}
242
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800243/// Indicates the type of the keyentry.
244#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
245pub enum KeyType {
246 /// This is a client key type. These keys are created or imported through the Keystore 2.0
247 /// AIDL interface android.system.keystore2.
248 Client,
249 /// This is a super key type. These keys are created by keystore itself and used to encrypt
250 /// other key blobs to provide LSKF binding.
251 Super,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800252}
253
254impl ToSql for KeyType {
255 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
256 Ok(ToSqlOutput::Owned(Value::Integer(match self {
257 KeyType::Client => 0,
258 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800259 })))
260 }
261}
262
263impl FromSql for KeyType {
264 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
265 match i64::column_result(value)? {
266 0 => Ok(KeyType::Client),
267 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800268 v => Err(FromSqlError::OutOfRange(v)),
269 }
270 }
271}
272
Max Bires8e93d2b2021-01-14 13:17:59 -0800273/// Uuid representation that can be stored in the database.
274/// Right now it can only be initialized from SecurityLevel.
275/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
276#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
277pub struct Uuid([u8; 16]);
278
279impl Deref for Uuid {
280 type Target = [u8; 16];
281
282 fn deref(&self) -> &Self::Target {
283 &self.0
284 }
285}
286
287impl From<SecurityLevel> for Uuid {
288 fn from(sec_level: SecurityLevel) -> Self {
289 Self((sec_level.0 as u128).to_be_bytes())
290 }
291}
292
293impl ToSql for Uuid {
294 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
295 self.0.to_sql()
296 }
297}
298
299impl FromSql for Uuid {
300 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
301 let blob = Vec::<u8>::column_result(value)?;
302 if blob.len() != 16 {
303 return Err(FromSqlError::OutOfRange(blob.len() as i64));
304 }
305 let mut arr = [0u8; 16];
306 arr.copy_from_slice(&blob);
307 Ok(Self(arr))
308 }
309}
310
311/// Key entries that are not associated with any KeyMint instance, such as pure certificate
312/// entries are associated with this UUID.
313pub static KEYSTORE_UUID: Uuid = Uuid([
314 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
315]);
316
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800317/// Indicates how the sensitive part of this key blob is encrypted.
318#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
319pub enum EncryptedBy {
320 /// The keyblob is encrypted by a user password.
321 /// In the database this variant is represented as NULL.
322 Password,
323 /// The keyblob is encrypted by another key with wrapped key id.
324 /// In the database this variant is represented as non NULL value
325 /// that is convertible to i64, typically NUMERIC.
326 KeyId(i64),
327}
328
329impl ToSql for EncryptedBy {
330 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
331 match self {
332 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
333 Self::KeyId(id) => id.to_sql(),
334 }
335 }
336}
337
338impl FromSql for EncryptedBy {
339 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
340 match value {
341 ValueRef::Null => Ok(Self::Password),
342 _ => Ok(Self::KeyId(i64::column_result(value)?)),
343 }
344 }
345}
346
347/// A database representation of wall clock time. DateTime stores unix epoch time as
348/// i64 in milliseconds.
349#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
350pub struct DateTime(i64);
351
352/// Error type returned when creating DateTime or converting it from and to
353/// SystemTime.
354#[derive(thiserror::Error, Debug)]
355pub enum DateTimeError {
356 /// This is returned when SystemTime and Duration computations fail.
357 #[error(transparent)]
358 SystemTimeError(#[from] SystemTimeError),
359
360 /// This is returned when type conversions fail.
361 #[error(transparent)]
362 TypeConversion(#[from] std::num::TryFromIntError),
363
364 /// This is returned when checked time arithmetic failed.
365 #[error("Time arithmetic failed.")]
366 TimeArithmetic,
367}
368
369impl DateTime {
370 /// Constructs a new DateTime object denoting the current time. This may fail during
371 /// conversion to unix epoch time and during conversion to the internal i64 representation.
372 pub fn now() -> Result<Self, DateTimeError> {
373 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
374 }
375
376 /// Constructs a new DateTime object from milliseconds.
377 pub fn from_millis_epoch(millis: i64) -> Self {
378 Self(millis)
379 }
380
381 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700382 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800383 self.0
384 }
385
386 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700387 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800388 self.0 / 1000
389 }
390}
391
392impl ToSql for DateTime {
393 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
394 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
395 }
396}
397
398impl FromSql for DateTime {
399 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
400 Ok(Self(i64::column_result(value)?))
401 }
402}
403
404impl TryInto<SystemTime> for DateTime {
405 type Error = DateTimeError;
406
407 fn try_into(self) -> Result<SystemTime, Self::Error> {
408 // We want to construct a SystemTime representation equivalent to self, denoting
409 // a point in time THEN, but we cannot set the time directly. We can only construct
410 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
411 // and between EPOCH and THEN. With this common reference we can construct the
412 // duration between NOW and THEN which we can add to our SystemTime representation
413 // of NOW to get a SystemTime representation of THEN.
414 // Durations can only be positive, thus the if statement below.
415 let now = SystemTime::now();
416 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
417 let then_epoch = Duration::from_millis(self.0.try_into()?);
418 Ok(if now_epoch > then_epoch {
419 // then = now - (now_epoch - then_epoch)
420 now_epoch
421 .checked_sub(then_epoch)
422 .and_then(|d| now.checked_sub(d))
423 .ok_or(DateTimeError::TimeArithmetic)?
424 } else {
425 // then = now + (then_epoch - now_epoch)
426 then_epoch
427 .checked_sub(now_epoch)
428 .and_then(|d| now.checked_add(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 })
431 }
432}
433
434impl TryFrom<SystemTime> for DateTime {
435 type Error = DateTimeError;
436
437 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
438 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
439 }
440}
441
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800442#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
443enum KeyLifeCycle {
444 /// Existing keys have a key ID but are not fully populated yet.
445 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
446 /// them to Unreferenced for garbage collection.
447 Existing,
448 /// A live key is fully populated and usable by clients.
449 Live,
450 /// An unreferenced key is scheduled for garbage collection.
451 Unreferenced,
452}
453
454impl ToSql for KeyLifeCycle {
455 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
456 match self {
457 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
458 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
459 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
460 }
461 }
462}
463
464impl FromSql for KeyLifeCycle {
465 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
466 match i64::column_result(value)? {
467 0 => Ok(KeyLifeCycle::Existing),
468 1 => Ok(KeyLifeCycle::Live),
469 2 => Ok(KeyLifeCycle::Unreferenced),
470 v => Err(FromSqlError::OutOfRange(v)),
471 }
472 }
473}
474
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700475/// Keys have a KeyMint blob component and optional public certificate and
476/// certificate chain components.
477/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
478/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800479#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700480pub struct KeyEntryLoadBits(u32);
481
482impl KeyEntryLoadBits {
483 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
484 pub const NONE: KeyEntryLoadBits = Self(0);
485 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
486 pub const KM: KeyEntryLoadBits = Self(1);
487 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
488 pub const PUBLIC: KeyEntryLoadBits = Self(2);
489 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
490 pub const BOTH: KeyEntryLoadBits = Self(3);
491
492 /// Returns true if this object indicates that the public components shall be loaded.
493 pub const fn load_public(&self) -> bool {
494 self.0 & Self::PUBLIC.0 != 0
495 }
496
497 /// Returns true if the object indicates that the KeyMint component shall be loaded.
498 pub const fn load_km(&self) -> bool {
499 self.0 & Self::KM.0 != 0
500 }
501}
502
Janis Danisevskisaec14592020-11-12 09:41:49 -0800503lazy_static! {
504 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
505}
506
507struct KeyIdLockDb {
508 locked_keys: Mutex<HashSet<i64>>,
509 cond_var: Condvar,
510}
511
512/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
513/// from the database a second time. Most functions manipulating the key blob database
514/// require a KeyIdGuard.
515#[derive(Debug)]
516pub struct KeyIdGuard(i64);
517
518impl KeyIdLockDb {
519 fn new() -> Self {
520 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
521 }
522
523 /// This function blocks until an exclusive lock for the given key entry id can
524 /// be acquired. It returns a guard object, that represents the lifecycle of the
525 /// acquired lock.
526 pub fn get(&self, key_id: i64) -> KeyIdGuard {
527 let mut locked_keys = self.locked_keys.lock().unwrap();
528 while locked_keys.contains(&key_id) {
529 locked_keys = self.cond_var.wait(locked_keys).unwrap();
530 }
531 locked_keys.insert(key_id);
532 KeyIdGuard(key_id)
533 }
534
535 /// This function attempts to acquire an exclusive lock on a given key id. If the
536 /// given key id is already taken the function returns None immediately. If a lock
537 /// can be acquired this function returns a guard object, that represents the
538 /// lifecycle of the acquired lock.
539 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
540 let mut locked_keys = self.locked_keys.lock().unwrap();
541 if locked_keys.insert(key_id) {
542 Some(KeyIdGuard(key_id))
543 } else {
544 None
545 }
546 }
547}
548
549impl KeyIdGuard {
550 /// Get the numeric key id of the locked key.
551 pub fn id(&self) -> i64 {
552 self.0
553 }
554}
555
556impl Drop for KeyIdGuard {
557 fn drop(&mut self) {
558 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
559 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800560 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800561 KEY_ID_LOCK.cond_var.notify_all();
562 }
563}
564
Max Bires8e93d2b2021-01-14 13:17:59 -0800565/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700566#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800567pub struct CertificateInfo {
568 cert: Option<Vec<u8>>,
569 cert_chain: Option<Vec<u8>>,
570}
571
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800572/// This type represents a Blob with its metadata and an optional superseded blob.
573#[derive(Debug)]
574pub struct BlobInfo<'a> {
575 blob: &'a [u8],
576 metadata: &'a BlobMetaData,
577 /// Superseded blobs are an artifact of legacy import. In some rare occasions
578 /// the key blob needs to be upgraded during import. In that case two
579 /// blob are imported, the superseded one will have to be imported first,
580 /// so that the garbage collector can reap it.
581 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
582}
583
584impl<'a> BlobInfo<'a> {
585 /// Create a new instance of blob info with blob and corresponding metadata
586 /// and no superseded blob info.
587 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
588 Self { blob, metadata, superseded_blob: None }
589 }
590
591 /// Create a new instance of blob info with blob and corresponding metadata
592 /// as well as superseded blob info.
593 pub fn new_with_superseded(
594 blob: &'a [u8],
595 metadata: &'a BlobMetaData,
596 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
597 ) -> Self {
598 Self { blob, metadata, superseded_blob }
599 }
600}
601
Max Bires8e93d2b2021-01-14 13:17:59 -0800602impl CertificateInfo {
603 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
604 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
605 Self { cert, cert_chain }
606 }
607
608 /// Take the cert
609 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
610 self.cert.take()
611 }
612
613 /// Take the cert chain
614 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
615 self.cert_chain.take()
616 }
617}
618
Max Bires2b2e6562020-09-22 11:22:36 -0700619/// This type represents a certificate chain with a private key corresponding to the leaf
620/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700621pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800622 /// A KM key blob
623 pub private_key: ZVec,
624 /// A batch cert for private_key
625 pub batch_cert: Vec<u8>,
626 /// A full certificate chain from root signing authority to private_key, including batch_cert
627 /// for convenience.
628 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700629}
630
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631/// This type represents a Keystore 2.0 key entry.
632/// An entry has a unique `id` by which it can be found in the database.
633/// It has a security level field, key parameters, and three optional fields
634/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800635#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700636pub struct KeyEntry {
637 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800638 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700639 cert: Option<Vec<u8>>,
640 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800641 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700642 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800643 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800644 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700645}
646
647impl KeyEntry {
648 /// Returns the unique id of the Key entry.
649 pub fn id(&self) -> i64 {
650 self.id
651 }
652 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800653 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
654 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800656 /// Extracts the Optional KeyMint blob including its metadata.
657 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
658 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700659 }
660 /// Exposes the optional public certificate.
661 pub fn cert(&self) -> &Option<Vec<u8>> {
662 &self.cert
663 }
664 /// Extracts the optional public certificate.
665 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
666 self.cert.take()
667 }
668 /// Exposes the optional public certificate chain.
669 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
670 &self.cert_chain
671 }
672 /// Extracts the optional public certificate_chain.
673 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
674 self.cert_chain.take()
675 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800676 /// Returns the uuid of the owning KeyMint instance.
677 pub fn km_uuid(&self) -> &Uuid {
678 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700679 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700680 /// Exposes the key parameters of this key entry.
681 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
682 &self.parameters
683 }
684 /// Consumes this key entry and extracts the keyparameters from it.
685 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
686 self.parameters
687 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800688 /// Exposes the key metadata of this key entry.
689 pub fn metadata(&self) -> &KeyMetaData {
690 &self.metadata
691 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800692 /// This returns true if the entry is a pure certificate entry with no
693 /// private key component.
694 pub fn pure_cert(&self) -> bool {
695 self.pure_cert
696 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000697 /// Consumes this key entry and extracts the keyparameters and metadata from it.
698 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
699 (self.parameters, self.metadata)
700 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700701}
702
703/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800704#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700705pub struct SubComponentType(u32);
706impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800707 /// Persistent identifier for a key blob.
708 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700709 /// Persistent identifier for a certificate blob.
710 pub const CERT: SubComponentType = Self(1);
711 /// Persistent identifier for a certificate chain blob.
712 pub const CERT_CHAIN: SubComponentType = Self(2);
713}
714
715impl ToSql for SubComponentType {
716 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
717 self.0.to_sql()
718 }
719}
720
721impl FromSql for SubComponentType {
722 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
723 Ok(Self(u32::column_result(value)?))
724 }
725}
726
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800727/// This trait is private to the database module. It is used to convey whether or not the garbage
728/// collector shall be invoked after a database access. All closures passed to
729/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
730/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
731/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
732/// `.need_gc()`.
733trait DoGc<T> {
734 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
735
736 fn no_gc(self) -> Result<(bool, T)>;
737
738 fn need_gc(self) -> Result<(bool, T)>;
739}
740
741impl<T> DoGc<T> for Result<T> {
742 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
743 self.map(|r| (need_gc, r))
744 }
745
746 fn no_gc(self) -> Result<(bool, T)> {
747 self.do_gc(false)
748 }
749
750 fn need_gc(self) -> Result<(bool, T)> {
751 self.do_gc(true)
752 }
753}
754
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700755/// KeystoreDB wraps a connection to an SQLite database and tracks its
756/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700757pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700758 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700759 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700760 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700761}
762
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000763/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000764/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000765#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000766pub struct BootTime(i64);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000767
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000768impl BootTime {
769 /// Constructs a new BootTime
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000770 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000771 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000772 }
773
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000774 /// Returns the value of BootTime in milliseconds as i64
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000775 pub fn milliseconds(&self) -> i64 {
776 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000777 }
778
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000779 /// Returns the integer value of BootTime as i64
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000780 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000781 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000782 }
783
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800784 /// Like i64::checked_sub.
785 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
786 self.0.checked_sub(other.0).map(Self)
787 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788}
789
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000790impl ToSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000791 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
792 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
793 }
794}
795
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000796impl FromSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000797 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
798 Ok(Self(i64::column_result(value)?))
799 }
800}
801
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000802/// This struct encapsulates the information to be stored in the database about the auth tokens
803/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700804#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000805pub struct AuthTokenEntry {
806 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000807 // Time received in milliseconds
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000808 time_received: BootTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000809}
810
811impl AuthTokenEntry {
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000812 fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000813 AuthTokenEntry { auth_token, time_received }
814 }
815
816 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800817 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800819 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000820 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000821 })
822 }
823
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000824 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800825 pub fn auth_token(&self) -> &HardwareAuthToken {
826 &self.auth_token
827 }
828
829 /// Returns the auth token wrapped by the AuthTokenEntry
830 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000831 self.auth_token
832 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800833
834 /// Returns the time that this auth token was received.
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000835 pub fn time_received(&self) -> BootTime {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800836 self.time_received
837 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000838
839 /// Returns the challenge value of the auth token.
840 pub fn challenge(&self) -> i64 {
841 self.auth_token.challenge
842 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000843}
844
Joel Galenson26f4d012020-07-17 14:57:21 -0700845impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800846 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700847 const CURRENT_DB_VERSION: u32 = 1;
848 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800849
Seth Moore78c091f2021-04-09 21:38:30 +0000850 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700851 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000852
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700853 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800854 /// files persistent.sqlite and perboot.sqlite in the given directory.
855 /// It also attempts to initialize all of the tables.
856 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700857 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700858 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700859 let _wp = wd::watch_millis("KeystoreDB::new", 500);
860
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700861 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700862 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800863
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700864 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800865 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700866 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000867 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800868 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800869 })?;
870 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700871 }
872
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700873 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
874 // cryptographic binding to the boot level keys was implemented.
875 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
876 tx.execute(
877 "UPDATE persistent.keyentry SET state = ?
878 WHERE
879 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
880 AND
881 id NOT IN (
882 SELECT keyentryid FROM persistent.blobentry
883 WHERE id IN (
884 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
885 )
886 );",
887 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
888 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000889 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700890 Ok(1)
891 }
892
Janis Danisevskis66784c42021-01-27 08:40:25 -0800893 fn init_tables(tx: &Transaction) -> Result<()> {
894 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700895 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700896 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800897 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700898 domain INTEGER,
899 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800900 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800901 state INTEGER,
902 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000903 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700904 )
905 .context("Failed to initialize \"keyentry\" table.")?;
906
Janis Danisevskis66784c42021-01-27 08:40:25 -0800907 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800908 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
909 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000910 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800911 )
912 .context("Failed to create index keyentry_id_index.")?;
913
914 tx.execute(
915 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
916 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000917 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800918 )
919 .context("Failed to create index keyentry_domain_namespace_index.")?;
920
921 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700922 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
923 id INTEGER PRIMARY KEY,
924 subcomponent_type INTEGER,
925 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800926 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000927 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700928 )
929 .context("Failed to initialize \"blobentry\" table.")?;
930
Janis Danisevskis66784c42021-01-27 08:40:25 -0800931 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800932 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
933 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000934 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800935 )
936 .context("Failed to create index blobentry_keyentryid_index.")?;
937
938 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800939 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
940 id INTEGER PRIMARY KEY,
941 blobentryid INTEGER,
942 tag INTEGER,
943 data ANY,
944 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000945 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800946 )
947 .context("Failed to initialize \"blobmetadata\" table.")?;
948
949 tx.execute(
950 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
951 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000952 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800953 )
954 .context("Failed to create index blobmetadata_blobentryid_index.")?;
955
956 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700957 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000958 keyentryid INTEGER,
959 tag INTEGER,
960 data ANY,
961 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000962 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700963 )
964 .context("Failed to initialize \"keyparameter\" table.")?;
965
Janis Danisevskis66784c42021-01-27 08:40:25 -0800966 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800967 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
968 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000969 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800970 )
971 .context("Failed to create index keyparameter_keyentryid_index.")?;
972
973 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800974 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
975 keyentryid INTEGER,
976 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000977 data ANY,
978 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000979 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800980 )
981 .context("Failed to initialize \"keymetadata\" table.")?;
982
Janis Danisevskis66784c42021-01-27 08:40:25 -0800983 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800984 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
985 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000986 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800987 )
988 .context("Failed to create index keymetadata_keyentryid_index.")?;
989
990 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800991 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700992 id INTEGER UNIQUE,
993 grantee INTEGER,
994 keyentryid INTEGER,
995 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000996 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700997 )
998 .context("Failed to initialize \"grant\" table.")?;
999
Joel Galenson0891bc12020-07-20 10:37:03 -07001000 Ok(())
1001 }
1002
Seth Moore472fcbb2021-05-12 10:07:51 -07001003 fn make_persistent_path(db_root: &Path) -> Result<String> {
1004 // Build the path to the sqlite file.
1005 let mut persistent_path = db_root.to_path_buf();
1006 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1007
1008 // Now convert them to strings prefixed with "file:"
1009 let mut persistent_path_str = "file:".to_owned();
1010 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1011
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001012 // Connect to database in specific mode
1013 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1014 "?journal_mode=WAL".to_owned()
1015 } else {
1016 "?journal_mode=DELETE".to_owned()
1017 };
1018 persistent_path_str.push_str(&persistent_path_mode);
1019
Seth Moore472fcbb2021-05-12 10:07:51 -07001020 Ok(persistent_path_str)
1021 }
1022
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001023 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001024 let conn =
1025 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1026
Janis Danisevskis66784c42021-01-27 08:40:25 -08001027 loop {
1028 if let Err(e) = conn
1029 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1030 .context("Failed to attach database persistent.")
1031 {
1032 if Self::is_locked_error(&e) {
1033 std::thread::sleep(std::time::Duration::from_micros(500));
1034 continue;
1035 } else {
1036 return Err(e);
1037 }
1038 }
1039 break;
1040 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001041
Matthew Maurer4fb19112021-05-06 15:40:44 -07001042 // Drop the cache size from default (2M) to 0.5M
1043 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1044 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001045
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001046 Ok(conn)
1047 }
1048
Seth Moore78c091f2021-04-09 21:38:30 +00001049 fn do_table_size_query(
1050 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001051 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001052 query: &str,
1053 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001054 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001055 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001056 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001057 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001058 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001059 })
1060 .no_gc()
1061 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001062 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001063 }
1064
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001065 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001066 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001067 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001068 "SELECT page_count * page_size, freelist_count * page_size
1069 FROM pragma_page_count('persistent'),
1070 pragma_page_size('persistent'),
1071 persistent.pragma_freelist_count();",
1072 &[],
1073 )
1074 }
1075
1076 fn get_table_size(
1077 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001078 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001079 schema: &str,
1080 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001081 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001082 self.do_table_size_query(
1083 storage_type,
1084 "SELECT pgsize,unused FROM dbstat(?1)
1085 WHERE name=?2 AND aggregate=TRUE;",
1086 &[schema, table],
1087 )
1088 }
1089
1090 /// Fetches a storage statisitics atom for a given storage type. For storage
1091 /// types that map to a table, information about the table's storage is
1092 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001093 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001094 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1095
Seth Moore78c091f2021-04-09 21:38:30 +00001096 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001097 MetricsStorage::DATABASE => self.get_total_size(),
1098 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001099 self.get_table_size(storage_type, "persistent", "keyentry")
1100 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001101 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001102 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1103 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001104 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001105 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1106 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001108 self.get_table_size(storage_type, "persistent", "blobentry")
1109 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001110 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001111 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "keyparameter")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001120 self.get_table_size(storage_type, "persistent", "keymetadata")
1121 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001123 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1124 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001125 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1126 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001127 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1128 // reportable
1129 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001131 storage_type,
1132 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001133 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001134 unused_size: 0,
1135 })
Seth Moore78c091f2021-04-09 21:38:30 +00001136 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001137 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001138 self.get_table_size(storage_type, "persistent", "blobmetadata")
1139 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001140 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001141 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1142 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001143 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001144 }
1145 }
1146
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001147 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001148 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1149 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001150 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1151 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001152 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 blob_ids_to_delete: &[i64],
1155 max_blobs: usize,
1156 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001157 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001158 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001159 // Delete the given blobs.
1160 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 tx.execute(
1162 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001163 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001165 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001166 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001167 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001168 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001169
1170 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1171
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1173 let result: Vec<(i64, Vec<u8>)> = {
1174 let mut stmt = tx
1175 .prepare(
1176 "SELECT id, blob FROM persistent.blobentry
1177 WHERE subcomponent_type = ?
1178 AND (
1179 id NOT IN (
1180 SELECT MAX(id) FROM persistent.blobentry
1181 WHERE subcomponent_type = ?
1182 GROUP BY keyentryid, subcomponent_type
1183 )
1184 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1185 ) LIMIT ?;",
1186 )
1187 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001188
Janis Danisevskis3395f862021-05-06 10:54:17 -07001189 let rows = stmt
1190 .query_map(
1191 params![
1192 SubComponentType::KEY_BLOB,
1193 SubComponentType::KEY_BLOB,
1194 max_blobs as i64,
1195 ],
1196 |row| Ok((row.get(0)?, row.get(1)?)),
1197 )
1198 .context("Trying to query superseded blob.")?;
1199
1200 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1201 .context("Trying to extract superseded blobs.")?
1202 };
1203
1204 let result = result
1205 .into_iter()
1206 .map(|(blob_id, blob)| {
1207 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1208 })
1209 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1210 .context("Trying to load blob metadata.")?;
1211 if !result.is_empty() {
1212 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001213 }
1214
1215 // We did not find any superseded key blob, so let's remove other superseded blob in
1216 // one transaction.
1217 tx.execute(
1218 "DELETE FROM persistent.blobentry
1219 WHERE NOT subcomponent_type = ?
1220 AND (
1221 id NOT IN (
1222 SELECT MAX(id) FROM persistent.blobentry
1223 WHERE NOT subcomponent_type = ?
1224 GROUP BY keyentryid, subcomponent_type
1225 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1226 );",
1227 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1228 )
1229 .context("Trying to purge superseded blobs.")?;
1230
Janis Danisevskis3395f862021-05-06 10:54:17 -07001231 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001232 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001233 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001234 }
1235
1236 /// This maintenance function should be called only once before the database is used for the
1237 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1238 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1239 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1240 /// Keystore crashed at some point during key generation. Callers may want to log such
1241 /// occurrences.
1242 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1243 /// it to `KeyLifeCycle::Live` may have grants.
1244 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001245 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1246
Janis Danisevskis66784c42021-01-27 08:40:25 -08001247 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1248 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001249 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1250 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1251 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001252 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001253 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001254 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001255 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001256 }
1257
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001258 /// Checks if a key exists with given key type and key descriptor properties.
1259 pub fn key_exists(
1260 &mut self,
1261 domain: Domain,
1262 nspace: i64,
1263 alias: &str,
1264 key_type: KeyType,
1265 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001266 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1267
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001268 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1269 let key_descriptor =
1270 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001271 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001272 match result {
1273 Ok(_) => Ok(true),
1274 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1275 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001276 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001277 },
1278 }
1279 .no_gc()
1280 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001281 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001282 }
1283
Hasini Gunasingheda895552021-01-27 19:34:37 +00001284 /// Stores a super key in the database.
1285 pub fn store_super_key(
1286 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001287 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001288 key_type: &SuperKeyType,
1289 blob: &[u8],
1290 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001291 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001293 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1294
Hasini Gunasingheda895552021-01-27 19:34:37 +00001295 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1296 let key_id = Self::insert_with_retry(|id| {
1297 tx.execute(
1298 "INSERT into persistent.keyentry
1299 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001300 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 params![
1302 id,
1303 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001304 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001305 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001306 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 KeyLifeCycle::Live,
1308 &KEYSTORE_UUID,
1309 ],
1310 )
1311 })
1312 .context("Failed to insert into keyentry table.")?;
1313
Paul Crowley8d5b2532021-03-19 10:53:07 -07001314 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1315
Hasini Gunasingheda895552021-01-27 19:34:37 +00001316 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001317 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001318 key_id,
1319 SubComponentType::KEY_BLOB,
1320 Some(blob),
1321 Some(blob_metadata),
1322 )
1323 .context("Failed to store key blob.")?;
1324
1325 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1326 .context("Trying to load key components.")
1327 .no_gc()
1328 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001329 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001330 }
1331
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001332 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001333 pub fn load_super_key(
1334 &mut self,
1335 key_type: &SuperKeyType,
1336 user_id: u32,
1337 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001338 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1339
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001340 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1341 let key_descriptor = KeyDescriptor {
1342 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001343 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001344 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001345 blob: None,
1346 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001347 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001348 match id {
1349 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001350 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001351 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001352 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1353 }
1354 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1355 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001356 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001357 },
1358 }
1359 .no_gc()
1360 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001361 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001362 }
1363
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001364 /// Atomically loads a key entry and associated metadata or creates it using the
1365 /// callback create_new_key callback. The callback is called during a database
1366 /// transaction. This means that implementers should be mindful about using
1367 /// blocking operations such as IPC or grabbing mutexes.
1368 pub fn get_or_create_key_with<F>(
1369 &mut self,
1370 domain: Domain,
1371 namespace: i64,
1372 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001373 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001374 create_new_key: F,
1375 ) -> Result<(KeyIdGuard, KeyEntry)>
1376 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001377 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001378 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001379 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1380
Janis Danisevskis66784c42021-01-27 08:40:25 -08001381 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1382 let id = {
1383 let mut stmt = tx
1384 .prepare(
1385 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001386 WHERE
1387 key_type = ?
1388 AND domain = ?
1389 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001390 AND alias = ?
1391 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001392 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001393 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001394 let mut rows = stmt
1395 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001396 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001397
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 db_utils::with_rows_extract_one(&mut rows, |row| {
1399 Ok(match row {
1400 Some(r) => r.get(0).context("Failed to unpack id.")?,
1401 None => None,
1402 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001404 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001405 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001406
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 let (id, entry) = match id {
1408 Some(id) => (
1409 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001410 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001411 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001412
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 None => {
1414 let id = Self::insert_with_retry(|id| {
1415 tx.execute(
1416 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001417 (id, key_type, domain, namespace, alias, state, km_uuid)
1418 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 params![
1420 id,
1421 KeyType::Super,
1422 domain.0,
1423 namespace,
1424 alias,
1425 KeyLifeCycle::Live,
1426 km_uuid,
1427 ],
1428 )
1429 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001430 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001431
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001432 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001433 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001434 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001435 id,
1436 SubComponentType::KEY_BLOB,
1437 Some(&blob),
1438 Some(&metadata),
1439 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001440 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001441 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001442 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001443 KeyEntry {
1444 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001445 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001446 pure_cert: false,
1447 ..Default::default()
1448 },
1449 )
1450 }
1451 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001452 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001453 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001454 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001455 }
1456
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001457 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001458 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1459 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001460 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1461 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001462 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001463 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001465 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001466 .conn
1467 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001468 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001469 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1470 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001471 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001472 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001473 });
1474 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001475 Ok(result) => break Ok(result),
1476 Err(e) => {
1477 if Self::is_locked_error(&e) {
1478 std::thread::sleep(std::time::Duration::from_micros(500));
1479 continue;
1480 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001481 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001482 }
1483 }
1484 }
1485 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001486 .map(|(need_gc, result)| {
1487 if need_gc {
1488 if let Some(ref gc) = self.gc {
1489 gc.notify_gc();
1490 }
1491 }
1492 result
1493 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001494 }
1495
1496 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001497 matches!(
1498 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1499 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1500 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1501 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001502 }
1503
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001504 /// Creates a new key entry and allocates a new randomized id for the new key.
1505 /// The key id gets associated with a domain and namespace but not with an alias.
1506 /// To complete key generation `rebind_alias` should be called after all of the
1507 /// key artifacts, i.e., blobs and parameters have been associated with the new
1508 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1509 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001510 pub fn create_key_entry(
1511 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001512 domain: &Domain,
1513 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001514 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001515 km_uuid: &Uuid,
1516 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001517 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1518
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001519 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001520 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001521 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001522 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001523 }
1524
1525 fn create_key_entry_internal(
1526 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001527 domain: &Domain,
1528 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001529 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001530 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001531 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001532 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001533 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001534 _ => {
1535 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001536 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001537 }
1538 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001539 Ok(KEY_ID_LOCK.get(
1540 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001541 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001542 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001543 (id, key_type, domain, namespace, alias, state, km_uuid)
1544 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001545 params![
1546 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001547 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001548 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001549 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001550 KeyLifeCycle::Existing,
1551 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001553 )
1554 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001555 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001556 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001557 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001558
Janis Danisevskis377d1002021-01-27 19:07:48 -08001559 /// Set a new blob and associates it with the given key id. Each blob
1560 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001561 /// Each key can have one of each sub component type associated. If more
1562 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001563 /// will get garbage collected.
1564 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1565 /// removed by setting blob to None.
1566 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001567 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001568 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001569 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001570 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001571 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001572 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001573 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1574
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001575 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001576 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001577 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001578 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001579 }
1580
Janis Danisevskiseed69842021-02-18 20:04:10 -08001581 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1582 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1583 /// We use this to insert key blobs into the database which can then be garbage collected
1584 /// lazily by the key garbage collector.
1585 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001586 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1587
Janis Danisevskiseed69842021-02-18 20:04:10 -08001588 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1589 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001590 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001591 Self::UNASSIGNED_KEY_ID,
1592 SubComponentType::KEY_BLOB,
1593 Some(blob),
1594 Some(blob_metadata),
1595 )
1596 .need_gc()
1597 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001598 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001599 }
1600
Janis Danisevskis377d1002021-01-27 19:07:48 -08001601 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001602 tx: &Transaction,
1603 key_id: i64,
1604 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001605 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001606 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001607 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001608 match (blob, sc_type) {
1609 (Some(blob), _) => {
1610 tx.execute(
1611 "INSERT INTO persistent.blobentry
1612 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1613 params![sc_type, key_id, blob],
1614 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001615 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001616 if let Some(blob_metadata) = blob_metadata {
1617 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001618 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001619 row.get(0)
1620 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001621 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001622 blob_metadata
1623 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001624 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001625 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001626 }
1627 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1628 tx.execute(
1629 "DELETE FROM persistent.blobentry
1630 WHERE subcomponent_type = ? AND keyentryid = ?;",
1631 params![sc_type, key_id],
1632 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001633 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001634 }
1635 (None, _) => {
1636 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001637 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001638 }
1639 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001640 Ok(())
1641 }
1642
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001643 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1644 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001645 #[cfg(test)]
1646 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001647 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001648 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001649 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001650 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001651 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001652
Janis Danisevskis66784c42021-01-27 08:40:25 -08001653 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001654 tx: &Transaction,
1655 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001656 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001657 ) -> Result<()> {
1658 let mut stmt = tx
1659 .prepare(
1660 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1661 VALUES (?, ?, ?, ?);",
1662 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001663 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001664
Janis Danisevskis66784c42021-01-27 08:40:25 -08001665 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001666 stmt.insert(params![
1667 key_id.0,
1668 p.get_tag().0,
1669 p.key_parameter_value(),
1670 p.security_level().0
1671 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001672 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001673 }
1674 Ok(())
1675 }
1676
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001677 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001678 #[cfg(test)]
1679 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001680 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001681 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001682 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001683 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001684 }
1685
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001686 /// Updates the alias column of the given key id `newid` with the given alias,
1687 /// and atomically, removes the alias, domain, and namespace from another row
1688 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001689 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1690 /// collector.
1691 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001692 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001693 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001694 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001695 domain: &Domain,
1696 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001697 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001698 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001699 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001700 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001701 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001702 return Err(KsError::sys())
1703 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001704 }
1705 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001706 let updated = tx
1707 .execute(
1708 "UPDATE persistent.keyentry
1709 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001710 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1711 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001712 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001713 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001714 let result = tx
1715 .execute(
1716 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001717 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001718 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001719 params![
1720 alias,
1721 KeyLifeCycle::Live,
1722 newid.0,
1723 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001724 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001725 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001726 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001727 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001728 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001729 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001730 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001731 return Err(KsError::sys()).context(ks_err!(
1732 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001733 result
1734 ));
1735 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001736 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001737 }
1738
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001739 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1740 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1741 pub fn migrate_key_namespace(
1742 &mut self,
1743 key_id_guard: KeyIdGuard,
1744 destination: &KeyDescriptor,
1745 caller_uid: u32,
1746 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1747 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001748 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1749
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001750 let destination = match destination.domain {
1751 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1752 Domain::SELINUX => (*destination).clone(),
1753 domain => {
1754 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1755 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1756 }
1757 };
1758
1759 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001760 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001761
1762 let alias = destination
1763 .alias
1764 .as_ref()
1765 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001766 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001767
1768 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1769 // Query the destination location. If there is a key, the migration request fails.
1770 if tx
1771 .query_row(
1772 "SELECT id FROM persistent.keyentry
1773 WHERE alias = ? AND domain = ? AND namespace = ?;",
1774 params![alias, destination.domain.0, destination.nspace],
1775 |_| Ok(()),
1776 )
1777 .optional()
1778 .context("Failed to query destination.")?
1779 .is_some()
1780 {
1781 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1782 .context("Target already exists.");
1783 }
1784
1785 let updated = tx
1786 .execute(
1787 "UPDATE persistent.keyentry
1788 SET alias = ?, domain = ?, namespace = ?
1789 WHERE id = ?;",
1790 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1791 )
1792 .context("Failed to update key entry.")?;
1793
1794 if updated != 1 {
1795 return Err(KsError::sys())
1796 .context(format!("Update succeeded, but {} rows were updated.", updated));
1797 }
1798 Ok(()).no_gc()
1799 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001800 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001801 }
1802
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001803 /// Store a new key in a single transaction.
1804 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1805 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001806 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1807 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001808 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001809 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001810 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001811 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001812 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001813 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001814 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001815 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001816 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001817 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001818 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001819 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1820
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001821 let (alias, domain, namespace) = match key {
1822 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1823 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1824 (alias, key.domain, nspace)
1825 }
1826 _ => {
1827 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001828 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001829 }
1830 };
1831 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001832 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001833 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001834 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1835
1836 // In some occasions the key blob is already upgraded during the import.
1837 // In order to make sure it gets properly deleted it is inserted into the
1838 // database here and then immediately replaced by the superseding blob.
1839 // The garbage collector will then subject the blob to deleteKey of the
1840 // KM back end to permanently invalidate the key.
1841 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1842 Self::set_blob_internal(
1843 tx,
1844 key_id.id(),
1845 SubComponentType::KEY_BLOB,
1846 Some(blob),
1847 Some(blob_metadata),
1848 )
1849 .context("Trying to insert superseded key blob.")?;
1850 true
1851 } else {
1852 false
1853 };
1854
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001855 Self::set_blob_internal(
1856 tx,
1857 key_id.id(),
1858 SubComponentType::KEY_BLOB,
1859 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001860 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001861 )
1862 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001863 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001864 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001865 .context("Trying to insert the certificate.")?;
1866 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001867 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001868 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001869 tx,
1870 key_id.id(),
1871 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001872 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001873 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001874 )
1875 .context("Trying to insert the certificate chain.")?;
1876 }
1877 Self::insert_keyparameter_internal(tx, &key_id, params)
1878 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001879 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001880 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001881 .context("Trying to rebind alias.")?
1882 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001883 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001884 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001885 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001886 }
1887
Janis Danisevskis377d1002021-01-27 19:07:48 -08001888 /// Store a new certificate
1889 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1890 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001891 pub fn store_new_certificate(
1892 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001893 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001894 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001895 cert: &[u8],
1896 km_uuid: &Uuid,
1897 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001898 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1899
Janis Danisevskis377d1002021-01-27 19:07:48 -08001900 let (alias, domain, namespace) = match key {
1901 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1902 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1903 (alias, key.domain, nspace)
1904 }
1905 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001906 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1907 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001908 }
1909 };
1910 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001911 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001912 .context("Trying to create new key entry.")?;
1913
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001914 Self::set_blob_internal(
1915 tx,
1916 key_id.id(),
1917 SubComponentType::CERT_CHAIN,
1918 Some(cert),
1919 None,
1920 )
1921 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001922
1923 let mut metadata = KeyMetaData::new();
1924 metadata.add(KeyMetaEntry::CreationDate(
1925 DateTime::now().context("Trying to make creation time.")?,
1926 ));
1927
1928 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1929
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001930 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001931 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001932 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001933 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001934 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001935 }
1936
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001937 // Helper function loading the key_id given the key descriptor
1938 // tuple comprising domain, namespace, and alias.
1939 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001940 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001941 let alias = key
1942 .alias
1943 .as_ref()
1944 .map_or_else(|| Err(KsError::sys()), Ok)
1945 .context("In load_key_entry_id: Alias must be specified.")?;
1946 let mut stmt = tx
1947 .prepare(
1948 "SELECT id FROM persistent.keyentry
1949 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001950 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001951 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001952 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001953 AND alias = ?
1954 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001955 )
1956 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1957 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001958 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001959 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001960 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001961 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001962 .get(0)
1963 .context("Failed to unpack id.")
1964 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001965 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001966 }
1967
1968 /// This helper function completes the access tuple of a key, which is required
1969 /// to perform access control. The strategy depends on the `domain` field in the
1970 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001971 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001972 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001973 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001974 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001975 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001976 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001977 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001978 /// `namespace`.
1979 /// In each case the information returned is sufficient to perform the access
1980 /// check and the key id can be used to load further key artifacts.
1981 fn load_access_tuple(
1982 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001983 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001984 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001985 caller_uid: u32,
1986 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1987 match key.domain {
1988 // Domain App or SELinux. In this case we load the key_id from
1989 // the keyentry database for further loading of key components.
1990 // We already have the full access tuple to perform access control.
1991 // The only distinction is that we use the caller_uid instead
1992 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001993 // Domain::APP.
1994 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001995 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001996 if access_key.domain == Domain::APP {
1997 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001998 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001999 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002000 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002001
2002 Ok((key_id, access_key, None))
2003 }
2004
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002005 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002006 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002007 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002008 let mut stmt = tx
2009 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002010 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002011 WHERE grantee = ? AND id = ? AND
2012 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002013 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002014 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002015 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002016 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002017 .context("Domain:Grant: query failed.")?;
2018 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002019 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002020 let r =
2021 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002022 Ok((
2023 r.get(0).context("Failed to unpack key_id.")?,
2024 r.get(1).context("Failed to unpack access_vector.")?,
2025 ))
2026 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002027 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002028 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002029 }
2030
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002031 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002032 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002033 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002034 let (domain, namespace): (Domain, i64) = {
2035 let mut stmt = tx
2036 .prepare(
2037 "SELECT domain, namespace FROM persistent.keyentry
2038 WHERE
2039 id = ?
2040 AND state = ?;",
2041 )
2042 .context("Domain::KEY_ID: prepare statement failed")?;
2043 let mut rows = stmt
2044 .query(params![key.nspace, KeyLifeCycle::Live])
2045 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002046 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002047 let r =
2048 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002049 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002050 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002051 r.get(1).context("Failed to unpack namespace.")?,
2052 ))
2053 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002054 .context("Domain::KEY_ID.")?
2055 };
2056
2057 // We may use a key by id after loading it by grant.
2058 // In this case we have to check if the caller has a grant for this particular
2059 // key. We can skip this if we already know that the caller is the owner.
2060 // But we cannot know this if domain is anything but App. E.g. in the case
2061 // of Domain::SELINUX we have to speculatively check for grants because we have to
2062 // consult the SEPolicy before we know if the caller is the owner.
2063 let access_vector: Option<KeyPermSet> =
2064 if domain != Domain::APP || namespace != caller_uid as i64 {
2065 let access_vector: Option<i32> = tx
2066 .query_row(
2067 "SELECT access_vector FROM persistent.grant
2068 WHERE grantee = ? AND keyentryid = ?;",
2069 params![caller_uid as i64, key.nspace],
2070 |row| row.get(0),
2071 )
2072 .optional()
2073 .context("Domain::KEY_ID: query grant failed.")?;
2074 access_vector.map(|p| p.into())
2075 } else {
2076 None
2077 };
2078
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002079 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002080 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002081 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002082 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002083
Janis Danisevskis45760022021-01-19 16:34:10 -08002084 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002085 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002086 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002087 }
2088 }
2089
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002090 fn load_blob_components(
2091 key_id: i64,
2092 load_bits: KeyEntryLoadBits,
2093 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002094 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002095 let mut stmt = tx
2096 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002097 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002098 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2099 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002100 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002101
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002102 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002103
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002104 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002105 let mut cert_blob: Option<Vec<u8>> = None;
2106 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002107 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002108 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002109 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002110 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002111 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002112 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2113 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002114 key_blob = Some((
2115 row.get(0).context("Failed to extract key blob id.")?,
2116 row.get(2).context("Failed to extract key blob.")?,
2117 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002118 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002119 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002120 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002121 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002122 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002123 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002124 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002126 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 (SubComponentType::CERT, _, _)
2128 | (SubComponentType::CERT_CHAIN, _, _)
2129 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002130 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2131 }
2132 Ok(())
2133 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002134 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002135
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002136 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2137 Ok(Some((
2138 blob,
2139 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002140 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002141 )))
2142 })?;
2143
2144 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002145 }
2146
2147 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2148 let mut stmt = tx
2149 .prepare(
2150 "SELECT tag, data, security_level from persistent.keyparameter
2151 WHERE keyentryid = ?;",
2152 )
2153 .context("In load_key_parameters: prepare statement failed.")?;
2154
2155 let mut parameters: Vec<KeyParameter> = Vec::new();
2156
2157 let mut rows =
2158 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002159 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002160 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2161 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002162 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002163 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002164 .context("Failed to read KeyParameter.")?,
2165 );
2166 Ok(())
2167 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002168 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002169
2170 Ok(parameters)
2171 }
2172
Qi Wub9433b52020-12-01 14:52:46 +08002173 /// Decrements the usage count of a limited use key. This function first checks whether the
2174 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2175 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2176 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002177 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002178 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2179
Qi Wub9433b52020-12-01 14:52:46 +08002180 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2181 let limit: Option<i32> = tx
2182 .query_row(
2183 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2184 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2185 |row| row.get(0),
2186 )
2187 .optional()
2188 .context("Trying to load usage count")?;
2189
2190 let limit = limit
2191 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2192 .context("The Key no longer exists. Key is exhausted.")?;
2193
2194 tx.execute(
2195 "UPDATE persistent.keyparameter
2196 SET data = data - 1
2197 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2198 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2199 )
2200 .context("Failed to update key usage count.")?;
2201
2202 match limit {
2203 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002204 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002205 .context("Trying to mark limited use key for deletion."),
2206 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002207 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002208 }
2209 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002210 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002211 }
2212
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002213 /// Load a key entry by the given key descriptor.
2214 /// It uses the `check_permission` callback to verify if the access is allowed
2215 /// given the key access tuple read from the database using `load_access_tuple`.
2216 /// With `load_bits` the caller may specify which blobs shall be loaded from
2217 /// the blob database.
2218 pub fn load_key_entry(
2219 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002220 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002221 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002222 load_bits: KeyEntryLoadBits,
2223 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002224 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2225 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002226 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2227
Janis Danisevskis66784c42021-01-27 08:40:25 -08002228 loop {
2229 match self.load_key_entry_internal(
2230 key,
2231 key_type,
2232 load_bits,
2233 caller_uid,
2234 &check_permission,
2235 ) {
2236 Ok(result) => break Ok(result),
2237 Err(e) => {
2238 if Self::is_locked_error(&e) {
2239 std::thread::sleep(std::time::Duration::from_micros(500));
2240 continue;
2241 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002242 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002243 }
2244 }
2245 }
2246 }
2247 }
2248
2249 fn load_key_entry_internal(
2250 &mut self,
2251 key: &KeyDescriptor,
2252 key_type: KeyType,
2253 load_bits: KeyEntryLoadBits,
2254 caller_uid: u32,
2255 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002256 ) -> Result<(KeyIdGuard, KeyEntry)> {
2257 // KEY ID LOCK 1/2
2258 // If we got a key descriptor with a key id we can get the lock right away.
2259 // Otherwise we have to defer it until we know the key id.
2260 let key_id_guard = match key.domain {
2261 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2262 _ => None,
2263 };
2264
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002265 let tx = self
2266 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002267 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002268 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002269
2270 // Load the key_id and complete the access control tuple.
2271 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002272 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273
2274 // Perform access control. It is vital that we return here if the permission is denied.
2275 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002276 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002277
Janis Danisevskisaec14592020-11-12 09:41:49 -08002278 // KEY ID LOCK 2/2
2279 // If we did not get a key id lock by now, it was because we got a key descriptor
2280 // without a key id. At this point we got the key id, so we can try and get a lock.
2281 // However, we cannot block here, because we are in the middle of the transaction.
2282 // So first we try to get the lock non blocking. If that fails, we roll back the
2283 // transaction and block until we get the lock. After we successfully got the lock,
2284 // we start a new transaction and load the access tuple again.
2285 //
2286 // We don't need to perform access control again, because we already established
2287 // that the caller had access to the given key. But we need to make sure that the
2288 // key id still exists. So we have to load the key entry by key id this time.
2289 let (key_id_guard, tx) = match key_id_guard {
2290 None => match KEY_ID_LOCK.try_get(key_id) {
2291 None => {
2292 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002293 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002294
Janis Danisevskisaec14592020-11-12 09:41:49 -08002295 // Block until we have a key id lock.
2296 let key_id_guard = KEY_ID_LOCK.get(key_id);
2297
2298 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002299 let tx = self
2300 .conn
2301 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002302 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002303
2304 Self::load_access_tuple(
2305 &tx,
2306 // This time we have to load the key by the retrieved key id, because the
2307 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002308 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002309 domain: Domain::KEY_ID,
2310 nspace: key_id,
2311 ..Default::default()
2312 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002313 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002314 caller_uid,
2315 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002316 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002317 (key_id_guard, tx)
2318 }
2319 Some(l) => (l, tx),
2320 },
2321 Some(key_id_guard) => (key_id_guard, tx),
2322 };
2323
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002324 let key_entry =
2325 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002326
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002327 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002328
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002329 Ok((key_id_guard, key_entry))
2330 }
2331
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002332 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002333 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002334 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2335 .context("Trying to delete keyentry.")?;
2336 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2337 .context("Trying to delete keymetadata.")?;
2338 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2339 .context("Trying to delete keyparameters.")?;
2340 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2341 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002342 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002343 }
2344
2345 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002346 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002347 pub fn unbind_key(
2348 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002349 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002350 key_type: KeyType,
2351 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002352 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002353 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002354 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2355
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002356 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2357 let (key_id, access_key_descriptor, access_vector) =
2358 Self::load_access_tuple(tx, key, key_type, caller_uid)
2359 .context("Trying to get access tuple.")?;
2360
2361 // Perform access control. It is vital that we return here if the permission is denied.
2362 // So do not touch that '?' at the end.
2363 check_permission(&access_key_descriptor, access_vector)
2364 .context("While checking permission.")?;
2365
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002366 Self::mark_unreferenced(tx, key_id)
2367 .map(|need_gc| (need_gc, ()))
2368 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002369 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002370 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002371 }
2372
Max Bires8e93d2b2021-01-14 13:17:59 -08002373 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2374 tx.query_row(
2375 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2376 params![key_id],
2377 |row| row.get(0),
2378 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002379 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002380 }
2381
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002382 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2383 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2384 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002385 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2386
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002387 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002388 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002389 }
2390 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2391 tx.execute(
2392 "DELETE FROM persistent.keymetadata
2393 WHERE keyentryid IN (
2394 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002395 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002396 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002397 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002398 )
2399 .context("Trying to delete keymetadata.")?;
2400 tx.execute(
2401 "DELETE FROM persistent.keyparameter
2402 WHERE keyentryid IN (
2403 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002404 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002405 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002406 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002407 )
2408 .context("Trying to delete keyparameters.")?;
2409 tx.execute(
2410 "DELETE FROM persistent.grant
2411 WHERE keyentryid IN (
2412 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002413 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002414 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002415 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002416 )
2417 .context("Trying to delete grants.")?;
2418 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002419 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002420 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2421 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002422 )
2423 .context("Trying to delete keyentry.")?;
2424 Ok(()).need_gc()
2425 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002426 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002427 }
2428
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002429 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2430 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2431 {
2432 tx.execute(
2433 "DELETE FROM persistent.keymetadata
2434 WHERE keyentryid IN (
2435 SELECT id FROM persistent.keyentry
2436 WHERE state = ?
2437 );",
2438 params![KeyLifeCycle::Unreferenced],
2439 )
2440 .context("Trying to delete keymetadata.")?;
2441 tx.execute(
2442 "DELETE FROM persistent.keyparameter
2443 WHERE keyentryid IN (
2444 SELECT id FROM persistent.keyentry
2445 WHERE state = ?
2446 );",
2447 params![KeyLifeCycle::Unreferenced],
2448 )
2449 .context("Trying to delete keyparameters.")?;
2450 tx.execute(
2451 "DELETE FROM persistent.grant
2452 WHERE keyentryid IN (
2453 SELECT id FROM persistent.keyentry
2454 WHERE state = ?
2455 );",
2456 params![KeyLifeCycle::Unreferenced],
2457 )
2458 .context("Trying to delete grants.")?;
2459 tx.execute(
2460 "DELETE FROM persistent.keyentry
2461 WHERE state = ?;",
2462 params![KeyLifeCycle::Unreferenced],
2463 )
2464 .context("Trying to delete keyentry.")?;
2465 Result::<()>::Ok(())
2466 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002467 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002468 }
2469
Hasini Gunasingheda895552021-01-27 19:34:37 +00002470 /// Delete the keys created on behalf of the user, denoted by the user id.
2471 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2472 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2473 /// The caller of this function should notify the gc if the returned value is true.
2474 pub fn unbind_keys_for_user(
2475 &mut self,
2476 user_id: u32,
2477 keep_non_super_encrypted_keys: bool,
2478 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002479 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2480
Hasini Gunasingheda895552021-01-27 19:34:37 +00002481 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2482 let mut stmt = tx
2483 .prepare(&format!(
2484 "SELECT id from persistent.keyentry
2485 WHERE (
2486 key_type = ?
2487 AND domain = ?
2488 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2489 AND state = ?
2490 ) OR (
2491 key_type = ?
2492 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002493 AND state = ?
2494 );",
2495 aid_user_offset = AID_USER_OFFSET
2496 ))
2497 .context(concat!(
2498 "In unbind_keys_for_user. ",
2499 "Failed to prepare the query to find the keys created by apps."
2500 ))?;
2501
2502 let mut rows = stmt
2503 .query(params![
2504 // WHERE client key:
2505 KeyType::Client,
2506 Domain::APP.0 as u32,
2507 user_id,
2508 KeyLifeCycle::Live,
2509 // OR super key:
2510 KeyType::Super,
2511 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002512 KeyLifeCycle::Live
2513 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002514 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002515
2516 let mut key_ids: Vec<i64> = Vec::new();
2517 db_utils::with_rows_extract_all(&mut rows, |row| {
2518 key_ids
2519 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2520 Ok(())
2521 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002522 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002523
2524 let mut notify_gc = false;
2525 for key_id in key_ids {
2526 if keep_non_super_encrypted_keys {
2527 // Load metadata and filter out non-super-encrypted keys.
2528 if let (_, Some((_, blob_metadata)), _, _) =
2529 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002530 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002531 {
2532 if blob_metadata.encrypted_by().is_none() {
2533 continue;
2534 }
2535 }
2536 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002537 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002538 .context("In unbind_keys_for_user.")?
2539 || notify_gc;
2540 }
2541 Ok(()).do_gc(notify_gc)
2542 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002543 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002544 }
2545
Eric Biggersb0478cf2023-10-27 03:55:29 +00002546 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2547 /// This runs when the user's lock screen is being changed to Swipe or None.
2548 ///
2549 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2550 /// such keys also require user authentication. Keystore's concept of user authentication is
2551 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2552 /// authentication is no longer possible. In contrast, keys that just require that the device
2553 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2554 /// is always considered "unlocked" in that case.
2555 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2556 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2557
2558 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2559 let mut stmt = tx
2560 .prepare(&format!(
2561 "SELECT id from persistent.keyentry
2562 WHERE key_type = ?
2563 AND domain = ?
2564 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2565 AND state = ?;",
2566 aid_user_offset = AID_USER_OFFSET
2567 ))
2568 .context(concat!(
2569 "In unbind_auth_bound_keys_for_user. ",
2570 "Failed to prepare the query to find the keys created by apps."
2571 ))?;
2572
2573 let mut rows = stmt
2574 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2575 .context(ks_err!("Failed to query the keys created by apps."))?;
2576
2577 let mut key_ids: Vec<i64> = Vec::new();
2578 db_utils::with_rows_extract_all(&mut rows, |row| {
2579 key_ids
2580 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2581 Ok(())
2582 })
2583 .context(ks_err!())?;
2584
2585 let mut notify_gc = false;
2586 let mut num_unbound = 0;
2587 for key_id in key_ids {
2588 // Load the key parameters and filter out non-auth-bound keys. To identify
2589 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2590 // could also be used, but UserSecureID is what Keystore treats as authoritative
2591 // when actually enforcing the key parameters (it might not matter, though).
2592 let params = Self::load_key_parameters(key_id, tx)
2593 .context("Failed to load key parameters.")?;
2594 let is_auth_bound_key = params.iter().any(|kp| {
2595 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2596 });
2597 if is_auth_bound_key {
2598 notify_gc = Self::mark_unreferenced(tx, key_id)
2599 .context("In unbind_auth_bound_keys_for_user.")?
2600 || notify_gc;
2601 num_unbound += 1;
2602 }
2603 }
2604 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2605 Ok(()).do_gc(notify_gc)
2606 })
2607 .context(ks_err!())
2608 }
2609
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002610 fn load_key_components(
2611 tx: &Transaction,
2612 load_bits: KeyEntryLoadBits,
2613 key_id: i64,
2614 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002615 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002616
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002617 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002618 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002619
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002620 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002621 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002622
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002623 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002624 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002625
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002626 Ok(KeyEntry {
2627 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002628 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002629 cert: cert_blob,
2630 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002631 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002632 parameters,
2633 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002634 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002635 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002636 }
2637
Eran Messeri24f31972023-01-25 17:00:33 +00002638 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2639 /// aliases are greater than the specified 'start_past_alias'. If no value
2640 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002641 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002642 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002643 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002644 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002645 &mut self,
2646 domain: Domain,
2647 namespace: i64,
2648 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002649 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002650 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002651 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002652
Eran Messeri24f31972023-01-25 17:00:33 +00002653 let query = format!(
2654 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002655 WHERE domain = ?
2656 AND namespace = ?
2657 AND alias IS NOT NULL
2658 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002659 AND key_type = ?
2660 {}
2661 ORDER BY alias ASC;",
2662 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2663 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002664
Eran Messeri24f31972023-01-25 17:00:33 +00002665 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2666 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2667
2668 let mut rows = match start_past_alias {
2669 Some(past_alias) => stmt
2670 .query(params![
2671 domain.0 as u32,
2672 namespace,
2673 KeyLifeCycle::Live,
2674 key_type,
2675 past_alias
2676 ])
2677 .context(ks_err!("Failed to query."))?,
2678 None => stmt
2679 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2680 .context(ks_err!("Failed to query."))?,
2681 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002682
Janis Danisevskis66784c42021-01-27 08:40:25 -08002683 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2684 db_utils::with_rows_extract_all(&mut rows, |row| {
2685 descriptors.push(KeyDescriptor {
2686 domain,
2687 nspace: namespace,
2688 alias: Some(row.get(0).context("Trying to extract alias.")?),
2689 blob: None,
2690 });
2691 Ok(())
2692 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002693 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002694 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002695 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002696 }
2697
Eran Messeri24f31972023-01-25 17:00:33 +00002698 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2699 /// Domain must be APP or SELINUX, the caller must make sure of that.
2700 pub fn count_keys(
2701 &mut self,
2702 domain: Domain,
2703 namespace: i64,
2704 key_type: KeyType,
2705 ) -> Result<usize> {
2706 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2707
2708 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2709 tx.query_row(
2710 "SELECT COUNT(alias) FROM persistent.keyentry
2711 WHERE domain = ?
2712 AND namespace = ?
2713 AND alias IS NOT NULL
2714 AND state = ?
2715 AND key_type = ?;",
2716 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2717 |row| row.get(0),
2718 )
2719 .context(ks_err!("Failed to count number of keys."))
2720 .no_gc()
2721 })?;
2722 Ok(num_keys)
2723 }
2724
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002725 /// Adds a grant to the grant table.
2726 /// Like `load_key_entry` this function loads the access tuple before
2727 /// it uses the callback for a permission check. Upon success,
2728 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2729 /// grant table. The new row will have a randomized id, which is used as
2730 /// grant id in the namespace field of the resulting KeyDescriptor.
2731 pub fn grant(
2732 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002733 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002734 caller_uid: u32,
2735 grantee_uid: u32,
2736 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002737 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002738 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002739 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2740
Janis Danisevskis66784c42021-01-27 08:40:25 -08002741 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2742 // Load the key_id and complete the access control tuple.
2743 // We ignore the access vector here because grants cannot be granted.
2744 // The access vector returned here expresses the permissions the
2745 // grantee has if key.domain == Domain::GRANT. But this vector
2746 // cannot include the grant permission by design, so there is no way the
2747 // subsequent permission check can pass.
2748 // We could check key.domain == Domain::GRANT and fail early.
2749 // But even if we load the access tuple by grant here, the permission
2750 // check denies the attempt to create a grant by grant descriptor.
2751 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002752 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002753
Janis Danisevskis66784c42021-01-27 08:40:25 -08002754 // Perform access control. It is vital that we return here if the permission
2755 // was denied. So do not touch that '?' at the end of the line.
2756 // This permission check checks if the caller has the grant permission
2757 // for the given key and in addition to all of the permissions
2758 // expressed in `access_vector`.
2759 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002760 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002761
Janis Danisevskis66784c42021-01-27 08:40:25 -08002762 let grant_id = if let Some(grant_id) = tx
2763 .query_row(
2764 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002765 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002766 params![key_id, grantee_uid],
2767 |row| row.get(0),
2768 )
2769 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002770 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002771 {
2772 tx.execute(
2773 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002774 SET access_vector = ?
2775 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002776 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002777 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002778 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002779 grant_id
2780 } else {
2781 Self::insert_with_retry(|id| {
2782 tx.execute(
2783 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2784 VALUES (?, ?, ?, ?);",
2785 params![id, grantee_uid, key_id, i32::from(access_vector)],
2786 )
2787 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002788 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002789 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002790
Janis Danisevskis66784c42021-01-27 08:40:25 -08002791 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002792 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002793 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002794 }
2795
2796 /// This function checks permissions like `grant` and `load_key_entry`
2797 /// before removing a grant from the grant table.
2798 pub fn ungrant(
2799 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002800 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002801 caller_uid: u32,
2802 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002803 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002804 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002805 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2806
Janis Danisevskis66784c42021-01-27 08:40:25 -08002807 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2808 // Load the key_id and complete the access control tuple.
2809 // We ignore the access vector here because grants cannot be granted.
2810 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002811 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002812
Janis Danisevskis66784c42021-01-27 08:40:25 -08002813 // Perform access control. We must return here if the permission
2814 // was denied. So do not touch the '?' at the end of this line.
2815 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002816 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002817
Janis Danisevskis66784c42021-01-27 08:40:25 -08002818 tx.execute(
2819 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002820 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002821 params![key_id, grantee_uid],
2822 )
2823 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002824
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002825 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002826 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002827 }
2828
Joel Galenson845f74b2020-09-09 14:11:55 -07002829 // Generates a random id and passes it to the given function, which will
2830 // try to insert it into a database. If that insertion fails, retry;
2831 // otherwise return the id.
2832 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2833 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002834 let newid: i64 = match random() {
2835 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2836 i => i,
2837 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002838 match inserter(newid) {
2839 // If the id already existed, try again.
2840 Err(rusqlite::Error::SqliteFailure(
2841 libsqlite3_sys::Error {
2842 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2843 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2844 },
2845 _,
2846 )) => (),
2847 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002848 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002849 }
2850 _ => return Ok(newid),
2851 }
2852 }
2853 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002854
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002855 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2856 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002857 self.perboot
2858 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002859 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002860
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002861 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002862 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002863 where
2864 F: Fn(&AuthTokenEntry) -> bool,
2865 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002866 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002867 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002868
2869 /// Load descriptor of a key by key id
2870 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2871 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2872
2873 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2874 tx.query_row(
2875 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2876 params![key_id],
2877 |row| {
2878 Ok(KeyDescriptor {
2879 domain: Domain(row.get(0)?),
2880 nspace: row.get(1)?,
2881 alias: row.get(2)?,
2882 blob: None,
2883 })
2884 },
2885 )
2886 .optional()
2887 .context("Trying to load key descriptor")
2888 .no_gc()
2889 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002890 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002891 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002892
2893 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2894 /// (for the given user_id).
2895 /// This is helpful for finding out which apps will have their keys invalidated when
2896 /// the user changes biometrics enrollment or removes their LSKF.
2897 pub fn get_app_uids_affected_by_sid(
2898 &mut self,
2899 user_id: i32,
2900 secure_user_id: i64,
2901 ) -> Result<Vec<i64>> {
2902 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2903
2904 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2905 let mut stmt = tx
2906 .prepare(&format!(
2907 "SELECT id, namespace from persistent.keyentry
2908 WHERE key_type = ?
2909 AND domain = ?
2910 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2911 AND state = ?;",
2912 ))
2913 .context(concat!(
2914 "In get_app_uids_affected_by_sid, ",
2915 "failed to prepare the query to find the keys created by apps."
2916 ))?;
2917
2918 let mut rows = stmt
2919 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2920 .context(ks_err!("Failed to query the keys created by apps."))?;
2921
2922 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2923 db_utils::with_rows_extract_all(&mut rows, |row| {
2924 key_ids_and_app_uids.insert(
2925 row.get(0).context("Failed to read key id of a key created by an app.")?,
2926 row.get(1).context("Failed to read the app uid")?,
2927 );
2928 Ok(())
2929 })?;
2930 Ok(key_ids_and_app_uids).no_gc()
2931 })?;
2932 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2933 for (key_id, app_uid) in key_ids_and_app_uids {
2934 // Read the key parameters for each key in its own transaction. It is OK to ignore
2935 // an error to get the properties of a particular key since it might have been deleted
2936 // under our feet after the previous transaction concluded. If the key was deleted
2937 // then it is no longer applicable if it was auth-bound or not.
2938 if let Ok(is_key_bound_to_sid) =
2939 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2940 let params = Self::load_key_parameters(key_id, tx)
2941 .context("Failed to load key parameters.")?;
2942 // Check if the key is bound to this secure user ID.
2943 let is_key_bound_to_sid = params.iter().any(|kp| {
2944 matches!(
2945 kp.key_parameter_value(),
2946 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2947 )
2948 });
2949 Ok(is_key_bound_to_sid).no_gc()
2950 })
2951 {
2952 if is_key_bound_to_sid {
2953 app_uids_affected_by_sid.insert(app_uid);
2954 }
2955 }
2956 }
2957
2958 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2959 Ok(app_uids_vec)
2960 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002961}
2962
2963#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002964pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002965
2966 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002967 use crate::key_parameter::{
2968 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2969 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2970 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002971 use crate::key_perm_set;
2972 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002973 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002974 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002975 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2976 HardwareAuthToken::HardwareAuthToken,
2977 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002978 };
2979 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002980 Timestamp::Timestamp,
2981 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002982 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07002983 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002984 use std::collections::BTreeMap;
2985 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002986 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002987 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002988 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002989 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002990 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002991 #[cfg(disabled)]
2992 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002993
Seth Moore7ee79f92021-12-07 11:42:49 -08002994 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002995 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002996
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002997 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002998 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002999 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003000 })?;
3001 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003002 }
3003
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003004 fn rebind_alias(
3005 db: &mut KeystoreDB,
3006 newid: &KeyIdGuard,
3007 alias: &str,
3008 domain: Domain,
3009 namespace: i64,
3010 ) -> Result<bool> {
3011 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003012 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003013 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003014 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003015 }
3016
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003017 #[test]
3018 fn datetime() -> Result<()> {
3019 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003020 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003021 let now = SystemTime::now();
3022 let duration = Duration::from_secs(1000);
3023 let then = now.checked_sub(duration).unwrap();
3024 let soon = now.checked_add(duration).unwrap();
3025 conn.execute(
3026 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3027 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3028 )?;
3029 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003030 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003031 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3032 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3033 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3034 assert!(rows.next()?.is_none());
3035 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3036 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3037 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3038 Ok(())
3039 }
3040
Joel Galenson0891bc12020-07-20 10:37:03 -07003041 // Ensure that we're using the "injected" random function, not the real one.
3042 #[test]
3043 fn test_mocked_random() {
3044 let rand1 = random();
3045 let rand2 = random();
3046 let rand3 = random();
3047 if rand1 == rand2 {
3048 assert_eq!(rand2 + 1, rand3);
3049 } else {
3050 assert_eq!(rand1 + 1, rand2);
3051 assert_eq!(rand2, rand3);
3052 }
3053 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003054
Joel Galenson26f4d012020-07-17 14:57:21 -07003055 // Test that we have the correct tables.
3056 #[test]
3057 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003058 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003059 let tables = db
3060 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003061 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003062 .query_map(params![], |row| row.get(0))?
3063 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003064 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003065 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003066 assert_eq!(tables[1], "blobmetadata");
3067 assert_eq!(tables[2], "grant");
3068 assert_eq!(tables[3], "keyentry");
3069 assert_eq!(tables[4], "keymetadata");
3070 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003071 Ok(())
3072 }
3073
3074 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003075 fn test_auth_token_table_invariant() -> Result<()> {
3076 let mut db = new_test_db()?;
3077 let auth_token1 = HardwareAuthToken {
3078 challenge: i64::MAX,
3079 userId: 200,
3080 authenticatorId: 200,
3081 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3082 timestamp: Timestamp { milliSeconds: 500 },
3083 mac: String::from("mac").into_bytes(),
3084 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003085 db.insert_auth_token(&auth_token1);
3086 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003087 assert_eq!(auth_tokens_returned.len(), 1);
3088
3089 // insert another auth token with the same values for the columns in the UNIQUE constraint
3090 // of the auth token table and different value for timestamp
3091 let auth_token2 = HardwareAuthToken {
3092 challenge: i64::MAX,
3093 userId: 200,
3094 authenticatorId: 200,
3095 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3096 timestamp: Timestamp { milliSeconds: 600 },
3097 mac: String::from("mac").into_bytes(),
3098 };
3099
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003100 db.insert_auth_token(&auth_token2);
3101 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003102 assert_eq!(auth_tokens_returned.len(), 1);
3103
3104 if let Some(auth_token) = auth_tokens_returned.pop() {
3105 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3106 }
3107
3108 // insert another auth token with the different values for the columns in the UNIQUE
3109 // constraint of the auth token table
3110 let auth_token3 = HardwareAuthToken {
3111 challenge: i64::MAX,
3112 userId: 201,
3113 authenticatorId: 200,
3114 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3115 timestamp: Timestamp { milliSeconds: 600 },
3116 mac: String::from("mac").into_bytes(),
3117 };
3118
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003119 db.insert_auth_token(&auth_token3);
3120 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003121 assert_eq!(auth_tokens_returned.len(), 2);
3122
3123 Ok(())
3124 }
3125
3126 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003127 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3128 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003129 }
3130
3131 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003132 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003133 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003134 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003135
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003136 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003137 let entries = get_keyentry(&db)?;
3138 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003139
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003140 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003141
3142 let entries_new = get_keyentry(&db)?;
3143 assert_eq!(entries, entries_new);
3144 Ok(())
3145 }
3146
3147 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003148 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003149 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3150 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003151 }
3152
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003153 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003154
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003155 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3156 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003157
3158 let entries = get_keyentry(&db)?;
3159 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003160 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3161 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003162
3163 // Test that we must pass in a valid Domain.
3164 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003165 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003166 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003167 );
3168 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003169 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003170 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003171 );
3172 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003173 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003174 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003175 );
3176
3177 Ok(())
3178 }
3179
Joel Galenson33c04ad2020-08-03 11:04:38 -07003180 #[test]
3181 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003182 fn extractor(
3183 ke: &KeyEntryRow,
3184 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3185 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003186 }
3187
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003188 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003189 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3190 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003191 let entries = get_keyentry(&db)?;
3192 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003193 assert_eq!(
3194 extractor(&entries[0]),
3195 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3196 );
3197 assert_eq!(
3198 extractor(&entries[1]),
3199 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3200 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003201
3202 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003203 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003204 let entries = get_keyentry(&db)?;
3205 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003206 assert_eq!(
3207 extractor(&entries[0]),
3208 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3209 );
3210 assert_eq!(
3211 extractor(&entries[1]),
3212 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3213 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003214
3215 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003216 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003217 let entries = get_keyentry(&db)?;
3218 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003219 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3220 assert_eq!(
3221 extractor(&entries[1]),
3222 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3223 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003224
3225 // Test that we must pass in a valid Domain.
3226 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003227 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003228 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003229 );
3230 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003231 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003232 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003233 );
3234 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003235 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003236 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003237 );
3238
3239 // Test that we correctly handle setting an alias for something that does not exist.
3240 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003241 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003242 "Expected to update a single entry but instead updated 0",
3243 );
3244 // Test that we correctly abort the transaction in this case.
3245 let entries = get_keyentry(&db)?;
3246 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003247 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3248 assert_eq!(
3249 extractor(&entries[1]),
3250 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3251 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003252
3253 Ok(())
3254 }
3255
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003256 #[test]
3257 fn test_grant_ungrant() -> Result<()> {
3258 const CALLER_UID: u32 = 15;
3259 const GRANTEE_UID: u32 = 12;
3260 const SELINUX_NAMESPACE: i64 = 7;
3261
3262 let mut db = new_test_db()?;
3263 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003264 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3265 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3266 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003267 )?;
3268 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003269 domain: super::Domain::APP,
3270 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003271 alias: Some("key".to_string()),
3272 blob: None,
3273 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003274 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3275 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003276
3277 // Reset totally predictable random number generator in case we
3278 // are not the first test running on this thread.
3279 reset_random();
3280 let next_random = 0i64;
3281
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003282 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003283 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003284 assert_eq!(*a, PVEC1);
3285 assert_eq!(
3286 *k,
3287 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003288 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003289 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003290 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003291 alias: Some("key".to_string()),
3292 blob: None,
3293 }
3294 );
3295 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003296 })
3297 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003298
3299 assert_eq!(
3300 app_granted_key,
3301 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003302 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003304 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003305 alias: None,
3306 blob: None,
3307 }
3308 );
3309
3310 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003311 domain: super::Domain::SELINUX,
3312 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003313 alias: Some("yek".to_string()),
3314 blob: None,
3315 };
3316
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003317 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003318 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003319 assert_eq!(*a, PVEC1);
3320 assert_eq!(
3321 *k,
3322 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003323 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003324 // namespace must be the supplied SELinux
3325 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003326 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003327 alias: Some("yek".to_string()),
3328 blob: None,
3329 }
3330 );
3331 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003332 })
3333 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003334
3335 assert_eq!(
3336 selinux_granted_key,
3337 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003338 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003339 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003340 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003341 alias: None,
3342 blob: None,
3343 }
3344 );
3345
3346 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003347 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003348 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003349 assert_eq!(*a, PVEC2);
3350 assert_eq!(
3351 *k,
3352 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003353 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003354 // namespace must be the supplied SELinux
3355 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003356 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003357 alias: Some("yek".to_string()),
3358 blob: None,
3359 }
3360 );
3361 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003362 })
3363 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003364
3365 assert_eq!(
3366 selinux_granted_key,
3367 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003368 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003369 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003370 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003371 alias: None,
3372 blob: None,
3373 }
3374 );
3375
3376 {
3377 // Limiting scope of stmt, because it borrows db.
3378 let mut stmt = db
3379 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003380 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003381 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3382 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3383 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003384
3385 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003386 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003387 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003388 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003389 assert!(rows.next().is_none());
3390 }
3391
3392 debug_dump_keyentry_table(&mut db)?;
3393 println!("app_key {:?}", app_key);
3394 println!("selinux_key {:?}", selinux_key);
3395
Janis Danisevskis66784c42021-01-27 08:40:25 -08003396 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3397 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003398
3399 Ok(())
3400 }
3401
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003402 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003403 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3404 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3405
3406 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003407 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003408 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003409 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003410 let mut blob_metadata = BlobMetaData::new();
3411 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3412 db.set_blob(
3413 &key_id,
3414 SubComponentType::KEY_BLOB,
3415 Some(TEST_KEY_BLOB),
3416 Some(&blob_metadata),
3417 )?;
3418 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3419 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003420 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003421
3422 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003423 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003424 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003425 )?;
3426 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003427 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003428 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003429 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003430 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003431 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003432 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003433 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003434 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003435 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003436
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003437 drop(rows);
3438 drop(stmt);
3439
3440 assert_eq!(
3441 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3442 BlobMetaData::load_from_db(id, tx).no_gc()
3443 })
3444 .expect("Should find blob metadata."),
3445 blob_metadata
3446 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003447 Ok(())
3448 }
3449
3450 static TEST_ALIAS: &str = "my super duper key";
3451
3452 #[test]
3453 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3454 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003455 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003456 .context("test_insert_and_load_full_keyentry_domain_app")?
3457 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003458 let (_key_guard, key_entry) = db
3459 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003460 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003461 domain: Domain::APP,
3462 nspace: 0,
3463 alias: Some(TEST_ALIAS.to_string()),
3464 blob: None,
3465 },
3466 KeyType::Client,
3467 KeyEntryLoadBits::BOTH,
3468 1,
3469 |_k, _av| Ok(()),
3470 )
3471 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003472 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003473
3474 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003475 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003476 domain: Domain::APP,
3477 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003478 alias: Some(TEST_ALIAS.to_string()),
3479 blob: None,
3480 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003481 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003482 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003483 |_, _| Ok(()),
3484 )
3485 .unwrap();
3486
3487 assert_eq!(
3488 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3489 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003490 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003491 domain: Domain::APP,
3492 nspace: 0,
3493 alias: Some(TEST_ALIAS.to_string()),
3494 blob: None,
3495 },
3496 KeyType::Client,
3497 KeyEntryLoadBits::NONE,
3498 1,
3499 |_k, _av| Ok(()),
3500 )
3501 .unwrap_err()
3502 .root_cause()
3503 .downcast_ref::<KsError>()
3504 );
3505
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003506 Ok(())
3507 }
3508
3509 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003510 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3511 let mut db = new_test_db()?;
3512
3513 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003514 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003515 domain: Domain::APP,
3516 nspace: 1,
3517 alias: Some(TEST_ALIAS.to_string()),
3518 blob: None,
3519 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003520 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003521 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003522 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003523 )
3524 .expect("Trying to insert cert.");
3525
3526 let (_key_guard, mut key_entry) = db
3527 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003528 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003529 domain: Domain::APP,
3530 nspace: 1,
3531 alias: Some(TEST_ALIAS.to_string()),
3532 blob: None,
3533 },
3534 KeyType::Client,
3535 KeyEntryLoadBits::PUBLIC,
3536 1,
3537 |_k, _av| Ok(()),
3538 )
3539 .expect("Trying to read certificate entry.");
3540
3541 assert!(key_entry.pure_cert());
3542 assert!(key_entry.cert().is_none());
3543 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3544
3545 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003546 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003547 domain: Domain::APP,
3548 nspace: 1,
3549 alias: Some(TEST_ALIAS.to_string()),
3550 blob: None,
3551 },
3552 KeyType::Client,
3553 1,
3554 |_, _| Ok(()),
3555 )
3556 .unwrap();
3557
3558 assert_eq!(
3559 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3560 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003561 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003562 domain: Domain::APP,
3563 nspace: 1,
3564 alias: Some(TEST_ALIAS.to_string()),
3565 blob: None,
3566 },
3567 KeyType::Client,
3568 KeyEntryLoadBits::NONE,
3569 1,
3570 |_k, _av| Ok(()),
3571 )
3572 .unwrap_err()
3573 .root_cause()
3574 .downcast_ref::<KsError>()
3575 );
3576
3577 Ok(())
3578 }
3579
3580 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003581 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3582 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003583 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003584 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3585 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003586 let (_key_guard, key_entry) = db
3587 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003588 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003589 domain: Domain::SELINUX,
3590 nspace: 1,
3591 alias: Some(TEST_ALIAS.to_string()),
3592 blob: None,
3593 },
3594 KeyType::Client,
3595 KeyEntryLoadBits::BOTH,
3596 1,
3597 |_k, _av| Ok(()),
3598 )
3599 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003600 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003601
3602 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003603 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003604 domain: Domain::SELINUX,
3605 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003606 alias: Some(TEST_ALIAS.to_string()),
3607 blob: None,
3608 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003609 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003610 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003611 |_, _| Ok(()),
3612 )
3613 .unwrap();
3614
3615 assert_eq!(
3616 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3617 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003618 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003619 domain: Domain::SELINUX,
3620 nspace: 1,
3621 alias: Some(TEST_ALIAS.to_string()),
3622 blob: None,
3623 },
3624 KeyType::Client,
3625 KeyEntryLoadBits::NONE,
3626 1,
3627 |_k, _av| Ok(()),
3628 )
3629 .unwrap_err()
3630 .root_cause()
3631 .downcast_ref::<KsError>()
3632 );
3633
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003634 Ok(())
3635 }
3636
3637 #[test]
3638 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3639 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003640 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003641 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3642 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003643 let (_, key_entry) = db
3644 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003645 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003646 KeyType::Client,
3647 KeyEntryLoadBits::BOTH,
3648 1,
3649 |_k, _av| Ok(()),
3650 )
3651 .unwrap();
3652
Qi Wub9433b52020-12-01 14:52:46 +08003653 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003654
3655 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003656 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003657 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003658 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003659 |_, _| Ok(()),
3660 )
3661 .unwrap();
3662
3663 assert_eq!(
3664 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3665 db.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::NONE,
3669 1,
3670 |_k, _av| Ok(()),
3671 )
3672 .unwrap_err()
3673 .root_cause()
3674 .downcast_ref::<KsError>()
3675 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003676
3677 Ok(())
3678 }
3679
3680 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003681 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3682 let mut db = new_test_db()?;
3683 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3684 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3685 .0;
3686 // Update the usage count of the limited use key.
3687 db.check_and_update_key_usage_count(key_id)?;
3688
3689 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003690 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003691 KeyType::Client,
3692 KeyEntryLoadBits::BOTH,
3693 1,
3694 |_k, _av| Ok(()),
3695 )?;
3696
3697 // The usage count is decremented now.
3698 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3699
3700 Ok(())
3701 }
3702
3703 #[test]
3704 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3705 let mut db = new_test_db()?;
3706 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3707 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3708 .0;
3709 // Update the usage count of the limited use key.
3710 db.check_and_update_key_usage_count(key_id).expect(concat!(
3711 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3712 "This should succeed."
3713 ));
3714
3715 // Try to update the exhausted limited use key.
3716 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3717 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3718 "This should fail."
3719 ));
3720 assert_eq!(
3721 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3722 e.root_cause().downcast_ref::<KsError>().unwrap()
3723 );
3724
3725 Ok(())
3726 }
3727
3728 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003729 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3730 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003731 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003732 .context("test_insert_and_load_full_keyentry_from_grant")?
3733 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003734
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003735 let granted_key = db
3736 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003737 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003738 domain: Domain::APP,
3739 nspace: 0,
3740 alias: Some(TEST_ALIAS.to_string()),
3741 blob: None,
3742 },
3743 1,
3744 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003745 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003746 |_k, _av| Ok(()),
3747 )
3748 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003749
3750 debug_dump_grant_table(&mut db)?;
3751
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003752 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003753 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3754 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003755 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003756 Ok(())
3757 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003758 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003759
Qi Wub9433b52020-12-01 14:52:46 +08003760 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003761
Janis Danisevskis66784c42021-01-27 08:40:25 -08003762 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003763
3764 assert_eq!(
3765 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3766 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003767 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003768 KeyType::Client,
3769 KeyEntryLoadBits::NONE,
3770 2,
3771 |_k, _av| Ok(()),
3772 )
3773 .unwrap_err()
3774 .root_cause()
3775 .downcast_ref::<KsError>()
3776 );
3777
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003778 Ok(())
3779 }
3780
Janis Danisevskis45760022021-01-19 16:34:10 -08003781 // This test attempts to load a key by key id while the caller is not the owner
3782 // but a grant exists for the given key and the caller.
3783 #[test]
3784 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3785 let mut db = new_test_db()?;
3786 const OWNER_UID: u32 = 1u32;
3787 const GRANTEE_UID: u32 = 2u32;
3788 const SOMEONE_ELSE_UID: u32 = 3u32;
3789 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3790 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3791 .0;
3792
3793 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003794 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003795 domain: Domain::APP,
3796 nspace: 0,
3797 alias: Some(TEST_ALIAS.to_string()),
3798 blob: None,
3799 },
3800 OWNER_UID,
3801 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003802 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003803 |_k, _av| Ok(()),
3804 )
3805 .unwrap();
3806
3807 debug_dump_grant_table(&mut db)?;
3808
3809 let id_descriptor =
3810 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3811
3812 let (_, key_entry) = db
3813 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003814 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003815 KeyType::Client,
3816 KeyEntryLoadBits::BOTH,
3817 GRANTEE_UID,
3818 |k, av| {
3819 assert_eq!(Domain::APP, k.domain);
3820 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003821 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003822 Ok(())
3823 },
3824 )
3825 .unwrap();
3826
3827 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3828
3829 let (_, key_entry) = db
3830 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003831 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003832 KeyType::Client,
3833 KeyEntryLoadBits::BOTH,
3834 SOMEONE_ELSE_UID,
3835 |k, av| {
3836 assert_eq!(Domain::APP, k.domain);
3837 assert_eq!(OWNER_UID as i64, k.nspace);
3838 assert!(av.is_none());
3839 Ok(())
3840 },
3841 )
3842 .unwrap();
3843
3844 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3845
Janis Danisevskis66784c42021-01-27 08:40:25 -08003846 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003847
3848 assert_eq!(
3849 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3850 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003851 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003852 KeyType::Client,
3853 KeyEntryLoadBits::NONE,
3854 GRANTEE_UID,
3855 |_k, _av| Ok(()),
3856 )
3857 .unwrap_err()
3858 .root_cause()
3859 .downcast_ref::<KsError>()
3860 );
3861
3862 Ok(())
3863 }
3864
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003865 // Creates a key migrates it to a different location and then tries to access it by the old
3866 // and new location.
3867 #[test]
3868 fn test_migrate_key_app_to_app() -> Result<()> {
3869 let mut db = new_test_db()?;
3870 const SOURCE_UID: u32 = 1u32;
3871 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003872 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3873 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003874 let key_id_guard =
3875 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3876 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3877
3878 let source_descriptor: KeyDescriptor = KeyDescriptor {
3879 domain: Domain::APP,
3880 nspace: -1,
3881 alias: Some(SOURCE_ALIAS.to_string()),
3882 blob: None,
3883 };
3884
3885 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3886 domain: Domain::APP,
3887 nspace: -1,
3888 alias: Some(DESTINATION_ALIAS.to_string()),
3889 blob: None,
3890 };
3891
3892 let key_id = key_id_guard.id();
3893
3894 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3895 Ok(())
3896 })
3897 .unwrap();
3898
3899 let (_, key_entry) = db
3900 .load_key_entry(
3901 &destination_descriptor,
3902 KeyType::Client,
3903 KeyEntryLoadBits::BOTH,
3904 DESTINATION_UID,
3905 |k, av| {
3906 assert_eq!(Domain::APP, k.domain);
3907 assert_eq!(DESTINATION_UID as i64, k.nspace);
3908 assert!(av.is_none());
3909 Ok(())
3910 },
3911 )
3912 .unwrap();
3913
3914 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3915
3916 assert_eq!(
3917 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3918 db.load_key_entry(
3919 &source_descriptor,
3920 KeyType::Client,
3921 KeyEntryLoadBits::NONE,
3922 SOURCE_UID,
3923 |_k, _av| Ok(()),
3924 )
3925 .unwrap_err()
3926 .root_cause()
3927 .downcast_ref::<KsError>()
3928 );
3929
3930 Ok(())
3931 }
3932
3933 // Creates a key migrates it to a different location and then tries to access it by the old
3934 // and new location.
3935 #[test]
3936 fn test_migrate_key_app_to_selinux() -> Result<()> {
3937 let mut db = new_test_db()?;
3938 const SOURCE_UID: u32 = 1u32;
3939 const DESTINATION_UID: u32 = 2u32;
3940 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003941 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3942 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003943 let key_id_guard =
3944 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3945 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3946
3947 let source_descriptor: KeyDescriptor = KeyDescriptor {
3948 domain: Domain::APP,
3949 nspace: -1,
3950 alias: Some(SOURCE_ALIAS.to_string()),
3951 blob: None,
3952 };
3953
3954 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3955 domain: Domain::SELINUX,
3956 nspace: DESTINATION_NAMESPACE,
3957 alias: Some(DESTINATION_ALIAS.to_string()),
3958 blob: None,
3959 };
3960
3961 let key_id = key_id_guard.id();
3962
3963 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3964 Ok(())
3965 })
3966 .unwrap();
3967
3968 let (_, key_entry) = db
3969 .load_key_entry(
3970 &destination_descriptor,
3971 KeyType::Client,
3972 KeyEntryLoadBits::BOTH,
3973 DESTINATION_UID,
3974 |k, av| {
3975 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003976 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003977 assert!(av.is_none());
3978 Ok(())
3979 },
3980 )
3981 .unwrap();
3982
3983 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3984
3985 assert_eq!(
3986 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3987 db.load_key_entry(
3988 &source_descriptor,
3989 KeyType::Client,
3990 KeyEntryLoadBits::NONE,
3991 SOURCE_UID,
3992 |_k, _av| Ok(()),
3993 )
3994 .unwrap_err()
3995 .root_cause()
3996 .downcast_ref::<KsError>()
3997 );
3998
3999 Ok(())
4000 }
4001
4002 // Creates two keys and tries to migrate the first to the location of the second which
4003 // is expected to fail.
4004 #[test]
4005 fn test_migrate_key_destination_occupied() -> Result<()> {
4006 let mut db = new_test_db()?;
4007 const SOURCE_UID: u32 = 1u32;
4008 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004009 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4010 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004011 let key_id_guard =
4012 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4013 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4014 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4015 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4016
4017 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4018 domain: Domain::APP,
4019 nspace: -1,
4020 alias: Some(DESTINATION_ALIAS.to_string()),
4021 blob: None,
4022 };
4023
4024 assert_eq!(
4025 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4026 db.migrate_key_namespace(
4027 key_id_guard,
4028 &destination_descriptor,
4029 DESTINATION_UID,
4030 |_k| Ok(())
4031 )
4032 .unwrap_err()
4033 .root_cause()
4034 .downcast_ref::<KsError>()
4035 );
4036
4037 Ok(())
4038 }
4039
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004040 #[test]
4041 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004042 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4043 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4044 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004045 const UID: u32 = 33;
4046 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4047 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4048 let key_id_untouched1 =
4049 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4050 let key_id_untouched2 =
4051 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4052 let key_id_deleted =
4053 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4054
4055 let (_, key_entry) = db
4056 .load_key_entry(
4057 &KeyDescriptor {
4058 domain: Domain::APP,
4059 nspace: -1,
4060 alias: Some(ALIAS1.to_string()),
4061 blob: None,
4062 },
4063 KeyType::Client,
4064 KeyEntryLoadBits::BOTH,
4065 UID,
4066 |k, av| {
4067 assert_eq!(Domain::APP, k.domain);
4068 assert_eq!(UID as i64, k.nspace);
4069 assert!(av.is_none());
4070 Ok(())
4071 },
4072 )
4073 .unwrap();
4074 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4075 let (_, key_entry) = db
4076 .load_key_entry(
4077 &KeyDescriptor {
4078 domain: Domain::APP,
4079 nspace: -1,
4080 alias: Some(ALIAS2.to_string()),
4081 blob: None,
4082 },
4083 KeyType::Client,
4084 KeyEntryLoadBits::BOTH,
4085 UID,
4086 |k, av| {
4087 assert_eq!(Domain::APP, k.domain);
4088 assert_eq!(UID as i64, k.nspace);
4089 assert!(av.is_none());
4090 Ok(())
4091 },
4092 )
4093 .unwrap();
4094 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4095 let (_, key_entry) = db
4096 .load_key_entry(
4097 &KeyDescriptor {
4098 domain: Domain::APP,
4099 nspace: -1,
4100 alias: Some(ALIAS3.to_string()),
4101 blob: None,
4102 },
4103 KeyType::Client,
4104 KeyEntryLoadBits::BOTH,
4105 UID,
4106 |k, av| {
4107 assert_eq!(Domain::APP, k.domain);
4108 assert_eq!(UID as i64, k.nspace);
4109 assert!(av.is_none());
4110 Ok(())
4111 },
4112 )
4113 .unwrap();
4114 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4115
4116 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4117 KeystoreDB::from_0_to_1(tx).no_gc()
4118 })
4119 .unwrap();
4120
4121 let (_, key_entry) = db
4122 .load_key_entry(
4123 &KeyDescriptor {
4124 domain: Domain::APP,
4125 nspace: -1,
4126 alias: Some(ALIAS1.to_string()),
4127 blob: None,
4128 },
4129 KeyType::Client,
4130 KeyEntryLoadBits::BOTH,
4131 UID,
4132 |k, av| {
4133 assert_eq!(Domain::APP, k.domain);
4134 assert_eq!(UID as i64, k.nspace);
4135 assert!(av.is_none());
4136 Ok(())
4137 },
4138 )
4139 .unwrap();
4140 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4141 let (_, key_entry) = db
4142 .load_key_entry(
4143 &KeyDescriptor {
4144 domain: Domain::APP,
4145 nspace: -1,
4146 alias: Some(ALIAS2.to_string()),
4147 blob: None,
4148 },
4149 KeyType::Client,
4150 KeyEntryLoadBits::BOTH,
4151 UID,
4152 |k, av| {
4153 assert_eq!(Domain::APP, k.domain);
4154 assert_eq!(UID as i64, k.nspace);
4155 assert!(av.is_none());
4156 Ok(())
4157 },
4158 )
4159 .unwrap();
4160 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4161 assert_eq!(
4162 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4163 db.load_key_entry(
4164 &KeyDescriptor {
4165 domain: Domain::APP,
4166 nspace: -1,
4167 alias: Some(ALIAS3.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_err()
4181 .root_cause()
4182 .downcast_ref::<KsError>()
4183 );
4184 }
4185
Janis Danisevskisaec14592020-11-12 09:41:49 -08004186 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4187
Janis Danisevskisaec14592020-11-12 09:41:49 -08004188 #[test]
4189 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4190 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004191 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4192 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004193 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004194 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004195 .context("test_insert_and_load_full_keyentry_domain_app")?
4196 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004197 let (_key_guard, key_entry) = db
4198 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004199 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004200 domain: Domain::APP,
4201 nspace: 0,
4202 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4203 blob: None,
4204 },
4205 KeyType::Client,
4206 KeyEntryLoadBits::BOTH,
4207 33,
4208 |_k, _av| Ok(()),
4209 )
4210 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004211 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004212 let state = Arc::new(AtomicU8::new(1));
4213 let state2 = state.clone();
4214
4215 // Spawning a second thread that attempts to acquire the key id lock
4216 // for the same key as the primary thread. The primary thread then
4217 // waits, thereby forcing the secondary thread into the second stage
4218 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4219 // The test succeeds if the secondary thread observes the transition
4220 // of `state` from 1 to 2, despite having a whole second to overtake
4221 // the primary thread.
4222 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004223 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004224 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004225 assert!(db
4226 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004227 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004228 domain: Domain::APP,
4229 nspace: 0,
4230 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4231 blob: None,
4232 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004233 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004234 KeyEntryLoadBits::BOTH,
4235 33,
4236 |_k, _av| Ok(()),
4237 )
4238 .is_ok());
4239 // We should only see a 2 here because we can only return
4240 // from load_key_entry when the `_key_guard` expires,
4241 // which happens at the end of the scope.
4242 assert_eq!(2, state2.load(Ordering::Relaxed));
4243 });
4244
4245 thread::sleep(std::time::Duration::from_millis(1000));
4246
4247 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4248
4249 // Return the handle from this scope so we can join with the
4250 // secondary thread after the key id lock has expired.
4251 handle
4252 // This is where the `_key_guard` goes out of scope,
4253 // which is the reason for concurrent load_key_entry on the same key
4254 // to unblock.
4255 };
4256 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4257 // main test thread. We will not see failing asserts in secondary threads otherwise.
4258 handle.join().unwrap();
4259 Ok(())
4260 }
4261
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004262 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004263 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004264 let temp_dir =
4265 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4266
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004267 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4268 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004269
4270 let _tx1 = db1
4271 .conn
4272 .transaction_with_behavior(TransactionBehavior::Immediate)
4273 .expect("Failed to create first transaction.");
4274
4275 let error = db2
4276 .conn
4277 .transaction_with_behavior(TransactionBehavior::Immediate)
4278 .context("Transaction begin failed.")
4279 .expect_err("This should fail.");
4280 let root_cause = error.root_cause();
4281 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4282 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4283 {
4284 return;
4285 }
4286 panic!(
4287 "Unexpected error {:?} \n{:?} \n{:?}",
4288 error,
4289 root_cause,
4290 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4291 )
4292 }
4293
4294 #[cfg(disabled)]
4295 #[test]
4296 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4297 let temp_dir = Arc::new(
4298 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4299 .expect("Failed to create temp dir."),
4300 );
4301
4302 let test_begin = Instant::now();
4303
Janis Danisevskis66784c42021-01-27 08:40:25 -08004304 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004305 let mut db =
4306 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004307 const OPEN_DB_COUNT: u32 = 50u32;
4308
4309 let mut actual_key_count = KEY_COUNT;
4310 // First insert KEY_COUNT keys.
4311 for count in 0..KEY_COUNT {
4312 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4313 actual_key_count = count;
4314 break;
4315 }
4316 let alias = format!("test_alias_{}", count);
4317 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4318 .expect("Failed to make key entry.");
4319 }
4320
4321 // Insert more keys from a different thread and into a different namespace.
4322 let temp_dir1 = temp_dir.clone();
4323 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004324 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4325 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004326
4327 for count in 0..actual_key_count {
4328 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4329 return;
4330 }
4331 let alias = format!("test_alias_{}", count);
4332 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4333 .expect("Failed to make key entry.");
4334 }
4335
4336 // then unbind them again.
4337 for count in 0..actual_key_count {
4338 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4339 return;
4340 }
4341 let key = KeyDescriptor {
4342 domain: Domain::APP,
4343 nspace: -1,
4344 alias: Some(format!("test_alias_{}", count)),
4345 blob: None,
4346 };
4347 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4348 }
4349 });
4350
4351 // And start unbinding the first set of keys.
4352 let temp_dir2 = temp_dir.clone();
4353 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004354 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4355 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004356
4357 for count in 0..actual_key_count {
4358 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4359 return;
4360 }
4361 let key = KeyDescriptor {
4362 domain: Domain::APP,
4363 nspace: -1,
4364 alias: Some(format!("test_alias_{}", count)),
4365 blob: None,
4366 };
4367 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4368 }
4369 });
4370
Janis Danisevskis66784c42021-01-27 08:40:25 -08004371 // While a lot of inserting and deleting is going on we have to open database connections
4372 // successfully and use them.
4373 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4374 // out of scope.
4375 #[allow(clippy::redundant_clone)]
4376 let temp_dir4 = temp_dir.clone();
4377 let handle4 = thread::spawn(move || {
4378 for count in 0..OPEN_DB_COUNT {
4379 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4380 return;
4381 }
Seth Moore444b51a2021-06-11 09:49:49 -07004382 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4383 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004384
4385 let alias = format!("test_alias_{}", count);
4386 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4387 .expect("Failed to make key entry.");
4388 let key = KeyDescriptor {
4389 domain: Domain::APP,
4390 nspace: -1,
4391 alias: Some(alias),
4392 blob: None,
4393 };
4394 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4395 }
4396 });
4397
4398 handle1.join().expect("Thread 1 panicked.");
4399 handle2.join().expect("Thread 2 panicked.");
4400 handle4.join().expect("Thread 4 panicked.");
4401
Janis Danisevskis66784c42021-01-27 08:40:25 -08004402 Ok(())
4403 }
4404
4405 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004406 fn list() -> Result<()> {
4407 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004408 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004409 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4410 (Domain::APP, 1, "test1"),
4411 (Domain::APP, 1, "test2"),
4412 (Domain::APP, 1, "test3"),
4413 (Domain::APP, 1, "test4"),
4414 (Domain::APP, 1, "test5"),
4415 (Domain::APP, 1, "test6"),
4416 (Domain::APP, 1, "test7"),
4417 (Domain::APP, 2, "test1"),
4418 (Domain::APP, 2, "test2"),
4419 (Domain::APP, 2, "test3"),
4420 (Domain::APP, 2, "test4"),
4421 (Domain::APP, 2, "test5"),
4422 (Domain::APP, 2, "test6"),
4423 (Domain::APP, 2, "test8"),
4424 (Domain::SELINUX, 100, "test1"),
4425 (Domain::SELINUX, 100, "test2"),
4426 (Domain::SELINUX, 100, "test3"),
4427 (Domain::SELINUX, 100, "test4"),
4428 (Domain::SELINUX, 100, "test5"),
4429 (Domain::SELINUX, 100, "test6"),
4430 (Domain::SELINUX, 100, "test9"),
4431 ];
4432
4433 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4434 .iter()
4435 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004436 let entry =
4437 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004438 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4439 });
4440 (entry.id(), *ns)
4441 })
4442 .collect();
4443
4444 for (domain, namespace) in
4445 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4446 {
4447 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4448 .iter()
4449 .filter_map(|(domain, ns, alias)| match ns {
4450 ns if *ns == *namespace => Some(KeyDescriptor {
4451 domain: *domain,
4452 nspace: *ns,
4453 alias: Some(alias.to_string()),
4454 blob: None,
4455 }),
4456 _ => None,
4457 })
4458 .collect();
4459 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004460 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004461 list_result.sort();
4462 assert_eq!(list_o_descriptors, list_result);
4463
4464 let mut list_o_ids: Vec<i64> = list_o_descriptors
4465 .into_iter()
4466 .map(|d| {
4467 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004468 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004469 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004470 KeyType::Client,
4471 KeyEntryLoadBits::NONE,
4472 *namespace as u32,
4473 |_, _| Ok(()),
4474 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004475 .unwrap();
4476 entry.id()
4477 })
4478 .collect();
4479 list_o_ids.sort_unstable();
4480 let mut loaded_entries: Vec<i64> = list_o_keys
4481 .iter()
4482 .filter_map(|(id, ns)| match ns {
4483 ns if *ns == *namespace => Some(*id),
4484 _ => None,
4485 })
4486 .collect();
4487 loaded_entries.sort_unstable();
4488 assert_eq!(list_o_ids, loaded_entries);
4489 }
Eran Messeri24f31972023-01-25 17:00:33 +00004490 assert_eq!(
4491 Vec::<KeyDescriptor>::new(),
4492 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4493 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004494
4495 Ok(())
4496 }
4497
Joel Galenson0891bc12020-07-20 10:37:03 -07004498 // Helpers
4499
4500 // Checks that the given result is an error containing the given string.
4501 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4502 let error_str = format!(
4503 "{:#?}",
4504 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4505 );
4506 assert!(
4507 error_str.contains(target),
4508 "The string \"{}\" should contain \"{}\"",
4509 error_str,
4510 target
4511 );
4512 }
4513
Joel Galenson2aab4432020-07-22 15:27:57 -07004514 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004515 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004516 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004517 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004518 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004519 namespace: Option<i64>,
4520 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004521 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004522 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004523 }
4524
4525 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4526 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004527 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004528 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004529 Ok(KeyEntryRow {
4530 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004531 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004532 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004533 namespace: row.get(3)?,
4534 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004535 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004536 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004537 })
4538 })?
4539 .map(|r| r.context("Could not read keyentry row."))
4540 .collect::<Result<Vec<_>>>()
4541 }
4542
Eran Messeri4dc27b52024-01-09 12:43:31 +00004543 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4544 make_test_params_with_sids(max_usage_count, &[42])
4545 }
4546
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004547 // Note: The parameters and SecurityLevel associations are nonsensical. This
4548 // collection is only used to check if the parameters are preserved as expected by the
4549 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004550 fn make_test_params_with_sids(
4551 max_usage_count: Option<i32>,
4552 user_secure_ids: &[i64],
4553 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004554 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004555 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4556 KeyParameter::new(
4557 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4558 SecurityLevel::TRUSTED_ENVIRONMENT,
4559 ),
4560 KeyParameter::new(
4561 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4562 SecurityLevel::TRUSTED_ENVIRONMENT,
4563 ),
4564 KeyParameter::new(
4565 KeyParameterValue::Algorithm(Algorithm::RSA),
4566 SecurityLevel::TRUSTED_ENVIRONMENT,
4567 ),
4568 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4569 KeyParameter::new(
4570 KeyParameterValue::BlockMode(BlockMode::ECB),
4571 SecurityLevel::TRUSTED_ENVIRONMENT,
4572 ),
4573 KeyParameter::new(
4574 KeyParameterValue::BlockMode(BlockMode::GCM),
4575 SecurityLevel::TRUSTED_ENVIRONMENT,
4576 ),
4577 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4578 KeyParameter::new(
4579 KeyParameterValue::Digest(Digest::MD5),
4580 SecurityLevel::TRUSTED_ENVIRONMENT,
4581 ),
4582 KeyParameter::new(
4583 KeyParameterValue::Digest(Digest::SHA_2_224),
4584 SecurityLevel::TRUSTED_ENVIRONMENT,
4585 ),
4586 KeyParameter::new(
4587 KeyParameterValue::Digest(Digest::SHA_2_256),
4588 SecurityLevel::STRONGBOX,
4589 ),
4590 KeyParameter::new(
4591 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4592 SecurityLevel::TRUSTED_ENVIRONMENT,
4593 ),
4594 KeyParameter::new(
4595 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4596 SecurityLevel::TRUSTED_ENVIRONMENT,
4597 ),
4598 KeyParameter::new(
4599 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4600 SecurityLevel::STRONGBOX,
4601 ),
4602 KeyParameter::new(
4603 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4604 SecurityLevel::TRUSTED_ENVIRONMENT,
4605 ),
4606 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4607 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4608 KeyParameter::new(
4609 KeyParameterValue::EcCurve(EcCurve::P_224),
4610 SecurityLevel::TRUSTED_ENVIRONMENT,
4611 ),
4612 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4613 KeyParameter::new(
4614 KeyParameterValue::EcCurve(EcCurve::P_384),
4615 SecurityLevel::TRUSTED_ENVIRONMENT,
4616 ),
4617 KeyParameter::new(
4618 KeyParameterValue::EcCurve(EcCurve::P_521),
4619 SecurityLevel::TRUSTED_ENVIRONMENT,
4620 ),
4621 KeyParameter::new(
4622 KeyParameterValue::RSAPublicExponent(3),
4623 SecurityLevel::TRUSTED_ENVIRONMENT,
4624 ),
4625 KeyParameter::new(
4626 KeyParameterValue::IncludeUniqueID,
4627 SecurityLevel::TRUSTED_ENVIRONMENT,
4628 ),
4629 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4630 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4631 KeyParameter::new(
4632 KeyParameterValue::ActiveDateTime(1234567890),
4633 SecurityLevel::STRONGBOX,
4634 ),
4635 KeyParameter::new(
4636 KeyParameterValue::OriginationExpireDateTime(1234567890),
4637 SecurityLevel::TRUSTED_ENVIRONMENT,
4638 ),
4639 KeyParameter::new(
4640 KeyParameterValue::UsageExpireDateTime(1234567890),
4641 SecurityLevel::TRUSTED_ENVIRONMENT,
4642 ),
4643 KeyParameter::new(
4644 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4645 SecurityLevel::TRUSTED_ENVIRONMENT,
4646 ),
4647 KeyParameter::new(
4648 KeyParameterValue::MaxUsesPerBoot(1234567890),
4649 SecurityLevel::TRUSTED_ENVIRONMENT,
4650 ),
4651 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004652 KeyParameter::new(
4653 KeyParameterValue::NoAuthRequired,
4654 SecurityLevel::TRUSTED_ENVIRONMENT,
4655 ),
4656 KeyParameter::new(
4657 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4658 SecurityLevel::TRUSTED_ENVIRONMENT,
4659 ),
4660 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4661 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4662 KeyParameter::new(
4663 KeyParameterValue::TrustedUserPresenceRequired,
4664 SecurityLevel::TRUSTED_ENVIRONMENT,
4665 ),
4666 KeyParameter::new(
4667 KeyParameterValue::TrustedConfirmationRequired,
4668 SecurityLevel::TRUSTED_ENVIRONMENT,
4669 ),
4670 KeyParameter::new(
4671 KeyParameterValue::UnlockedDeviceRequired,
4672 SecurityLevel::TRUSTED_ENVIRONMENT,
4673 ),
4674 KeyParameter::new(
4675 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4676 SecurityLevel::SOFTWARE,
4677 ),
4678 KeyParameter::new(
4679 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4680 SecurityLevel::SOFTWARE,
4681 ),
4682 KeyParameter::new(
4683 KeyParameterValue::CreationDateTime(12345677890),
4684 SecurityLevel::SOFTWARE,
4685 ),
4686 KeyParameter::new(
4687 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4688 SecurityLevel::TRUSTED_ENVIRONMENT,
4689 ),
4690 KeyParameter::new(
4691 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4692 SecurityLevel::TRUSTED_ENVIRONMENT,
4693 ),
4694 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4695 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4696 KeyParameter::new(
4697 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4698 SecurityLevel::SOFTWARE,
4699 ),
4700 KeyParameter::new(
4701 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4702 SecurityLevel::TRUSTED_ENVIRONMENT,
4703 ),
4704 KeyParameter::new(
4705 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4706 SecurityLevel::TRUSTED_ENVIRONMENT,
4707 ),
4708 KeyParameter::new(
4709 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4710 SecurityLevel::TRUSTED_ENVIRONMENT,
4711 ),
4712 KeyParameter::new(
4713 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4714 SecurityLevel::TRUSTED_ENVIRONMENT,
4715 ),
4716 KeyParameter::new(
4717 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4718 SecurityLevel::TRUSTED_ENVIRONMENT,
4719 ),
4720 KeyParameter::new(
4721 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4722 SecurityLevel::TRUSTED_ENVIRONMENT,
4723 ),
4724 KeyParameter::new(
4725 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4726 SecurityLevel::TRUSTED_ENVIRONMENT,
4727 ),
4728 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004729 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4730 SecurityLevel::TRUSTED_ENVIRONMENT,
4731 ),
4732 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004733 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4734 SecurityLevel::TRUSTED_ENVIRONMENT,
4735 ),
4736 KeyParameter::new(
4737 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4738 SecurityLevel::TRUSTED_ENVIRONMENT,
4739 ),
4740 KeyParameter::new(
4741 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4742 SecurityLevel::TRUSTED_ENVIRONMENT,
4743 ),
4744 KeyParameter::new(
4745 KeyParameterValue::VendorPatchLevel(3),
4746 SecurityLevel::TRUSTED_ENVIRONMENT,
4747 ),
4748 KeyParameter::new(
4749 KeyParameterValue::BootPatchLevel(4),
4750 SecurityLevel::TRUSTED_ENVIRONMENT,
4751 ),
4752 KeyParameter::new(
4753 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4754 SecurityLevel::TRUSTED_ENVIRONMENT,
4755 ),
4756 KeyParameter::new(
4757 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4758 SecurityLevel::TRUSTED_ENVIRONMENT,
4759 ),
4760 KeyParameter::new(
4761 KeyParameterValue::MacLength(256),
4762 SecurityLevel::TRUSTED_ENVIRONMENT,
4763 ),
4764 KeyParameter::new(
4765 KeyParameterValue::ResetSinceIdRotation,
4766 SecurityLevel::TRUSTED_ENVIRONMENT,
4767 ),
4768 KeyParameter::new(
4769 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4770 SecurityLevel::TRUSTED_ENVIRONMENT,
4771 ),
Qi Wub9433b52020-12-01 14:52:46 +08004772 ];
4773 if let Some(value) = max_usage_count {
4774 params.push(KeyParameter::new(
4775 KeyParameterValue::UsageCountLimit(value),
4776 SecurityLevel::SOFTWARE,
4777 ));
4778 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004779
4780 for sid in user_secure_ids.iter() {
4781 params.push(KeyParameter::new(
4782 KeyParameterValue::UserSecureID(*sid),
4783 SecurityLevel::STRONGBOX,
4784 ));
4785 }
Qi Wub9433b52020-12-01 14:52:46 +08004786 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004787 }
4788
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004789 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004790 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004791 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004792 namespace: i64,
4793 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004794 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004795 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004796 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4797 }
4798
4799 pub fn make_test_key_entry_with_sids(
4800 db: &mut KeystoreDB,
4801 domain: Domain,
4802 namespace: i64,
4803 alias: &str,
4804 max_usage_count: Option<i32>,
4805 sids: &[i64],
4806 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004807 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004808 let mut blob_metadata = BlobMetaData::new();
4809 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4810 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4811 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4812 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4813 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4814
4815 db.set_blob(
4816 &key_id,
4817 SubComponentType::KEY_BLOB,
4818 Some(TEST_KEY_BLOB),
4819 Some(&blob_metadata),
4820 )?;
4821 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4822 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004823
Eran Messeri4dc27b52024-01-09 12:43:31 +00004824 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004825 db.insert_keyparameter(&key_id, &params)?;
4826
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004827 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004828 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004829 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004830 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004831 Ok(key_id)
4832 }
4833
Qi Wub9433b52020-12-01 14:52:46 +08004834 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4835 let params = make_test_params(max_usage_count);
4836
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004837 let mut blob_metadata = BlobMetaData::new();
4838 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4839 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4840 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4841 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4842 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4843
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004844 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004845 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004846
4847 KeyEntry {
4848 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004849 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004850 cert: Some(TEST_CERT_BLOB.to_vec()),
4851 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004852 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004853 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004854 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004855 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004856 }
4857 }
4858
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004859 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004860 db: &mut KeystoreDB,
4861 domain: Domain,
4862 namespace: i64,
4863 alias: &str,
4864 logical_only: bool,
4865 ) -> Result<KeyIdGuard> {
4866 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4867 let mut blob_metadata = BlobMetaData::new();
4868 if !logical_only {
4869 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4870 }
4871 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4872
4873 db.set_blob(
4874 &key_id,
4875 SubComponentType::KEY_BLOB,
4876 Some(TEST_KEY_BLOB),
4877 Some(&blob_metadata),
4878 )?;
4879 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4880 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4881
4882 let mut params = make_test_params(None);
4883 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4884
4885 db.insert_keyparameter(&key_id, &params)?;
4886
4887 let mut metadata = KeyMetaData::new();
4888 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4889 db.insert_key_metadata(&key_id, &metadata)?;
4890 rebind_alias(db, &key_id, alias, domain, namespace)?;
4891 Ok(key_id)
4892 }
4893
Eric Biggersb0478cf2023-10-27 03:55:29 +00004894 // Creates an app key that is marked as being superencrypted by the given
4895 // super key ID and that has the given authentication and unlocked device
4896 // parameters. This does not actually superencrypt the key blob.
4897 fn make_superencrypted_key_entry(
4898 db: &mut KeystoreDB,
4899 namespace: i64,
4900 alias: &str,
4901 requires_authentication: bool,
4902 requires_unlocked_device: bool,
4903 super_key_id: i64,
4904 ) -> Result<KeyIdGuard> {
4905 let domain = Domain::APP;
4906 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4907
4908 let mut blob_metadata = BlobMetaData::new();
4909 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4910 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4911 db.set_blob(
4912 &key_id,
4913 SubComponentType::KEY_BLOB,
4914 Some(TEST_KEY_BLOB),
4915 Some(&blob_metadata),
4916 )?;
4917
4918 let mut params = vec![];
4919 if requires_unlocked_device {
4920 params.push(KeyParameter::new(
4921 KeyParameterValue::UnlockedDeviceRequired,
4922 SecurityLevel::TRUSTED_ENVIRONMENT,
4923 ));
4924 }
4925 if requires_authentication {
4926 params.push(KeyParameter::new(
4927 KeyParameterValue::UserSecureID(42),
4928 SecurityLevel::TRUSTED_ENVIRONMENT,
4929 ));
4930 }
4931 db.insert_keyparameter(&key_id, &params)?;
4932
4933 let mut metadata = KeyMetaData::new();
4934 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4935 db.insert_key_metadata(&key_id, &metadata)?;
4936
4937 rebind_alias(db, &key_id, alias, domain, namespace)?;
4938 Ok(key_id)
4939 }
4940
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004941 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4942 let mut params = make_test_params(None);
4943 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4944
4945 let mut blob_metadata = BlobMetaData::new();
4946 if !logical_only {
4947 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4948 }
4949 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4950
4951 let mut metadata = KeyMetaData::new();
4952 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4953
4954 KeyEntry {
4955 id: key_id,
4956 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4957 cert: Some(TEST_CERT_BLOB.to_vec()),
4958 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4959 km_uuid: KEYSTORE_UUID,
4960 parameters: params,
4961 metadata,
4962 pure_cert: false,
4963 }
4964 }
4965
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004966 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004967 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004968 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004969 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004970 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004971 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004972 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004973 Ok((
4974 row.get(0)?,
4975 row.get(1)?,
4976 row.get(2)?,
4977 row.get(3)?,
4978 row.get(4)?,
4979 row.get(5)?,
4980 row.get(6)?,
4981 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004982 },
4983 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004984
4985 println!("Key entry table rows:");
4986 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004987 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004988 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004989 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4990 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004991 );
4992 }
4993 Ok(())
4994 }
4995
4996 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004997 let mut stmt = db
4998 .conn
4999 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005000 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005001 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5002 })?;
5003
5004 println!("Grant table rows:");
5005 for r in rows {
5006 let (id, gt, ki, av) = r.unwrap();
5007 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5008 }
5009 Ok(())
5010 }
5011
Joel Galenson0891bc12020-07-20 10:37:03 -07005012 // Use a custom random number generator that repeats each number once.
5013 // This allows us to test repeated elements.
5014
5015 thread_local! {
Charisee43391152024-04-02 16:16:30 +00005016 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07005017 }
5018
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005019 fn reset_random() {
5020 RANDOM_COUNTER.with(|counter| {
5021 *counter.borrow_mut() = 0;
5022 })
5023 }
5024
Joel Galenson0891bc12020-07-20 10:37:03 -07005025 pub fn random() -> i64 {
5026 RANDOM_COUNTER.with(|counter| {
5027 let result = *counter.borrow() / 2;
5028 *counter.borrow_mut() += 1;
5029 result
5030 })
5031 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005032
5033 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005034 fn test_unbind_keys_for_user() -> Result<()> {
5035 let mut db = new_test_db()?;
5036 db.unbind_keys_for_user(1, false)?;
5037
5038 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5039 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5040 db.unbind_keys_for_user(2, false)?;
5041
Eran Messeri24f31972023-01-25 17:00:33 +00005042 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
5043 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005044
5045 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00005046 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005047
5048 Ok(())
5049 }
5050
5051 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005052 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5053 let mut db = new_test_db()?;
5054 let super_key = keystore2_crypto::generate_aes256_key()?;
5055 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5056 let (encrypted_super_key, metadata) =
5057 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5058
5059 let key_name_enc = SuperKeyType {
5060 alias: "test_super_key_1",
5061 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005062 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005063 };
5064
5065 let key_name_nonenc = SuperKeyType {
5066 alias: "test_super_key_2",
5067 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005068 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005069 };
5070
5071 // Install two super keys.
5072 db.store_super_key(
5073 1,
5074 &key_name_nonenc,
5075 &super_key,
5076 &BlobMetaData::new(),
5077 &KeyMetaData::new(),
5078 )?;
5079 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5080
5081 // Check that both can be found in the database.
5082 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5083 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5084
5085 // Install the same keys for a different user.
5086 db.store_super_key(
5087 2,
5088 &key_name_nonenc,
5089 &super_key,
5090 &BlobMetaData::new(),
5091 &KeyMetaData::new(),
5092 )?;
5093 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5094
5095 // Check that the second pair of keys can be found in the database.
5096 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5097 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5098
5099 // Delete only encrypted keys.
5100 db.unbind_keys_for_user(1, true)?;
5101
5102 // The encrypted superkey should be gone now.
5103 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5104 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5105
5106 // Reinsert the encrypted key.
5107 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5108
5109 // Check that both can be found in the database, again..
5110 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5111 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5112
5113 // Delete all even unencrypted keys.
5114 db.unbind_keys_for_user(1, false)?;
5115
5116 // Both should be gone now.
5117 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5118 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5119
5120 // Check that the second pair of keys was untouched.
5121 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5122 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5123
5124 Ok(())
5125 }
5126
Eric Biggersb0478cf2023-10-27 03:55:29 +00005127 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5128 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5129 }
5130
5131 // Tests the unbind_auth_bound_keys_for_user() function.
5132 #[test]
5133 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5134 let mut db = new_test_db()?;
5135 let user_id = 1;
5136 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5137 let other_user_id = 2;
5138 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5139 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5140
5141 // Create a superencryption key.
5142 let super_key = keystore2_crypto::generate_aes256_key()?;
5143 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5144 let (encrypted_super_key, blob_metadata) =
5145 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5146 db.store_super_key(
5147 user_id,
5148 super_key_type,
5149 &encrypted_super_key,
5150 &blob_metadata,
5151 &KeyMetaData::new(),
5152 )?;
5153 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5154
5155 // Store 4 superencrypted app keys, one for each possible combination of
5156 // (authentication required, unlocked device required).
5157 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5158 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5159 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5160 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5161 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5162 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5163 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5164 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5165
5166 // Also store a key for a different user that requires authentication.
5167 make_superencrypted_key_entry(
5168 &mut db,
5169 other_user_nspace,
5170 "auth_ud",
5171 true,
5172 true,
5173 super_key_id,
5174 )?;
5175
5176 db.unbind_auth_bound_keys_for_user(user_id)?;
5177
5178 // Verify that only the user's app keys that require authentication were
5179 // deleted. Keys that require an unlocked device but not authentication
5180 // should *not* have been deleted, nor should the super key have been
5181 // deleted, nor should other users' keys have been deleted.
5182 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5183 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5184 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5185 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5186 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5187 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5188
5189 Ok(())
5190 }
5191
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005192 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005193 fn test_store_super_key() -> Result<()> {
5194 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005195 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005196 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005197 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005198 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005199 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005200
5201 let (encrypted_super_key, metadata) =
5202 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005203 db.store_super_key(
5204 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005205 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005206 &encrypted_super_key,
5207 &metadata,
5208 &KeyMetaData::new(),
5209 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005210
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005211 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005212 assert!(db.key_exists(
5213 Domain::APP,
5214 1,
5215 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5216 KeyType::Super
5217 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005218
Eric Biggers673d34a2023-10-18 01:54:18 +00005219 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005220 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005221 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005222 key_entry,
5223 &pw,
5224 None,
5225 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005226
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005227 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005228 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005229
Hasini Gunasingheda895552021-01-27 19:34:37 +00005230 Ok(())
5231 }
Seth Moore78c091f2021-04-09 21:38:30 +00005232
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005233 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005234 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005235 MetricsStorage::KEY_ENTRY,
5236 MetricsStorage::KEY_ENTRY_ID_INDEX,
5237 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5238 MetricsStorage::BLOB_ENTRY,
5239 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5240 MetricsStorage::KEY_PARAMETER,
5241 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5242 MetricsStorage::KEY_METADATA,
5243 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5244 MetricsStorage::GRANT,
5245 MetricsStorage::AUTH_TOKEN,
5246 MetricsStorage::BLOB_METADATA,
5247 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005248 ]
5249 }
5250
5251 /// Perform a simple check to ensure that we can query all the storage types
5252 /// that are supported by the DB. Check for reasonable values.
5253 #[test]
5254 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005255 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005256
5257 let mut db = new_test_db()?;
5258
5259 for t in get_valid_statsd_storage_types() {
5260 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005261 // AuthToken can be less than a page since it's in a btree, not sqlite
5262 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005263 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005264 } else {
5265 assert!(stat.size >= PAGE_SIZE);
5266 }
Seth Moore78c091f2021-04-09 21:38:30 +00005267 assert!(stat.size >= stat.unused_size);
5268 }
5269
5270 Ok(())
5271 }
5272
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005273 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005274 get_valid_statsd_storage_types()
5275 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005276 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005277 .collect()
5278 }
5279
5280 fn assert_storage_increased(
5281 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005282 increased_storage_types: Vec<MetricsStorage>,
5283 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005284 ) {
5285 for storage in increased_storage_types {
5286 // Verify the expected storage increased.
5287 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005288 let old = &baseline[&storage.0];
5289 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005290 assert!(
5291 new.unused_size <= old.unused_size,
5292 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005293 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005294 new.unused_size,
5295 old.unused_size
5296 );
5297
5298 // Update the baseline with the new value so that it succeeds in the
5299 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005300 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005301 }
5302
5303 // Get an updated map of the storage and verify there were no unexpected changes.
5304 let updated_stats = get_storage_stats_map(db);
5305 assert_eq!(updated_stats.len(), baseline.len());
5306
5307 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005308 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005309 let mut s = String::new();
5310 for &k in map.keys() {
5311 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5312 .expect("string concat failed");
5313 }
5314 s
5315 };
5316
5317 assert!(
5318 updated_stats[&k].size == baseline[&k].size
5319 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5320 "updated_stats:\n{}\nbaseline:\n{}",
5321 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005322 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005323 );
5324 }
5325 }
5326
5327 #[test]
5328 fn test_verify_key_table_size_reporting() -> Result<()> {
5329 let mut db = new_test_db()?;
5330 let mut working_stats = get_storage_stats_map(&mut db);
5331
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005332 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005333 assert_storage_increased(
5334 &mut db,
5335 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005336 MetricsStorage::KEY_ENTRY,
5337 MetricsStorage::KEY_ENTRY_ID_INDEX,
5338 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005339 ],
5340 &mut working_stats,
5341 );
5342
5343 let mut blob_metadata = BlobMetaData::new();
5344 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5345 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5346 assert_storage_increased(
5347 &mut db,
5348 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005349 MetricsStorage::BLOB_ENTRY,
5350 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5351 MetricsStorage::BLOB_METADATA,
5352 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005353 ],
5354 &mut working_stats,
5355 );
5356
5357 let params = make_test_params(None);
5358 db.insert_keyparameter(&key_id, &params)?;
5359 assert_storage_increased(
5360 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005361 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005362 &mut working_stats,
5363 );
5364
5365 let mut metadata = KeyMetaData::new();
5366 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5367 db.insert_key_metadata(&key_id, &metadata)?;
5368 assert_storage_increased(
5369 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005370 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005371 &mut working_stats,
5372 );
5373
5374 let mut sum = 0;
5375 for stat in working_stats.values() {
5376 sum += stat.size;
5377 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005378 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005379 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5380
5381 Ok(())
5382 }
5383
5384 #[test]
5385 fn test_verify_auth_table_size_reporting() -> Result<()> {
5386 let mut db = new_test_db()?;
5387 let mut working_stats = get_storage_stats_map(&mut db);
5388 db.insert_auth_token(&HardwareAuthToken {
5389 challenge: 123,
5390 userId: 456,
5391 authenticatorId: 789,
5392 authenticatorType: kmhw_authenticator_type::ANY,
5393 timestamp: Timestamp { milliSeconds: 10 },
5394 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005395 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005396 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005397 Ok(())
5398 }
5399
5400 #[test]
5401 fn test_verify_grant_table_size_reporting() -> Result<()> {
5402 const OWNER: i64 = 1;
5403 let mut db = new_test_db()?;
5404 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5405
5406 let mut working_stats = get_storage_stats_map(&mut db);
5407 db.grant(
5408 &KeyDescriptor {
5409 domain: Domain::APP,
5410 nspace: 0,
5411 alias: Some(TEST_ALIAS.to_string()),
5412 blob: None,
5413 },
5414 OWNER as u32,
5415 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005416 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005417 |_, _| Ok(()),
5418 )?;
5419
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005420 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005421
5422 Ok(())
5423 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005424
5425 #[test]
5426 fn find_auth_token_entry_returns_latest() -> Result<()> {
5427 let mut db = new_test_db()?;
5428 db.insert_auth_token(&HardwareAuthToken {
5429 challenge: 123,
5430 userId: 456,
5431 authenticatorId: 789,
5432 authenticatorType: kmhw_authenticator_type::ANY,
5433 timestamp: Timestamp { milliSeconds: 10 },
5434 mac: b"mac0".to_vec(),
5435 });
5436 std::thread::sleep(std::time::Duration::from_millis(1));
5437 db.insert_auth_token(&HardwareAuthToken {
5438 challenge: 123,
5439 userId: 457,
5440 authenticatorId: 789,
5441 authenticatorType: kmhw_authenticator_type::ANY,
5442 timestamp: Timestamp { milliSeconds: 12 },
5443 mac: b"mac1".to_vec(),
5444 });
5445 std::thread::sleep(std::time::Duration::from_millis(1));
5446 db.insert_auth_token(&HardwareAuthToken {
5447 challenge: 123,
5448 userId: 458,
5449 authenticatorId: 789,
5450 authenticatorType: kmhw_authenticator_type::ANY,
5451 timestamp: Timestamp { milliSeconds: 3 },
5452 mac: b"mac2".to_vec(),
5453 });
5454 // All three entries are in the database
5455 assert_eq!(db.perboot.auth_tokens_len(), 3);
5456 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005457 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005458 Ok(())
5459 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005460
5461 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005462 fn test_load_key_descriptor() -> Result<()> {
5463 let mut db = new_test_db()?;
5464 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5465
5466 let key = db.load_key_descriptor(key_id)?.unwrap();
5467
5468 assert_eq!(key.domain, Domain::APP);
5469 assert_eq!(key.nspace, 1);
5470 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5471
5472 // No such id
5473 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5474 Ok(())
5475 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005476
5477 #[test]
5478 fn test_get_list_app_uids_for_sid() -> Result<()> {
5479 let uid: i32 = 1;
5480 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5481 let first_sid = 667;
5482 let second_sid = 669;
5483 let first_app_id: i64 = 123 + uid_offset;
5484 let second_app_id: i64 = 456 + uid_offset;
5485 let third_app_id: i64 = 789 + uid_offset;
5486 let unrelated_app_id: i64 = 1011 + uid_offset;
5487 let mut db = new_test_db()?;
5488 make_test_key_entry_with_sids(
5489 &mut db,
5490 Domain::APP,
5491 first_app_id,
5492 TEST_ALIAS,
5493 None,
5494 &[first_sid],
5495 )
5496 .context("test_get_list_app_uids_for_sid")?;
5497 make_test_key_entry_with_sids(
5498 &mut db,
5499 Domain::APP,
5500 second_app_id,
5501 "alias2",
5502 None,
5503 &[first_sid],
5504 )
5505 .context("test_get_list_app_uids_for_sid")?;
5506 make_test_key_entry_with_sids(
5507 &mut db,
5508 Domain::APP,
5509 second_app_id,
5510 TEST_ALIAS,
5511 None,
5512 &[second_sid],
5513 )
5514 .context("test_get_list_app_uids_for_sid")?;
5515 make_test_key_entry_with_sids(
5516 &mut db,
5517 Domain::APP,
5518 third_app_id,
5519 "alias3",
5520 None,
5521 &[second_sid],
5522 )
5523 .context("test_get_list_app_uids_for_sid")?;
5524 make_test_key_entry_with_sids(
5525 &mut db,
5526 Domain::APP,
5527 unrelated_app_id,
5528 TEST_ALIAS,
5529 None,
5530 &[],
5531 )
5532 .context("test_get_list_app_uids_for_sid")?;
5533
5534 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5535 first_sid_apps.sort();
5536 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5537 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5538 second_sid_apps.sort();
5539 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5540 Ok(())
5541 }
5542
5543 #[test]
5544 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5545 let uid: i32 = 1;
5546 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5547 let first_sid = 667;
5548 let second_sid = 669;
5549 let third_sid = 772;
5550 let first_app_id: i64 = 123 + uid_offset;
5551 let second_app_id: i64 = 456 + uid_offset;
5552 let mut db = new_test_db()?;
5553 make_test_key_entry_with_sids(
5554 &mut db,
5555 Domain::APP,
5556 first_app_id,
5557 TEST_ALIAS,
5558 None,
5559 &[first_sid, 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 second_app_id,
5566 "alias2",
5567 None,
5568 &[second_sid, third_sid],
5569 )
5570 .context("test_get_list_app_uids_for_sid")?;
5571
5572 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5573 assert_eq!(first_sid_apps, vec![first_app_id]);
5574
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![first_app_id, second_app_id]);
5578
5579 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5580 assert_eq!(third_sid_apps, vec![second_app_id]);
5581 Ok(())
5582 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005583}