blob: 43eaa559798fd86848a6a1802568282c11f15d08 [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
David Drysdale115c4722024-04-15 14:11:52 +010098/// If the database returns a busy error code, retry after this interval.
99const DB_BUSY_RETRY_INTERVAL: Duration = Duration::from_micros(500);
100/// If the database returns a busy error code, keep retrying for this long.
101const MAX_DB_BUSY_RETRY_PERIOD: Duration = Duration::from_secs(15);
102
103/// Check whether a database lock has timed out.
104fn check_lock_timeout(start: &std::time::Instant, timeout: Duration) -> Result<()> {
105 if keystore2_flags::database_loop_timeout() {
106 let elapsed = start.elapsed();
107 if elapsed >= timeout {
108 error!("Abandon locked DB after {elapsed:?}");
109 return Err(&KsError::Rc(ResponseCode::BACKEND_BUSY))
110 .context(ks_err!("Abandon locked DB after {elapsed:?}",));
111 }
112 }
113 Ok(())
114}
115
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800116impl_metadata!(
117 /// A set of metadata for key entries.
118 #[derive(Debug, Default, Eq, PartialEq)]
119 pub struct KeyMetaData;
120 /// A metadata entry for key entries.
121 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
122 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800123 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800124 CreationDate(DateTime) with accessor creation_date,
125 /// Expiration date for attestation keys.
126 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700127 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
128 /// provisioning
129 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
130 /// Vector representing the raw public key so results from the server can be matched
131 /// to the right entry
132 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700133 /// SEC1 public key for ECDH encryption
134 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800135 // --- ADD NEW META DATA FIELDS HERE ---
136 // For backwards compatibility add new entries only to
137 // end of this list and above this comment.
138 };
139);
140
141impl KeyMetaData {
142 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
143 let mut stmt = tx
144 .prepare(
145 "SELECT tag, data from persistent.keymetadata
146 WHERE keyentryid = ?;",
147 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000148 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800149
150 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
151
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000152 let mut rows = stmt
153 .query(params![key_id])
154 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800155 db_utils::with_rows_extract_all(&mut rows, |row| {
156 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
157 metadata.insert(
158 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700159 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800160 .context("Failed to read KeyMetaEntry.")?,
161 );
162 Ok(())
163 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000164 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800165
166 Ok(Self { data: metadata })
167 }
168
169 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
170 let mut stmt = tx
171 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000172 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800173 VALUES (?, ?, ?);",
174 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000175 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800176
177 let iter = self.data.iter();
178 for (tag, entry) in iter {
179 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000180 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800181 })?;
182 }
183 Ok(())
184 }
185}
186
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800187impl_metadata!(
188 /// A set of metadata for key blobs.
189 #[derive(Debug, Default, Eq, PartialEq)]
190 pub struct BlobMetaData;
191 /// A metadata entry for key blobs.
192 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
193 pub enum BlobMetaEntry {
194 /// If present, indicates that the blob is encrypted with another key or a key derived
195 /// from a password.
196 EncryptedBy(EncryptedBy) with accessor encrypted_by,
197 /// If the blob is password encrypted this field is set to the
198 /// salt used for the key derivation.
199 Salt(Vec<u8>) with accessor salt,
200 /// If the blob is encrypted, this field is set to the initialization vector.
201 Iv(Vec<u8>) with accessor iv,
202 /// If the blob is encrypted, this field holds the AEAD TAG.
203 AeadTag(Vec<u8>) with accessor aead_tag,
204 /// The uuid of the owning KeyMint instance.
205 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700206 /// If the key is ECDH encrypted, this is the ephemeral public key
207 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000208 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
209 /// of that key
210 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800211 // --- ADD NEW META DATA FIELDS HERE ---
212 // For backwards compatibility add new entries only to
213 // end of this list and above this comment.
214 };
215);
216
217impl BlobMetaData {
218 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
219 let mut stmt = tx
220 .prepare(
221 "SELECT tag, data from persistent.blobmetadata
222 WHERE blobentryid = ?;",
223 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000224 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800225
226 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
227
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000228 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800229 db_utils::with_rows_extract_all(&mut rows, |row| {
230 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
231 metadata.insert(
232 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700233 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800234 .context("Failed to read BlobMetaEntry.")?,
235 );
236 Ok(())
237 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000238 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800239
240 Ok(Self { data: metadata })
241 }
242
243 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
244 let mut stmt = tx
245 .prepare(
246 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
247 VALUES (?, ?, ?);",
248 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000249 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800250
251 let iter = self.data.iter();
252 for (tag, entry) in iter {
253 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000254 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800255 })?;
256 }
257 Ok(())
258 }
259}
260
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800261/// Indicates the type of the keyentry.
262#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
263pub enum KeyType {
264 /// This is a client key type. These keys are created or imported through the Keystore 2.0
265 /// AIDL interface android.system.keystore2.
266 Client,
267 /// This is a super key type. These keys are created by keystore itself and used to encrypt
268 /// other key blobs to provide LSKF binding.
269 Super,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800270}
271
272impl ToSql for KeyType {
273 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
274 Ok(ToSqlOutput::Owned(Value::Integer(match self {
275 KeyType::Client => 0,
276 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800277 })))
278 }
279}
280
281impl FromSql for KeyType {
282 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
283 match i64::column_result(value)? {
284 0 => Ok(KeyType::Client),
285 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800286 v => Err(FromSqlError::OutOfRange(v)),
287 }
288 }
289}
290
Max Bires8e93d2b2021-01-14 13:17:59 -0800291/// Uuid representation that can be stored in the database.
292/// Right now it can only be initialized from SecurityLevel.
293/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
294#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
295pub struct Uuid([u8; 16]);
296
297impl Deref for Uuid {
298 type Target = [u8; 16];
299
300 fn deref(&self) -> &Self::Target {
301 &self.0
302 }
303}
304
305impl From<SecurityLevel> for Uuid {
306 fn from(sec_level: SecurityLevel) -> Self {
307 Self((sec_level.0 as u128).to_be_bytes())
308 }
309}
310
311impl ToSql for Uuid {
312 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
313 self.0.to_sql()
314 }
315}
316
317impl FromSql for Uuid {
318 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
319 let blob = Vec::<u8>::column_result(value)?;
320 if blob.len() != 16 {
321 return Err(FromSqlError::OutOfRange(blob.len() as i64));
322 }
323 let mut arr = [0u8; 16];
324 arr.copy_from_slice(&blob);
325 Ok(Self(arr))
326 }
327}
328
329/// Key entries that are not associated with any KeyMint instance, such as pure certificate
330/// entries are associated with this UUID.
331pub static KEYSTORE_UUID: Uuid = Uuid([
332 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
333]);
334
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800335/// Indicates how the sensitive part of this key blob is encrypted.
336#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
337pub enum EncryptedBy {
338 /// The keyblob is encrypted by a user password.
339 /// In the database this variant is represented as NULL.
340 Password,
341 /// The keyblob is encrypted by another key with wrapped key id.
342 /// In the database this variant is represented as non NULL value
343 /// that is convertible to i64, typically NUMERIC.
344 KeyId(i64),
345}
346
347impl ToSql for EncryptedBy {
348 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
349 match self {
350 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
351 Self::KeyId(id) => id.to_sql(),
352 }
353 }
354}
355
356impl FromSql for EncryptedBy {
357 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
358 match value {
359 ValueRef::Null => Ok(Self::Password),
360 _ => Ok(Self::KeyId(i64::column_result(value)?)),
361 }
362 }
363}
364
365/// A database representation of wall clock time. DateTime stores unix epoch time as
366/// i64 in milliseconds.
367#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
368pub struct DateTime(i64);
369
370/// Error type returned when creating DateTime or converting it from and to
371/// SystemTime.
372#[derive(thiserror::Error, Debug)]
373pub enum DateTimeError {
374 /// This is returned when SystemTime and Duration computations fail.
375 #[error(transparent)]
376 SystemTimeError(#[from] SystemTimeError),
377
378 /// This is returned when type conversions fail.
379 #[error(transparent)]
380 TypeConversion(#[from] std::num::TryFromIntError),
381
382 /// This is returned when checked time arithmetic failed.
383 #[error("Time arithmetic failed.")]
384 TimeArithmetic,
385}
386
387impl DateTime {
388 /// Constructs a new DateTime object denoting the current time. This may fail during
389 /// conversion to unix epoch time and during conversion to the internal i64 representation.
390 pub fn now() -> Result<Self, DateTimeError> {
391 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
392 }
393
394 /// Constructs a new DateTime object from milliseconds.
395 pub fn from_millis_epoch(millis: i64) -> Self {
396 Self(millis)
397 }
398
399 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700400 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800401 self.0
402 }
403
404 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700405 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800406 self.0 / 1000
407 }
408}
409
410impl ToSql for DateTime {
411 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
412 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
413 }
414}
415
416impl FromSql for DateTime {
417 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
418 Ok(Self(i64::column_result(value)?))
419 }
420}
421
422impl TryInto<SystemTime> for DateTime {
423 type Error = DateTimeError;
424
425 fn try_into(self) -> Result<SystemTime, Self::Error> {
426 // We want to construct a SystemTime representation equivalent to self, denoting
427 // a point in time THEN, but we cannot set the time directly. We can only construct
428 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
429 // and between EPOCH and THEN. With this common reference we can construct the
430 // duration between NOW and THEN which we can add to our SystemTime representation
431 // of NOW to get a SystemTime representation of THEN.
432 // Durations can only be positive, thus the if statement below.
433 let now = SystemTime::now();
434 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
435 let then_epoch = Duration::from_millis(self.0.try_into()?);
436 Ok(if now_epoch > then_epoch {
437 // then = now - (now_epoch - then_epoch)
438 now_epoch
439 .checked_sub(then_epoch)
440 .and_then(|d| now.checked_sub(d))
441 .ok_or(DateTimeError::TimeArithmetic)?
442 } else {
443 // then = now + (then_epoch - now_epoch)
444 then_epoch
445 .checked_sub(now_epoch)
446 .and_then(|d| now.checked_add(d))
447 .ok_or(DateTimeError::TimeArithmetic)?
448 })
449 }
450}
451
452impl TryFrom<SystemTime> for DateTime {
453 type Error = DateTimeError;
454
455 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
456 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
457 }
458}
459
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800460#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
461enum KeyLifeCycle {
462 /// Existing keys have a key ID but are not fully populated yet.
463 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
464 /// them to Unreferenced for garbage collection.
465 Existing,
466 /// A live key is fully populated and usable by clients.
467 Live,
468 /// An unreferenced key is scheduled for garbage collection.
469 Unreferenced,
470}
471
472impl ToSql for KeyLifeCycle {
473 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
474 match self {
475 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
476 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
477 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
478 }
479 }
480}
481
482impl FromSql for KeyLifeCycle {
483 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
484 match i64::column_result(value)? {
485 0 => Ok(KeyLifeCycle::Existing),
486 1 => Ok(KeyLifeCycle::Live),
487 2 => Ok(KeyLifeCycle::Unreferenced),
488 v => Err(FromSqlError::OutOfRange(v)),
489 }
490 }
491}
492
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700493/// Keys have a KeyMint blob component and optional public certificate and
494/// certificate chain components.
495/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
496/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800497#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700498pub struct KeyEntryLoadBits(u32);
499
500impl KeyEntryLoadBits {
501 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
502 pub const NONE: KeyEntryLoadBits = Self(0);
503 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
504 pub const KM: KeyEntryLoadBits = Self(1);
505 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
506 pub const PUBLIC: KeyEntryLoadBits = Self(2);
507 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
508 pub const BOTH: KeyEntryLoadBits = Self(3);
509
510 /// Returns true if this object indicates that the public components shall be loaded.
511 pub const fn load_public(&self) -> bool {
512 self.0 & Self::PUBLIC.0 != 0
513 }
514
515 /// Returns true if the object indicates that the KeyMint component shall be loaded.
516 pub const fn load_km(&self) -> bool {
517 self.0 & Self::KM.0 != 0
518 }
519}
520
Janis Danisevskisaec14592020-11-12 09:41:49 -0800521lazy_static! {
522 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
523}
524
525struct KeyIdLockDb {
526 locked_keys: Mutex<HashSet<i64>>,
527 cond_var: Condvar,
528}
529
530/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
531/// from the database a second time. Most functions manipulating the key blob database
532/// require a KeyIdGuard.
533#[derive(Debug)]
534pub struct KeyIdGuard(i64);
535
536impl KeyIdLockDb {
537 fn new() -> Self {
538 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
539 }
540
541 /// This function blocks until an exclusive lock for the given key entry id can
542 /// be acquired. It returns a guard object, that represents the lifecycle of the
543 /// acquired lock.
544 pub fn get(&self, key_id: i64) -> KeyIdGuard {
545 let mut locked_keys = self.locked_keys.lock().unwrap();
546 while locked_keys.contains(&key_id) {
547 locked_keys = self.cond_var.wait(locked_keys).unwrap();
548 }
549 locked_keys.insert(key_id);
550 KeyIdGuard(key_id)
551 }
552
553 /// This function attempts to acquire an exclusive lock on a given key id. If the
554 /// given key id is already taken the function returns None immediately. If a lock
555 /// can be acquired this function returns a guard object, that represents the
556 /// lifecycle of the acquired lock.
557 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
558 let mut locked_keys = self.locked_keys.lock().unwrap();
559 if locked_keys.insert(key_id) {
560 Some(KeyIdGuard(key_id))
561 } else {
562 None
563 }
564 }
565}
566
567impl KeyIdGuard {
568 /// Get the numeric key id of the locked key.
569 pub fn id(&self) -> i64 {
570 self.0
571 }
572}
573
574impl Drop for KeyIdGuard {
575 fn drop(&mut self) {
576 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
577 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800578 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800579 KEY_ID_LOCK.cond_var.notify_all();
580 }
581}
582
Max Bires8e93d2b2021-01-14 13:17:59 -0800583/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700584#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800585pub struct CertificateInfo {
586 cert: Option<Vec<u8>>,
587 cert_chain: Option<Vec<u8>>,
588}
589
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800590/// This type represents a Blob with its metadata and an optional superseded blob.
591#[derive(Debug)]
592pub struct BlobInfo<'a> {
593 blob: &'a [u8],
594 metadata: &'a BlobMetaData,
595 /// Superseded blobs are an artifact of legacy import. In some rare occasions
596 /// the key blob needs to be upgraded during import. In that case two
597 /// blob are imported, the superseded one will have to be imported first,
598 /// so that the garbage collector can reap it.
599 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
600}
601
602impl<'a> BlobInfo<'a> {
603 /// Create a new instance of blob info with blob and corresponding metadata
604 /// and no superseded blob info.
605 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
606 Self { blob, metadata, superseded_blob: None }
607 }
608
609 /// Create a new instance of blob info with blob and corresponding metadata
610 /// as well as superseded blob info.
611 pub fn new_with_superseded(
612 blob: &'a [u8],
613 metadata: &'a BlobMetaData,
614 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
615 ) -> Self {
616 Self { blob, metadata, superseded_blob }
617 }
618}
619
Max Bires8e93d2b2021-01-14 13:17:59 -0800620impl CertificateInfo {
621 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
622 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
623 Self { cert, cert_chain }
624 }
625
626 /// Take the cert
627 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
628 self.cert.take()
629 }
630
631 /// Take the cert chain
632 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
633 self.cert_chain.take()
634 }
635}
636
Max Bires2b2e6562020-09-22 11:22:36 -0700637/// This type represents a certificate chain with a private key corresponding to the leaf
638/// 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 -0700639pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800640 /// A KM key blob
641 pub private_key: ZVec,
642 /// A batch cert for private_key
643 pub batch_cert: Vec<u8>,
644 /// A full certificate chain from root signing authority to private_key, including batch_cert
645 /// for convenience.
646 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700647}
648
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700649/// This type represents a Keystore 2.0 key entry.
650/// An entry has a unique `id` by which it can be found in the database.
651/// It has a security level field, key parameters, and three optional fields
652/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800653#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700654pub struct KeyEntry {
655 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800656 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700657 cert: Option<Vec<u8>>,
658 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800659 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700660 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800661 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800662 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700663}
664
665impl KeyEntry {
666 /// Returns the unique id of the Key entry.
667 pub fn id(&self) -> i64 {
668 self.id
669 }
670 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800671 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
672 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700673 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800674 /// Extracts the Optional KeyMint blob including its metadata.
675 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
676 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677 }
678 /// Exposes the optional public certificate.
679 pub fn cert(&self) -> &Option<Vec<u8>> {
680 &self.cert
681 }
682 /// Extracts the optional public certificate.
683 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
684 self.cert.take()
685 }
686 /// Exposes the optional public certificate chain.
687 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
688 &self.cert_chain
689 }
690 /// Extracts the optional public certificate_chain.
691 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
692 self.cert_chain.take()
693 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800694 /// Returns the uuid of the owning KeyMint instance.
695 pub fn km_uuid(&self) -> &Uuid {
696 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700697 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700698 /// Exposes the key parameters of this key entry.
699 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
700 &self.parameters
701 }
702 /// Consumes this key entry and extracts the keyparameters from it.
703 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
704 self.parameters
705 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800706 /// Exposes the key metadata of this key entry.
707 pub fn metadata(&self) -> &KeyMetaData {
708 &self.metadata
709 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800710 /// This returns true if the entry is a pure certificate entry with no
711 /// private key component.
712 pub fn pure_cert(&self) -> bool {
713 self.pure_cert
714 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000715 /// Consumes this key entry and extracts the keyparameters and metadata from it.
716 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
717 (self.parameters, self.metadata)
718 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700719}
720
721/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800722#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700723pub struct SubComponentType(u32);
724impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800725 /// Persistent identifier for a key blob.
726 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700727 /// Persistent identifier for a certificate blob.
728 pub const CERT: SubComponentType = Self(1);
729 /// Persistent identifier for a certificate chain blob.
730 pub const CERT_CHAIN: SubComponentType = Self(2);
731}
732
733impl ToSql for SubComponentType {
734 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
735 self.0.to_sql()
736 }
737}
738
739impl FromSql for SubComponentType {
740 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
741 Ok(Self(u32::column_result(value)?))
742 }
743}
744
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800745/// This trait is private to the database module. It is used to convey whether or not the garbage
746/// collector shall be invoked after a database access. All closures passed to
747/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
748/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
749/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
750/// `.need_gc()`.
751trait DoGc<T> {
752 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
753
754 fn no_gc(self) -> Result<(bool, T)>;
755
756 fn need_gc(self) -> Result<(bool, T)>;
757}
758
759impl<T> DoGc<T> for Result<T> {
760 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
761 self.map(|r| (need_gc, r))
762 }
763
764 fn no_gc(self) -> Result<(bool, T)> {
765 self.do_gc(false)
766 }
767
768 fn need_gc(self) -> Result<(bool, T)> {
769 self.do_gc(true)
770 }
771}
772
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700773/// KeystoreDB wraps a connection to an SQLite database and tracks its
774/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700775pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700776 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700777 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700778 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700779}
780
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000781/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000782/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000783#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000784pub struct BootTime(i64);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000785
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000786impl BootTime {
787 /// Constructs a new BootTime
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000789 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000790 }
791
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000792 /// Returns the value of BootTime in milliseconds as i64
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000793 pub fn milliseconds(&self) -> i64 {
794 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000795 }
796
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000797 /// Returns the integer value of BootTime as i64
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000798 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000799 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000800 }
801
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800802 /// Like i64::checked_sub.
803 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
804 self.0.checked_sub(other.0).map(Self)
805 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000806}
807
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000808impl ToSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000809 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
810 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
811 }
812}
813
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000814impl FromSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000815 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
816 Ok(Self(i64::column_result(value)?))
817 }
818}
819
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000820/// This struct encapsulates the information to be stored in the database about the auth tokens
821/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700822#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000823pub struct AuthTokenEntry {
824 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000825 // Time received in milliseconds
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000826 time_received: BootTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000827}
828
829impl AuthTokenEntry {
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000830 fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000831 AuthTokenEntry { auth_token, time_received }
832 }
833
834 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800835 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000836 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800837 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000838 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000839 })
840 }
841
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000842 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800843 pub fn auth_token(&self) -> &HardwareAuthToken {
844 &self.auth_token
845 }
846
847 /// Returns the auth token wrapped by the AuthTokenEntry
848 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000849 self.auth_token
850 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800851
852 /// Returns the time that this auth token was received.
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000853 pub fn time_received(&self) -> BootTime {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800854 self.time_received
855 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000856
857 /// Returns the challenge value of the auth token.
858 pub fn challenge(&self) -> i64 {
859 self.auth_token.challenge
860 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000861}
862
Joel Galenson26f4d012020-07-17 14:57:21 -0700863impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800864 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700865 const CURRENT_DB_VERSION: u32 = 1;
866 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800867
Seth Moore78c091f2021-04-09 21:38:30 +0000868 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700869 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000870
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700871 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800872 /// files persistent.sqlite and perboot.sqlite in the given directory.
873 /// It also attempts to initialize all of the tables.
874 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700875 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700876 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700877 let _wp = wd::watch_millis("KeystoreDB::new", 500);
878
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700879 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700880 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800881
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700882 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800883 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700884 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000885 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800886 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800887 })?;
888 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700889 }
890
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700891 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
892 // cryptographic binding to the boot level keys was implemented.
893 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
894 tx.execute(
895 "UPDATE persistent.keyentry SET state = ?
896 WHERE
897 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
898 AND
899 id NOT IN (
900 SELECT keyentryid FROM persistent.blobentry
901 WHERE id IN (
902 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
903 )
904 );",
905 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
906 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000907 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700908 Ok(1)
909 }
910
Janis Danisevskis66784c42021-01-27 08:40:25 -0800911 fn init_tables(tx: &Transaction) -> Result<()> {
912 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700913 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700914 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800915 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700916 domain INTEGER,
917 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800918 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800919 state INTEGER,
920 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000921 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700922 )
923 .context("Failed to initialize \"keyentry\" table.")?;
924
Janis Danisevskis66784c42021-01-27 08:40:25 -0800925 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800926 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
927 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000928 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800929 )
930 .context("Failed to create index keyentry_id_index.")?;
931
932 tx.execute(
933 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
934 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000935 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800936 )
937 .context("Failed to create index keyentry_domain_namespace_index.")?;
938
939 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700940 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
941 id INTEGER PRIMARY KEY,
942 subcomponent_type INTEGER,
943 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800944 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000945 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700946 )
947 .context("Failed to initialize \"blobentry\" table.")?;
948
Janis Danisevskis66784c42021-01-27 08:40:25 -0800949 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800950 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
951 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000952 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800953 )
954 .context("Failed to create index blobentry_keyentryid_index.")?;
955
956 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800957 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
958 id INTEGER PRIMARY KEY,
959 blobentryid INTEGER,
960 tag INTEGER,
961 data ANY,
962 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000963 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800964 )
965 .context("Failed to initialize \"blobmetadata\" table.")?;
966
967 tx.execute(
968 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
969 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000970 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800971 )
972 .context("Failed to create index blobmetadata_blobentryid_index.")?;
973
974 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700975 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000976 keyentryid INTEGER,
977 tag INTEGER,
978 data ANY,
979 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000980 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700981 )
982 .context("Failed to initialize \"keyparameter\" table.")?;
983
Janis Danisevskis66784c42021-01-27 08:40:25 -0800984 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800985 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
986 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000987 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800988 )
989 .context("Failed to create index keyparameter_keyentryid_index.")?;
990
991 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800992 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
993 keyentryid INTEGER,
994 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000995 data ANY,
996 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000997 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800998 )
999 .context("Failed to initialize \"keymetadata\" table.")?;
1000
Janis Danisevskis66784c42021-01-27 08:40:25 -08001001 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -08001002 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
1003 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001004 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -08001005 )
1006 .context("Failed to create index keymetadata_keyentryid_index.")?;
1007
1008 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001009 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001010 id INTEGER UNIQUE,
1011 grantee INTEGER,
1012 keyentryid INTEGER,
1013 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001014 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001015 )
1016 .context("Failed to initialize \"grant\" table.")?;
1017
Joel Galenson0891bc12020-07-20 10:37:03 -07001018 Ok(())
1019 }
1020
Seth Moore472fcbb2021-05-12 10:07:51 -07001021 fn make_persistent_path(db_root: &Path) -> Result<String> {
1022 // Build the path to the sqlite file.
1023 let mut persistent_path = db_root.to_path_buf();
1024 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1025
1026 // Now convert them to strings prefixed with "file:"
1027 let mut persistent_path_str = "file:".to_owned();
1028 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1029
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001030 // Connect to database in specific mode
1031 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1032 "?journal_mode=WAL".to_owned()
1033 } else {
1034 "?journal_mode=DELETE".to_owned()
1035 };
1036 persistent_path_str.push_str(&persistent_path_mode);
1037
Seth Moore472fcbb2021-05-12 10:07:51 -07001038 Ok(persistent_path_str)
1039 }
1040
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001041 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001042 let conn =
1043 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1044
Janis Danisevskis66784c42021-01-27 08:40:25 -08001045 loop {
1046 if let Err(e) = conn
1047 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1048 .context("Failed to attach database persistent.")
1049 {
1050 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001051 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001052 continue;
1053 } else {
1054 return Err(e);
1055 }
1056 }
1057 break;
1058 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001059
Matthew Maurer4fb19112021-05-06 15:40:44 -07001060 // Drop the cache size from default (2M) to 0.5M
1061 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1062 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001063
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001064 Ok(conn)
1065 }
1066
Seth Moore78c091f2021-04-09 21:38:30 +00001067 fn do_table_size_query(
1068 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001069 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001070 query: &str,
1071 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001072 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001073 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001074 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001075 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001076 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001077 })
1078 .no_gc()
1079 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001080 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001081 }
1082
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001083 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001084 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001085 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001086 "SELECT page_count * page_size, freelist_count * page_size
1087 FROM pragma_page_count('persistent'),
1088 pragma_page_size('persistent'),
1089 persistent.pragma_freelist_count();",
1090 &[],
1091 )
1092 }
1093
1094 fn get_table_size(
1095 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001096 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001097 schema: &str,
1098 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001099 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001100 self.do_table_size_query(
1101 storage_type,
1102 "SELECT pgsize,unused FROM dbstat(?1)
1103 WHERE name=?2 AND aggregate=TRUE;",
1104 &[schema, table],
1105 )
1106 }
1107
1108 /// Fetches a storage statisitics atom for a given storage type. For storage
1109 /// types that map to a table, information about the table's storage is
1110 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001111 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001112 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1113
Seth Moore78c091f2021-04-09 21:38:30 +00001114 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001115 MetricsStorage::DATABASE => self.get_total_size(),
1116 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "keyentry")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001120 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1121 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001123 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1124 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001125 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001126 self.get_table_size(storage_type, "persistent", "blobentry")
1127 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001128 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001129 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1130 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001131 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001132 self.get_table_size(storage_type, "persistent", "keyparameter")
1133 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001134 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001135 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1136 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001137 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001138 self.get_table_size(storage_type, "persistent", "keymetadata")
1139 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001140 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001141 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1142 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001143 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1144 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001145 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1146 // reportable
1147 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001148 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001149 storage_type,
1150 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001151 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001152 unused_size: 0,
1153 })
Seth Moore78c091f2021-04-09 21:38:30 +00001154 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001155 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001156 self.get_table_size(storage_type, "persistent", "blobmetadata")
1157 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001158 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001159 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1160 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001161 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001162 }
1163 }
1164
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001165 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001166 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1167 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001168 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1169 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001170 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001171 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 blob_ids_to_delete: &[i64],
1173 max_blobs: usize,
1174 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001175 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001176 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001177 // Delete the given blobs.
1178 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001179 tx.execute(
1180 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001181 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001182 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001183 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001184 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001185 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001186 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001187
1188 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1189
Janis Danisevskis3395f862021-05-06 10:54:17 -07001190 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1191 let result: Vec<(i64, Vec<u8>)> = {
1192 let mut stmt = tx
1193 .prepare(
1194 "SELECT id, blob FROM persistent.blobentry
1195 WHERE subcomponent_type = ?
1196 AND (
1197 id NOT IN (
1198 SELECT MAX(id) FROM persistent.blobentry
1199 WHERE subcomponent_type = ?
1200 GROUP BY keyentryid, subcomponent_type
1201 )
1202 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1203 ) LIMIT ?;",
1204 )
1205 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001206
Janis Danisevskis3395f862021-05-06 10:54:17 -07001207 let rows = stmt
1208 .query_map(
1209 params![
1210 SubComponentType::KEY_BLOB,
1211 SubComponentType::KEY_BLOB,
1212 max_blobs as i64,
1213 ],
1214 |row| Ok((row.get(0)?, row.get(1)?)),
1215 )
1216 .context("Trying to query superseded blob.")?;
1217
1218 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1219 .context("Trying to extract superseded blobs.")?
1220 };
1221
1222 let result = result
1223 .into_iter()
1224 .map(|(blob_id, blob)| {
1225 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1226 })
1227 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1228 .context("Trying to load blob metadata.")?;
1229 if !result.is_empty() {
1230 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001231 }
1232
1233 // We did not find any superseded key blob, so let's remove other superseded blob in
1234 // one transaction.
1235 tx.execute(
1236 "DELETE FROM persistent.blobentry
1237 WHERE NOT subcomponent_type = ?
1238 AND (
1239 id NOT IN (
1240 SELECT MAX(id) FROM persistent.blobentry
1241 WHERE NOT subcomponent_type = ?
1242 GROUP BY keyentryid, subcomponent_type
1243 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1244 );",
1245 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1246 )
1247 .context("Trying to purge superseded blobs.")?;
1248
Janis Danisevskis3395f862021-05-06 10:54:17 -07001249 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001250 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001251 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001252 }
1253
1254 /// This maintenance function should be called only once before the database is used for the
1255 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1256 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1257 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1258 /// Keystore crashed at some point during key generation. Callers may want to log such
1259 /// occurrences.
1260 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1261 /// it to `KeyLifeCycle::Live` may have grants.
1262 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001263 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1264
Janis Danisevskis66784c42021-01-27 08:40:25 -08001265 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1266 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001267 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1268 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1269 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001270 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001271 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001272 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001273 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001274 }
1275
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001276 /// Checks if a key exists with given key type and key descriptor properties.
1277 pub fn key_exists(
1278 &mut self,
1279 domain: Domain,
1280 nspace: i64,
1281 alias: &str,
1282 key_type: KeyType,
1283 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001284 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1285
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001286 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1287 let key_descriptor =
1288 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001289 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001290 match result {
1291 Ok(_) => Ok(true),
1292 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1293 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001294 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001295 },
1296 }
1297 .no_gc()
1298 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001299 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001300 }
1301
Hasini Gunasingheda895552021-01-27 19:34:37 +00001302 /// Stores a super key in the database.
1303 pub fn store_super_key(
1304 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001305 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001306 key_type: &SuperKeyType,
1307 blob: &[u8],
1308 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001309 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001310 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001311 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1312
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1314 let key_id = Self::insert_with_retry(|id| {
1315 tx.execute(
1316 "INSERT into persistent.keyentry
1317 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001318 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001319 params![
1320 id,
1321 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001322 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001323 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001324 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001325 KeyLifeCycle::Live,
1326 &KEYSTORE_UUID,
1327 ],
1328 )
1329 })
1330 .context("Failed to insert into keyentry table.")?;
1331
Paul Crowley8d5b2532021-03-19 10:53:07 -07001332 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1333
Hasini Gunasingheda895552021-01-27 19:34:37 +00001334 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001335 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001336 key_id,
1337 SubComponentType::KEY_BLOB,
1338 Some(blob),
1339 Some(blob_metadata),
1340 )
1341 .context("Failed to store key blob.")?;
1342
1343 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1344 .context("Trying to load key components.")
1345 .no_gc()
1346 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001347 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001348 }
1349
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001350 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001351 pub fn load_super_key(
1352 &mut self,
1353 key_type: &SuperKeyType,
1354 user_id: u32,
1355 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001356 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1357
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001358 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1359 let key_descriptor = KeyDescriptor {
1360 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001361 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001362 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001363 blob: None,
1364 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001365 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001366 match id {
1367 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001368 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001369 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001370 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1371 }
1372 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1373 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001374 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001375 },
1376 }
1377 .no_gc()
1378 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001379 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001380 }
1381
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001382 /// Atomically loads a key entry and associated metadata or creates it using the
1383 /// callback create_new_key callback. The callback is called during a database
1384 /// transaction. This means that implementers should be mindful about using
1385 /// blocking operations such as IPC or grabbing mutexes.
1386 pub fn get_or_create_key_with<F>(
1387 &mut self,
1388 domain: Domain,
1389 namespace: i64,
1390 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001391 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001392 create_new_key: F,
1393 ) -> Result<(KeyIdGuard, KeyEntry)>
1394 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001395 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001396 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001397 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1398
Janis Danisevskis66784c42021-01-27 08:40:25 -08001399 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1400 let id = {
1401 let mut stmt = tx
1402 .prepare(
1403 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001404 WHERE
1405 key_type = ?
1406 AND domain = ?
1407 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001408 AND alias = ?
1409 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001410 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001411 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 let mut rows = stmt
1413 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001414 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001415
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 db_utils::with_rows_extract_one(&mut rows, |row| {
1417 Ok(match row {
1418 Some(r) => r.get(0).context("Failed to unpack id.")?,
1419 None => None,
1420 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001421 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001422 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001423 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001424
Janis Danisevskis66784c42021-01-27 08:40:25 -08001425 let (id, entry) = match id {
1426 Some(id) => (
1427 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001428 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001429 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001430
Janis Danisevskis66784c42021-01-27 08:40:25 -08001431 None => {
1432 let id = Self::insert_with_retry(|id| {
1433 tx.execute(
1434 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001435 (id, key_type, domain, namespace, alias, state, km_uuid)
1436 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001437 params![
1438 id,
1439 KeyType::Super,
1440 domain.0,
1441 namespace,
1442 alias,
1443 KeyLifeCycle::Live,
1444 km_uuid,
1445 ],
1446 )
1447 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001448 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001449
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001450 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001451 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001452 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001453 id,
1454 SubComponentType::KEY_BLOB,
1455 Some(&blob),
1456 Some(&metadata),
1457 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001458 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001459 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001460 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001461 KeyEntry {
1462 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001463 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 pure_cert: false,
1465 ..Default::default()
1466 },
1467 )
1468 }
1469 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001470 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001471 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001472 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001473 }
1474
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001475 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001476 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1477 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001478 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1479 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001480 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001481 {
David Drysdale115c4722024-04-15 14:11:52 +01001482 self.with_transaction_timeout(behavior, MAX_DB_BUSY_RETRY_PERIOD, f)
1483 }
1484 fn with_transaction_timeout<T, F>(
1485 &mut self,
1486 behavior: TransactionBehavior,
1487 timeout: Duration,
1488 f: F,
1489 ) -> Result<T>
1490 where
1491 F: Fn(&Transaction) -> Result<(bool, T)>,
1492 {
1493 let start = std::time::Instant::now();
Janis Danisevskis66784c42021-01-27 08:40:25 -08001494 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001495 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001496 .conn
1497 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001498 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001499 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1500 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001501 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001502 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001503 });
1504 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001505 Ok(result) => break Ok(result),
1506 Err(e) => {
1507 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001508 check_lock_timeout(&start, timeout)?;
1509 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001510 continue;
1511 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001512 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001513 }
1514 }
1515 }
1516 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001517 .map(|(need_gc, result)| {
1518 if need_gc {
1519 if let Some(ref gc) = self.gc {
1520 gc.notify_gc();
1521 }
1522 }
1523 result
1524 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001525 }
1526
1527 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001528 matches!(
1529 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1530 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1531 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1532 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001533 }
1534
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001535 /// Creates a new key entry and allocates a new randomized id for the new key.
1536 /// The key id gets associated with a domain and namespace but not with an alias.
1537 /// To complete key generation `rebind_alias` should be called after all of the
1538 /// key artifacts, i.e., blobs and parameters have been associated with the new
1539 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1540 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001541 pub fn create_key_entry(
1542 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001543 domain: &Domain,
1544 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001545 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001546 km_uuid: &Uuid,
1547 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001548 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1549
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001550 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001551 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001553 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001554 }
1555
1556 fn create_key_entry_internal(
1557 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001558 domain: &Domain,
1559 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001560 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001561 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001562 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001563 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001564 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001565 _ => {
1566 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001567 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001568 }
1569 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001570 Ok(KEY_ID_LOCK.get(
1571 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001572 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001573 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001574 (id, key_type, domain, namespace, alias, state, km_uuid)
1575 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001576 params![
1577 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001578 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001579 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001580 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001581 KeyLifeCycle::Existing,
1582 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001583 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001584 )
1585 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001586 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001587 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001588 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001589
Janis Danisevskis377d1002021-01-27 19:07:48 -08001590 /// Set a new blob and associates it with the given key id. Each blob
1591 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001592 /// Each key can have one of each sub component type associated. If more
1593 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001594 /// will get garbage collected.
1595 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1596 /// removed by setting blob to None.
1597 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001598 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001599 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001600 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001601 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001602 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001603 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001604 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1605
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001606 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001607 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001608 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001609 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001610 }
1611
Janis Danisevskiseed69842021-02-18 20:04:10 -08001612 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1613 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1614 /// We use this to insert key blobs into the database which can then be garbage collected
1615 /// lazily by the key garbage collector.
1616 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001617 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1618
Janis Danisevskiseed69842021-02-18 20:04:10 -08001619 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1620 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001621 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001622 Self::UNASSIGNED_KEY_ID,
1623 SubComponentType::KEY_BLOB,
1624 Some(blob),
1625 Some(blob_metadata),
1626 )
1627 .need_gc()
1628 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001629 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001630 }
1631
Janis Danisevskis377d1002021-01-27 19:07:48 -08001632 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001633 tx: &Transaction,
1634 key_id: i64,
1635 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001636 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001637 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001638 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001639 match (blob, sc_type) {
1640 (Some(blob), _) => {
1641 tx.execute(
1642 "INSERT INTO persistent.blobentry
1643 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1644 params![sc_type, key_id, blob],
1645 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001646 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001647 if let Some(blob_metadata) = blob_metadata {
1648 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001649 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001650 row.get(0)
1651 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001652 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001653 blob_metadata
1654 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001655 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001656 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001657 }
1658 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1659 tx.execute(
1660 "DELETE FROM persistent.blobentry
1661 WHERE subcomponent_type = ? AND keyentryid = ?;",
1662 params![sc_type, key_id],
1663 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001664 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001665 }
1666 (None, _) => {
1667 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001668 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001669 }
1670 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001671 Ok(())
1672 }
1673
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001674 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1675 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001676 #[cfg(test)]
1677 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001678 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001679 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001680 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001681 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001682 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001683
Janis Danisevskis66784c42021-01-27 08:40:25 -08001684 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 tx: &Transaction,
1686 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001687 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001688 ) -> Result<()> {
1689 let mut stmt = tx
1690 .prepare(
1691 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1692 VALUES (?, ?, ?, ?);",
1693 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001694 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001695
Janis Danisevskis66784c42021-01-27 08:40:25 -08001696 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001697 stmt.insert(params![
1698 key_id.0,
1699 p.get_tag().0,
1700 p.key_parameter_value(),
1701 p.security_level().0
1702 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001703 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001704 }
1705 Ok(())
1706 }
1707
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001708 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001709 #[cfg(test)]
1710 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001711 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001712 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001713 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001714 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001715 }
1716
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001717 /// Updates the alias column of the given key id `newid` with the given alias,
1718 /// and atomically, removes the alias, domain, and namespace from another row
1719 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001720 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1721 /// collector.
1722 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001723 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001724 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001725 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001726 domain: &Domain,
1727 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001728 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001729 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001730 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001731 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001732 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001733 return Err(KsError::sys())
1734 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001735 }
1736 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001737 let updated = tx
1738 .execute(
1739 "UPDATE persistent.keyentry
1740 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001741 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1742 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001743 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001744 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001745 let result = tx
1746 .execute(
1747 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001748 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001749 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001750 params![
1751 alias,
1752 KeyLifeCycle::Live,
1753 newid.0,
1754 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001755 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001756 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001757 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001758 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001759 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001760 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001761 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001762 return Err(KsError::sys()).context(ks_err!(
1763 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001764 result
1765 ));
1766 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001767 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001768 }
1769
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001770 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1771 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1772 pub fn migrate_key_namespace(
1773 &mut self,
1774 key_id_guard: KeyIdGuard,
1775 destination: &KeyDescriptor,
1776 caller_uid: u32,
1777 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1778 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001779 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1780
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001781 let destination = match destination.domain {
1782 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1783 Domain::SELINUX => (*destination).clone(),
1784 domain => {
1785 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1786 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1787 }
1788 };
1789
1790 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001791 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001792
1793 let alias = destination
1794 .alias
1795 .as_ref()
1796 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001797 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001798
1799 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1800 // Query the destination location. If there is a key, the migration request fails.
1801 if tx
1802 .query_row(
1803 "SELECT id FROM persistent.keyentry
1804 WHERE alias = ? AND domain = ? AND namespace = ?;",
1805 params![alias, destination.domain.0, destination.nspace],
1806 |_| Ok(()),
1807 )
1808 .optional()
1809 .context("Failed to query destination.")?
1810 .is_some()
1811 {
1812 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1813 .context("Target already exists.");
1814 }
1815
1816 let updated = tx
1817 .execute(
1818 "UPDATE persistent.keyentry
1819 SET alias = ?, domain = ?, namespace = ?
1820 WHERE id = ?;",
1821 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1822 )
1823 .context("Failed to update key entry.")?;
1824
1825 if updated != 1 {
1826 return Err(KsError::sys())
1827 .context(format!("Update succeeded, but {} rows were updated.", updated));
1828 }
1829 Ok(()).no_gc()
1830 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001831 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001832 }
1833
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001834 /// Store a new key in a single transaction.
1835 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1836 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001837 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1838 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001839 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001840 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001841 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001842 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001843 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001844 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001845 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001846 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001847 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001848 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001849 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001850 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1851
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001852 let (alias, domain, namespace) = match key {
1853 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1854 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1855 (alias, key.domain, nspace)
1856 }
1857 _ => {
1858 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001859 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001860 }
1861 };
1862 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001863 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001864 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001865 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1866
1867 // In some occasions the key blob is already upgraded during the import.
1868 // In order to make sure it gets properly deleted it is inserted into the
1869 // database here and then immediately replaced by the superseding blob.
1870 // The garbage collector will then subject the blob to deleteKey of the
1871 // KM back end to permanently invalidate the key.
1872 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1873 Self::set_blob_internal(
1874 tx,
1875 key_id.id(),
1876 SubComponentType::KEY_BLOB,
1877 Some(blob),
1878 Some(blob_metadata),
1879 )
1880 .context("Trying to insert superseded key blob.")?;
1881 true
1882 } else {
1883 false
1884 };
1885
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001886 Self::set_blob_internal(
1887 tx,
1888 key_id.id(),
1889 SubComponentType::KEY_BLOB,
1890 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001891 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001892 )
1893 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001894 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001895 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001896 .context("Trying to insert the certificate.")?;
1897 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001898 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001899 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001900 tx,
1901 key_id.id(),
1902 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001903 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001904 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001905 )
1906 .context("Trying to insert the certificate chain.")?;
1907 }
1908 Self::insert_keyparameter_internal(tx, &key_id, params)
1909 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001910 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001911 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001912 .context("Trying to rebind alias.")?
1913 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001914 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001915 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001916 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001917 }
1918
Janis Danisevskis377d1002021-01-27 19:07:48 -08001919 /// Store a new certificate
1920 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1921 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001922 pub fn store_new_certificate(
1923 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001924 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001925 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001926 cert: &[u8],
1927 km_uuid: &Uuid,
1928 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001929 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1930
Janis Danisevskis377d1002021-01-27 19:07:48 -08001931 let (alias, domain, namespace) = match key {
1932 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1933 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1934 (alias, key.domain, nspace)
1935 }
1936 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001937 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1938 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001939 }
1940 };
1941 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001942 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001943 .context("Trying to create new key entry.")?;
1944
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001945 Self::set_blob_internal(
1946 tx,
1947 key_id.id(),
1948 SubComponentType::CERT_CHAIN,
1949 Some(cert),
1950 None,
1951 )
1952 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001953
1954 let mut metadata = KeyMetaData::new();
1955 metadata.add(KeyMetaEntry::CreationDate(
1956 DateTime::now().context("Trying to make creation time.")?,
1957 ));
1958
1959 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1960
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001961 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001962 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001963 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001964 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001965 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001966 }
1967
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001968 // Helper function loading the key_id given the key descriptor
1969 // tuple comprising domain, namespace, and alias.
1970 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001971 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001972 let alias = key
1973 .alias
1974 .as_ref()
1975 .map_or_else(|| Err(KsError::sys()), Ok)
1976 .context("In load_key_entry_id: Alias must be specified.")?;
1977 let mut stmt = tx
1978 .prepare(
1979 "SELECT id FROM persistent.keyentry
1980 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001981 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001982 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001983 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001984 AND alias = ?
1985 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001986 )
1987 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1988 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001989 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001990 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001991 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001992 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001993 .get(0)
1994 .context("Failed to unpack id.")
1995 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001996 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001997 }
1998
1999 /// This helper function completes the access tuple of a key, which is required
2000 /// to perform access control. The strategy depends on the `domain` field in the
2001 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002002 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002003 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002004 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002005 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002006 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002007 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002008 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002009 /// `namespace`.
2010 /// In each case the information returned is sufficient to perform the access
2011 /// check and the key id can be used to load further key artifacts.
2012 fn load_access_tuple(
2013 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002014 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002015 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002016 caller_uid: u32,
2017 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2018 match key.domain {
2019 // Domain App or SELinux. In this case we load the key_id from
2020 // the keyentry database for further loading of key components.
2021 // We already have the full access tuple to perform access control.
2022 // The only distinction is that we use the caller_uid instead
2023 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002024 // Domain::APP.
2025 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002026 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002027 if access_key.domain == Domain::APP {
2028 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002029 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002030 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002031 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002032
2033 Ok((key_id, access_key, None))
2034 }
2035
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002036 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002037 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002038 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002039 let mut stmt = tx
2040 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002041 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002042 WHERE grantee = ? AND id = ? AND
2043 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002044 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002045 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002046 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002047 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002048 .context("Domain:Grant: query failed.")?;
2049 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002050 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002051 let r =
2052 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002053 Ok((
2054 r.get(0).context("Failed to unpack key_id.")?,
2055 r.get(1).context("Failed to unpack access_vector.")?,
2056 ))
2057 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002058 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002059 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002060 }
2061
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002062 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002063 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002064 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002065 let (domain, namespace): (Domain, i64) = {
2066 let mut stmt = tx
2067 .prepare(
2068 "SELECT domain, namespace FROM persistent.keyentry
2069 WHERE
2070 id = ?
2071 AND state = ?;",
2072 )
2073 .context("Domain::KEY_ID: prepare statement failed")?;
2074 let mut rows = stmt
2075 .query(params![key.nspace, KeyLifeCycle::Live])
2076 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002077 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002078 let r =
2079 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002080 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002081 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002082 r.get(1).context("Failed to unpack namespace.")?,
2083 ))
2084 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002085 .context("Domain::KEY_ID.")?
2086 };
2087
2088 // We may use a key by id after loading it by grant.
2089 // In this case we have to check if the caller has a grant for this particular
2090 // key. We can skip this if we already know that the caller is the owner.
2091 // But we cannot know this if domain is anything but App. E.g. in the case
2092 // of Domain::SELINUX we have to speculatively check for grants because we have to
2093 // consult the SEPolicy before we know if the caller is the owner.
2094 let access_vector: Option<KeyPermSet> =
2095 if domain != Domain::APP || namespace != caller_uid as i64 {
2096 let access_vector: Option<i32> = tx
2097 .query_row(
2098 "SELECT access_vector FROM persistent.grant
2099 WHERE grantee = ? AND keyentryid = ?;",
2100 params![caller_uid as i64, key.nspace],
2101 |row| row.get(0),
2102 )
2103 .optional()
2104 .context("Domain::KEY_ID: query grant failed.")?;
2105 access_vector.map(|p| p.into())
2106 } else {
2107 None
2108 };
2109
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002110 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002111 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002112 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002113 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002114
Janis Danisevskis45760022021-01-19 16:34:10 -08002115 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002116 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002117 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002118 }
2119 }
2120
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002121 fn load_blob_components(
2122 key_id: i64,
2123 load_bits: KeyEntryLoadBits,
2124 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002125 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002126 let mut stmt = tx
2127 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002128 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002129 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2130 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002131 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002132
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002133 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002134
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002135 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002136 let mut cert_blob: Option<Vec<u8>> = None;
2137 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002138 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002139 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002140 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002141 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002142 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002143 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2144 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002145 key_blob = Some((
2146 row.get(0).context("Failed to extract key blob id.")?,
2147 row.get(2).context("Failed to extract key blob.")?,
2148 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002149 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002150 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002151 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002152 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002153 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002154 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002155 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002156 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002157 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002158 (SubComponentType::CERT, _, _)
2159 | (SubComponentType::CERT_CHAIN, _, _)
2160 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002161 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2162 }
2163 Ok(())
2164 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002165 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002166
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002167 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2168 Ok(Some((
2169 blob,
2170 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002171 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002172 )))
2173 })?;
2174
2175 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002176 }
2177
2178 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2179 let mut stmt = tx
2180 .prepare(
2181 "SELECT tag, data, security_level from persistent.keyparameter
2182 WHERE keyentryid = ?;",
2183 )
2184 .context("In load_key_parameters: prepare statement failed.")?;
2185
2186 let mut parameters: Vec<KeyParameter> = Vec::new();
2187
2188 let mut rows =
2189 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002190 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002191 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2192 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002193 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002194 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002195 .context("Failed to read KeyParameter.")?,
2196 );
2197 Ok(())
2198 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002199 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002200
2201 Ok(parameters)
2202 }
2203
Qi Wub9433b52020-12-01 14:52:46 +08002204 /// Decrements the usage count of a limited use key. This function first checks whether the
2205 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2206 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2207 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002208 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002209 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2210
Qi Wub9433b52020-12-01 14:52:46 +08002211 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2212 let limit: Option<i32> = tx
2213 .query_row(
2214 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2215 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2216 |row| row.get(0),
2217 )
2218 .optional()
2219 .context("Trying to load usage count")?;
2220
2221 let limit = limit
2222 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2223 .context("The Key no longer exists. Key is exhausted.")?;
2224
2225 tx.execute(
2226 "UPDATE persistent.keyparameter
2227 SET data = data - 1
2228 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2229 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2230 )
2231 .context("Failed to update key usage count.")?;
2232
2233 match limit {
2234 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002235 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002236 .context("Trying to mark limited use key for deletion."),
2237 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002238 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002239 }
2240 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002241 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002242 }
2243
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002244 /// Load a key entry by the given key descriptor.
2245 /// It uses the `check_permission` callback to verify if the access is allowed
2246 /// given the key access tuple read from the database using `load_access_tuple`.
2247 /// With `load_bits` the caller may specify which blobs shall be loaded from
2248 /// the blob database.
2249 pub fn load_key_entry(
2250 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002251 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002252 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002253 load_bits: KeyEntryLoadBits,
2254 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002255 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2256 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002257 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
David Drysdale115c4722024-04-15 14:11:52 +01002258 let start = std::time::Instant::now();
Janis Danisevskis850d4862021-05-05 08:41:14 -07002259
Janis Danisevskis66784c42021-01-27 08:40:25 -08002260 loop {
2261 match self.load_key_entry_internal(
2262 key,
2263 key_type,
2264 load_bits,
2265 caller_uid,
2266 &check_permission,
2267 ) {
2268 Ok(result) => break Ok(result),
2269 Err(e) => {
2270 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01002271 check_lock_timeout(&start, MAX_DB_BUSY_RETRY_PERIOD)?;
2272 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08002273 continue;
2274 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002275 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002276 }
2277 }
2278 }
2279 }
2280 }
2281
2282 fn load_key_entry_internal(
2283 &mut self,
2284 key: &KeyDescriptor,
2285 key_type: KeyType,
2286 load_bits: KeyEntryLoadBits,
2287 caller_uid: u32,
2288 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002289 ) -> Result<(KeyIdGuard, KeyEntry)> {
2290 // KEY ID LOCK 1/2
2291 // If we got a key descriptor with a key id we can get the lock right away.
2292 // Otherwise we have to defer it until we know the key id.
2293 let key_id_guard = match key.domain {
2294 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2295 _ => None,
2296 };
2297
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002298 let tx = self
2299 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002300 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002301 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002302
2303 // Load the key_id and complete the access control tuple.
2304 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002305 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002306
2307 // Perform access control. It is vital that we return here if the permission is denied.
2308 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002309 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002310
Janis Danisevskisaec14592020-11-12 09:41:49 -08002311 // KEY ID LOCK 2/2
2312 // If we did not get a key id lock by now, it was because we got a key descriptor
2313 // without a key id. At this point we got the key id, so we can try and get a lock.
2314 // However, we cannot block here, because we are in the middle of the transaction.
2315 // So first we try to get the lock non blocking. If that fails, we roll back the
2316 // transaction and block until we get the lock. After we successfully got the lock,
2317 // we start a new transaction and load the access tuple again.
2318 //
2319 // We don't need to perform access control again, because we already established
2320 // that the caller had access to the given key. But we need to make sure that the
2321 // key id still exists. So we have to load the key entry by key id this time.
2322 let (key_id_guard, tx) = match key_id_guard {
2323 None => match KEY_ID_LOCK.try_get(key_id) {
2324 None => {
2325 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002326 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002327
Janis Danisevskisaec14592020-11-12 09:41:49 -08002328 // Block until we have a key id lock.
2329 let key_id_guard = KEY_ID_LOCK.get(key_id);
2330
2331 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002332 let tx = self
2333 .conn
2334 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002335 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002336
2337 Self::load_access_tuple(
2338 &tx,
2339 // This time we have to load the key by the retrieved key id, because the
2340 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002341 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002342 domain: Domain::KEY_ID,
2343 nspace: key_id,
2344 ..Default::default()
2345 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002346 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002347 caller_uid,
2348 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002349 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002350 (key_id_guard, tx)
2351 }
2352 Some(l) => (l, tx),
2353 },
2354 Some(key_id_guard) => (key_id_guard, tx),
2355 };
2356
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002357 let key_entry =
2358 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002360 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002361
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002362 Ok((key_id_guard, key_entry))
2363 }
2364
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002365 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002366 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002367 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2368 .context("Trying to delete keyentry.")?;
2369 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2370 .context("Trying to delete keymetadata.")?;
2371 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2372 .context("Trying to delete keyparameters.")?;
2373 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2374 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002375 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002376 }
2377
2378 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002379 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002380 pub fn unbind_key(
2381 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002382 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002383 key_type: KeyType,
2384 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002385 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002386 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002387 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2388
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002389 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2390 let (key_id, access_key_descriptor, access_vector) =
2391 Self::load_access_tuple(tx, key, key_type, caller_uid)
2392 .context("Trying to get access tuple.")?;
2393
2394 // Perform access control. It is vital that we return here if the permission is denied.
2395 // So do not touch that '?' at the end.
2396 check_permission(&access_key_descriptor, access_vector)
2397 .context("While checking permission.")?;
2398
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002399 Self::mark_unreferenced(tx, key_id)
2400 .map(|need_gc| (need_gc, ()))
2401 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002402 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002403 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002404 }
2405
Max Bires8e93d2b2021-01-14 13:17:59 -08002406 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2407 tx.query_row(
2408 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2409 params![key_id],
2410 |row| row.get(0),
2411 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002412 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002413 }
2414
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002415 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2416 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2417 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002418 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2419
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002420 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002421 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002422 }
2423 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2424 tx.execute(
2425 "DELETE FROM persistent.keymetadata
2426 WHERE keyentryid IN (
2427 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002428 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002429 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002430 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002431 )
2432 .context("Trying to delete keymetadata.")?;
2433 tx.execute(
2434 "DELETE FROM persistent.keyparameter
2435 WHERE keyentryid IN (
2436 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002437 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002438 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002439 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002440 )
2441 .context("Trying to delete keyparameters.")?;
2442 tx.execute(
2443 "DELETE FROM persistent.grant
2444 WHERE keyentryid IN (
2445 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002446 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002447 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002448 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002449 )
2450 .context("Trying to delete grants.")?;
2451 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002452 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002453 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2454 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002455 )
2456 .context("Trying to delete keyentry.")?;
2457 Ok(()).need_gc()
2458 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002459 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002460 }
2461
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002462 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2463 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2464 {
2465 tx.execute(
2466 "DELETE FROM persistent.keymetadata
2467 WHERE keyentryid IN (
2468 SELECT id FROM persistent.keyentry
2469 WHERE state = ?
2470 );",
2471 params![KeyLifeCycle::Unreferenced],
2472 )
2473 .context("Trying to delete keymetadata.")?;
2474 tx.execute(
2475 "DELETE FROM persistent.keyparameter
2476 WHERE keyentryid IN (
2477 SELECT id FROM persistent.keyentry
2478 WHERE state = ?
2479 );",
2480 params![KeyLifeCycle::Unreferenced],
2481 )
2482 .context("Trying to delete keyparameters.")?;
2483 tx.execute(
2484 "DELETE FROM persistent.grant
2485 WHERE keyentryid IN (
2486 SELECT id FROM persistent.keyentry
2487 WHERE state = ?
2488 );",
2489 params![KeyLifeCycle::Unreferenced],
2490 )
2491 .context("Trying to delete grants.")?;
2492 tx.execute(
2493 "DELETE FROM persistent.keyentry
2494 WHERE state = ?;",
2495 params![KeyLifeCycle::Unreferenced],
2496 )
2497 .context("Trying to delete keyentry.")?;
2498 Result::<()>::Ok(())
2499 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002500 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002501 }
2502
Hasini Gunasingheda895552021-01-27 19:34:37 +00002503 /// Delete the keys created on behalf of the user, denoted by the user id.
2504 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2505 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2506 /// The caller of this function should notify the gc if the returned value is true.
2507 pub fn unbind_keys_for_user(
2508 &mut self,
2509 user_id: u32,
2510 keep_non_super_encrypted_keys: bool,
2511 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002512 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2513
Hasini Gunasingheda895552021-01-27 19:34:37 +00002514 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2515 let mut stmt = tx
2516 .prepare(&format!(
2517 "SELECT id from persistent.keyentry
2518 WHERE (
2519 key_type = ?
2520 AND domain = ?
2521 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2522 AND state = ?
2523 ) OR (
2524 key_type = ?
2525 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002526 AND state = ?
2527 );",
2528 aid_user_offset = AID_USER_OFFSET
2529 ))
2530 .context(concat!(
2531 "In unbind_keys_for_user. ",
2532 "Failed to prepare the query to find the keys created by apps."
2533 ))?;
2534
2535 let mut rows = stmt
2536 .query(params![
2537 // WHERE client key:
2538 KeyType::Client,
2539 Domain::APP.0 as u32,
2540 user_id,
2541 KeyLifeCycle::Live,
2542 // OR super key:
2543 KeyType::Super,
2544 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002545 KeyLifeCycle::Live
2546 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002547 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002548
2549 let mut key_ids: Vec<i64> = Vec::new();
2550 db_utils::with_rows_extract_all(&mut rows, |row| {
2551 key_ids
2552 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2553 Ok(())
2554 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002555 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002556
2557 let mut notify_gc = false;
2558 for key_id in key_ids {
2559 if keep_non_super_encrypted_keys {
2560 // Load metadata and filter out non-super-encrypted keys.
2561 if let (_, Some((_, blob_metadata)), _, _) =
2562 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002563 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002564 {
2565 if blob_metadata.encrypted_by().is_none() {
2566 continue;
2567 }
2568 }
2569 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002570 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002571 .context("In unbind_keys_for_user.")?
2572 || notify_gc;
2573 }
2574 Ok(()).do_gc(notify_gc)
2575 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002576 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002577 }
2578
Eric Biggersb0478cf2023-10-27 03:55:29 +00002579 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2580 /// This runs when the user's lock screen is being changed to Swipe or None.
2581 ///
2582 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2583 /// such keys also require user authentication. Keystore's concept of user authentication is
2584 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2585 /// authentication is no longer possible. In contrast, keys that just require that the device
2586 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2587 /// is always considered "unlocked" in that case.
2588 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2589 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2590
2591 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2592 let mut stmt = tx
2593 .prepare(&format!(
2594 "SELECT id from persistent.keyentry
2595 WHERE key_type = ?
2596 AND domain = ?
2597 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2598 AND state = ?;",
2599 aid_user_offset = AID_USER_OFFSET
2600 ))
2601 .context(concat!(
2602 "In unbind_auth_bound_keys_for_user. ",
2603 "Failed to prepare the query to find the keys created by apps."
2604 ))?;
2605
2606 let mut rows = stmt
2607 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2608 .context(ks_err!("Failed to query the keys created by apps."))?;
2609
2610 let mut key_ids: Vec<i64> = Vec::new();
2611 db_utils::with_rows_extract_all(&mut rows, |row| {
2612 key_ids
2613 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2614 Ok(())
2615 })
2616 .context(ks_err!())?;
2617
2618 let mut notify_gc = false;
2619 let mut num_unbound = 0;
2620 for key_id in key_ids {
2621 // Load the key parameters and filter out non-auth-bound keys. To identify
2622 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2623 // could also be used, but UserSecureID is what Keystore treats as authoritative
2624 // when actually enforcing the key parameters (it might not matter, though).
2625 let params = Self::load_key_parameters(key_id, tx)
2626 .context("Failed to load key parameters.")?;
2627 let is_auth_bound_key = params.iter().any(|kp| {
2628 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2629 });
2630 if is_auth_bound_key {
2631 notify_gc = Self::mark_unreferenced(tx, key_id)
2632 .context("In unbind_auth_bound_keys_for_user.")?
2633 || notify_gc;
2634 num_unbound += 1;
2635 }
2636 }
2637 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2638 Ok(()).do_gc(notify_gc)
2639 })
2640 .context(ks_err!())
2641 }
2642
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002643 fn load_key_components(
2644 tx: &Transaction,
2645 load_bits: KeyEntryLoadBits,
2646 key_id: i64,
2647 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002648 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002649
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002650 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002651 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002652
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002653 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002654 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002655
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002656 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002657 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002658
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002659 Ok(KeyEntry {
2660 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002661 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002662 cert: cert_blob,
2663 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002664 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002665 parameters,
2666 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002667 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002668 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002669 }
2670
Eran Messeri24f31972023-01-25 17:00:33 +00002671 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2672 /// aliases are greater than the specified 'start_past_alias'. If no value
2673 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002674 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002675 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002676 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002677 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002678 &mut self,
2679 domain: Domain,
2680 namespace: i64,
2681 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002682 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002683 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002684 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002685
Eran Messeri24f31972023-01-25 17:00:33 +00002686 let query = format!(
2687 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002688 WHERE domain = ?
2689 AND namespace = ?
2690 AND alias IS NOT NULL
2691 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002692 AND key_type = ?
2693 {}
2694 ORDER BY alias ASC;",
2695 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2696 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002697
Eran Messeri24f31972023-01-25 17:00:33 +00002698 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2699 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2700
2701 let mut rows = match start_past_alias {
2702 Some(past_alias) => stmt
2703 .query(params![
2704 domain.0 as u32,
2705 namespace,
2706 KeyLifeCycle::Live,
2707 key_type,
2708 past_alias
2709 ])
2710 .context(ks_err!("Failed to query."))?,
2711 None => stmt
2712 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2713 .context(ks_err!("Failed to query."))?,
2714 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002715
Janis Danisevskis66784c42021-01-27 08:40:25 -08002716 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2717 db_utils::with_rows_extract_all(&mut rows, |row| {
2718 descriptors.push(KeyDescriptor {
2719 domain,
2720 nspace: namespace,
2721 alias: Some(row.get(0).context("Trying to extract alias.")?),
2722 blob: None,
2723 });
2724 Ok(())
2725 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002726 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002727 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002728 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002729 }
2730
Eran Messeri24f31972023-01-25 17:00:33 +00002731 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2732 /// Domain must be APP or SELINUX, the caller must make sure of that.
2733 pub fn count_keys(
2734 &mut self,
2735 domain: Domain,
2736 namespace: i64,
2737 key_type: KeyType,
2738 ) -> Result<usize> {
2739 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2740
2741 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2742 tx.query_row(
2743 "SELECT COUNT(alias) FROM persistent.keyentry
2744 WHERE domain = ?
2745 AND namespace = ?
2746 AND alias IS NOT NULL
2747 AND state = ?
2748 AND key_type = ?;",
2749 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2750 |row| row.get(0),
2751 )
2752 .context(ks_err!("Failed to count number of keys."))
2753 .no_gc()
2754 })?;
2755 Ok(num_keys)
2756 }
2757
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002758 /// Adds a grant to the grant table.
2759 /// Like `load_key_entry` this function loads the access tuple before
2760 /// it uses the callback for a permission check. Upon success,
2761 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2762 /// grant table. The new row will have a randomized id, which is used as
2763 /// grant id in the namespace field of the resulting KeyDescriptor.
2764 pub fn grant(
2765 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002766 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002767 caller_uid: u32,
2768 grantee_uid: u32,
2769 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002770 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002771 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002772 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2773
Janis Danisevskis66784c42021-01-27 08:40:25 -08002774 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2775 // Load the key_id and complete the access control tuple.
2776 // We ignore the access vector here because grants cannot be granted.
2777 // The access vector returned here expresses the permissions the
2778 // grantee has if key.domain == Domain::GRANT. But this vector
2779 // cannot include the grant permission by design, so there is no way the
2780 // subsequent permission check can pass.
2781 // We could check key.domain == Domain::GRANT and fail early.
2782 // But even if we load the access tuple by grant here, the permission
2783 // check denies the attempt to create a grant by grant descriptor.
2784 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002785 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002786
Janis Danisevskis66784c42021-01-27 08:40:25 -08002787 // Perform access control. It is vital that we return here if the permission
2788 // was denied. So do not touch that '?' at the end of the line.
2789 // This permission check checks if the caller has the grant permission
2790 // for the given key and in addition to all of the permissions
2791 // expressed in `access_vector`.
2792 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002793 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002794
Janis Danisevskis66784c42021-01-27 08:40:25 -08002795 let grant_id = if let Some(grant_id) = tx
2796 .query_row(
2797 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002798 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002799 params![key_id, grantee_uid],
2800 |row| row.get(0),
2801 )
2802 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002803 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002804 {
2805 tx.execute(
2806 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002807 SET access_vector = ?
2808 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002809 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002810 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002811 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002812 grant_id
2813 } else {
2814 Self::insert_with_retry(|id| {
2815 tx.execute(
2816 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2817 VALUES (?, ?, ?, ?);",
2818 params![id, grantee_uid, key_id, i32::from(access_vector)],
2819 )
2820 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002821 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002822 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002823
Janis Danisevskis66784c42021-01-27 08:40:25 -08002824 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002825 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002826 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002827 }
2828
2829 /// This function checks permissions like `grant` and `load_key_entry`
2830 /// before removing a grant from the grant table.
2831 pub fn ungrant(
2832 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002833 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002834 caller_uid: u32,
2835 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002836 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002837 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002838 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2839
Janis Danisevskis66784c42021-01-27 08:40:25 -08002840 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2841 // Load the key_id and complete the access control tuple.
2842 // We ignore the access vector here because grants cannot be granted.
2843 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002844 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002845
Janis Danisevskis66784c42021-01-27 08:40:25 -08002846 // Perform access control. We must return here if the permission
2847 // was denied. So do not touch the '?' at the end of this line.
2848 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002849 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002850
Janis Danisevskis66784c42021-01-27 08:40:25 -08002851 tx.execute(
2852 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002853 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002854 params![key_id, grantee_uid],
2855 )
2856 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002857
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002858 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002859 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002860 }
2861
Joel Galenson845f74b2020-09-09 14:11:55 -07002862 // Generates a random id and passes it to the given function, which will
2863 // try to insert it into a database. If that insertion fails, retry;
2864 // otherwise return the id.
2865 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2866 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002867 let newid: i64 = match random() {
2868 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2869 i => i,
2870 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002871 match inserter(newid) {
2872 // If the id already existed, try again.
2873 Err(rusqlite::Error::SqliteFailure(
2874 libsqlite3_sys::Error {
2875 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2876 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2877 },
2878 _,
2879 )) => (),
2880 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002881 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002882 }
2883 _ => return Ok(newid),
2884 }
2885 }
2886 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002887
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002888 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2889 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002890 self.perboot
2891 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002892 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002893
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002894 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002895 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002896 where
2897 F: Fn(&AuthTokenEntry) -> bool,
2898 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002899 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002900 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002901
2902 /// Load descriptor of a key by key id
2903 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2904 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2905
2906 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2907 tx.query_row(
2908 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2909 params![key_id],
2910 |row| {
2911 Ok(KeyDescriptor {
2912 domain: Domain(row.get(0)?),
2913 nspace: row.get(1)?,
2914 alias: row.get(2)?,
2915 blob: None,
2916 })
2917 },
2918 )
2919 .optional()
2920 .context("Trying to load key descriptor")
2921 .no_gc()
2922 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002923 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002924 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002925
2926 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2927 /// (for the given user_id).
2928 /// This is helpful for finding out which apps will have their keys invalidated when
2929 /// the user changes biometrics enrollment or removes their LSKF.
2930 pub fn get_app_uids_affected_by_sid(
2931 &mut self,
2932 user_id: i32,
2933 secure_user_id: i64,
2934 ) -> Result<Vec<i64>> {
2935 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2936
2937 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2938 let mut stmt = tx
2939 .prepare(&format!(
2940 "SELECT id, namespace from persistent.keyentry
2941 WHERE key_type = ?
2942 AND domain = ?
2943 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2944 AND state = ?;",
2945 ))
2946 .context(concat!(
2947 "In get_app_uids_affected_by_sid, ",
2948 "failed to prepare the query to find the keys created by apps."
2949 ))?;
2950
2951 let mut rows = stmt
2952 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2953 .context(ks_err!("Failed to query the keys created by apps."))?;
2954
2955 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2956 db_utils::with_rows_extract_all(&mut rows, |row| {
2957 key_ids_and_app_uids.insert(
2958 row.get(0).context("Failed to read key id of a key created by an app.")?,
2959 row.get(1).context("Failed to read the app uid")?,
2960 );
2961 Ok(())
2962 })?;
2963 Ok(key_ids_and_app_uids).no_gc()
2964 })?;
2965 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2966 for (key_id, app_uid) in key_ids_and_app_uids {
2967 // Read the key parameters for each key in its own transaction. It is OK to ignore
2968 // an error to get the properties of a particular key since it might have been deleted
2969 // under our feet after the previous transaction concluded. If the key was deleted
2970 // then it is no longer applicable if it was auth-bound or not.
2971 if let Ok(is_key_bound_to_sid) =
2972 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2973 let params = Self::load_key_parameters(key_id, tx)
2974 .context("Failed to load key parameters.")?;
2975 // Check if the key is bound to this secure user ID.
2976 let is_key_bound_to_sid = params.iter().any(|kp| {
2977 matches!(
2978 kp.key_parameter_value(),
2979 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2980 )
2981 });
2982 Ok(is_key_bound_to_sid).no_gc()
2983 })
2984 {
2985 if is_key_bound_to_sid {
2986 app_uids_affected_by_sid.insert(app_uid);
2987 }
2988 }
2989 }
2990
2991 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2992 Ok(app_uids_vec)
2993 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002994}
2995
2996#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002997pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002998
2999 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003000 use crate::key_parameter::{
3001 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3002 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3003 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003004 use crate::key_perm_set;
3005 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00003006 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003007 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003008 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3009 HardwareAuthToken::HardwareAuthToken,
3010 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003011 };
3012 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003013 Timestamp::Timestamp,
3014 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003015 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003016 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003017 use std::collections::BTreeMap;
3018 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003019 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04003020 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003021 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003022 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003023 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003024 #[cfg(disabled)]
3025 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003026
Seth Moore7ee79f92021-12-07 11:42:49 -08003027 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003028 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003029
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003030 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003031 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003032 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003033 })?;
3034 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003035 }
3036
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003037 fn rebind_alias(
3038 db: &mut KeystoreDB,
3039 newid: &KeyIdGuard,
3040 alias: &str,
3041 domain: Domain,
3042 namespace: i64,
3043 ) -> Result<bool> {
3044 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003045 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003046 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003047 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003048 }
3049
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003050 #[test]
3051 fn datetime() -> Result<()> {
3052 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003053 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003054 let now = SystemTime::now();
3055 let duration = Duration::from_secs(1000);
3056 let then = now.checked_sub(duration).unwrap();
3057 let soon = now.checked_add(duration).unwrap();
3058 conn.execute(
3059 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3060 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3061 )?;
3062 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003063 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003064 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3065 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3066 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3067 assert!(rows.next()?.is_none());
3068 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3069 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3070 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3071 Ok(())
3072 }
3073
Joel Galenson0891bc12020-07-20 10:37:03 -07003074 // Ensure that we're using the "injected" random function, not the real one.
3075 #[test]
3076 fn test_mocked_random() {
3077 let rand1 = random();
3078 let rand2 = random();
3079 let rand3 = random();
3080 if rand1 == rand2 {
3081 assert_eq!(rand2 + 1, rand3);
3082 } else {
3083 assert_eq!(rand1 + 1, rand2);
3084 assert_eq!(rand2, rand3);
3085 }
3086 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003087
Joel Galenson26f4d012020-07-17 14:57:21 -07003088 // Test that we have the correct tables.
3089 #[test]
3090 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003091 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003092 let tables = db
3093 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003094 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003095 .query_map(params![], |row| row.get(0))?
3096 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003097 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003098 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003099 assert_eq!(tables[1], "blobmetadata");
3100 assert_eq!(tables[2], "grant");
3101 assert_eq!(tables[3], "keyentry");
3102 assert_eq!(tables[4], "keymetadata");
3103 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003104 Ok(())
3105 }
3106
3107 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003108 fn test_auth_token_table_invariant() -> Result<()> {
3109 let mut db = new_test_db()?;
3110 let auth_token1 = HardwareAuthToken {
3111 challenge: i64::MAX,
3112 userId: 200,
3113 authenticatorId: 200,
3114 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3115 timestamp: Timestamp { milliSeconds: 500 },
3116 mac: String::from("mac").into_bytes(),
3117 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003118 db.insert_auth_token(&auth_token1);
3119 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003120 assert_eq!(auth_tokens_returned.len(), 1);
3121
3122 // insert another auth token with the same values for the columns in the UNIQUE constraint
3123 // of the auth token table and different value for timestamp
3124 let auth_token2 = HardwareAuthToken {
3125 challenge: i64::MAX,
3126 userId: 200,
3127 authenticatorId: 200,
3128 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3129 timestamp: Timestamp { milliSeconds: 600 },
3130 mac: String::from("mac").into_bytes(),
3131 };
3132
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003133 db.insert_auth_token(&auth_token2);
3134 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003135 assert_eq!(auth_tokens_returned.len(), 1);
3136
3137 if let Some(auth_token) = auth_tokens_returned.pop() {
3138 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3139 }
3140
3141 // insert another auth token with the different values for the columns in the UNIQUE
3142 // constraint of the auth token table
3143 let auth_token3 = HardwareAuthToken {
3144 challenge: i64::MAX,
3145 userId: 201,
3146 authenticatorId: 200,
3147 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3148 timestamp: Timestamp { milliSeconds: 600 },
3149 mac: String::from("mac").into_bytes(),
3150 };
3151
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003152 db.insert_auth_token(&auth_token3);
3153 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003154 assert_eq!(auth_tokens_returned.len(), 2);
3155
3156 Ok(())
3157 }
3158
3159 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003160 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3161 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003162 }
3163
3164 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003165 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003166 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003167 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003168
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003169 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003170 let entries = get_keyentry(&db)?;
3171 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003172
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003173 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003174
3175 let entries_new = get_keyentry(&db)?;
3176 assert_eq!(entries, entries_new);
3177 Ok(())
3178 }
3179
3180 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003181 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003182 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3183 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003184 }
3185
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003186 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003187
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003188 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3189 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003190
3191 let entries = get_keyentry(&db)?;
3192 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003193 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3194 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003195
3196 // Test that we must pass in a valid Domain.
3197 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003198 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003199 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003200 );
3201 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003202 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003203 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003204 );
3205 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003206 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003207 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003208 );
3209
3210 Ok(())
3211 }
3212
Joel Galenson33c04ad2020-08-03 11:04:38 -07003213 #[test]
3214 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003215 fn extractor(
3216 ke: &KeyEntryRow,
3217 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3218 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003219 }
3220
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003221 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003222 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3223 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003224 let entries = get_keyentry(&db)?;
3225 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003226 assert_eq!(
3227 extractor(&entries[0]),
3228 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3229 );
3230 assert_eq!(
3231 extractor(&entries[1]),
3232 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3233 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003234
3235 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003236 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003237 let entries = get_keyentry(&db)?;
3238 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003239 assert_eq!(
3240 extractor(&entries[0]),
3241 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3242 );
3243 assert_eq!(
3244 extractor(&entries[1]),
3245 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3246 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003247
3248 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003249 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003250 let entries = get_keyentry(&db)?;
3251 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003252 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3253 assert_eq!(
3254 extractor(&entries[1]),
3255 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3256 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003257
3258 // Test that we must pass in a valid Domain.
3259 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003260 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003261 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003262 );
3263 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003264 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003265 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003266 );
3267 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003268 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003269 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003270 );
3271
3272 // Test that we correctly handle setting an alias for something that does not exist.
3273 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003274 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003275 "Expected to update a single entry but instead updated 0",
3276 );
3277 // Test that we correctly abort the transaction in this case.
3278 let entries = get_keyentry(&db)?;
3279 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003280 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3281 assert_eq!(
3282 extractor(&entries[1]),
3283 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3284 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003285
3286 Ok(())
3287 }
3288
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003289 #[test]
3290 fn test_grant_ungrant() -> Result<()> {
3291 const CALLER_UID: u32 = 15;
3292 const GRANTEE_UID: u32 = 12;
3293 const SELINUX_NAMESPACE: i64 = 7;
3294
3295 let mut db = new_test_db()?;
3296 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003297 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3298 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3299 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003300 )?;
3301 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003302 domain: super::Domain::APP,
3303 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003304 alias: Some("key".to_string()),
3305 blob: None,
3306 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003307 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3308 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003309
3310 // Reset totally predictable random number generator in case we
3311 // are not the first test running on this thread.
3312 reset_random();
3313 let next_random = 0i64;
3314
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003315 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003316 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003317 assert_eq!(*a, PVEC1);
3318 assert_eq!(
3319 *k,
3320 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003321 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003322 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003323 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003324 alias: Some("key".to_string()),
3325 blob: None,
3326 }
3327 );
3328 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003329 })
3330 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003331
3332 assert_eq!(
3333 app_granted_key,
3334 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003335 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003336 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003337 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003338 alias: None,
3339 blob: None,
3340 }
3341 );
3342
3343 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003344 domain: super::Domain::SELINUX,
3345 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003346 alias: Some("yek".to_string()),
3347 blob: None,
3348 };
3349
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003350 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003351 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003352 assert_eq!(*a, PVEC1);
3353 assert_eq!(
3354 *k,
3355 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003356 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003357 // namespace must be the supplied SELinux
3358 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003359 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003360 alias: Some("yek".to_string()),
3361 blob: None,
3362 }
3363 );
3364 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003365 })
3366 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003367
3368 assert_eq!(
3369 selinux_granted_key,
3370 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003371 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003372 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003373 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003374 alias: None,
3375 blob: None,
3376 }
3377 );
3378
3379 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003380 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003381 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003382 assert_eq!(*a, PVEC2);
3383 assert_eq!(
3384 *k,
3385 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003386 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003387 // namespace must be the supplied SELinux
3388 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003389 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003390 alias: Some("yek".to_string()),
3391 blob: None,
3392 }
3393 );
3394 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003395 })
3396 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003397
3398 assert_eq!(
3399 selinux_granted_key,
3400 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003401 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003402 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003403 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003404 alias: None,
3405 blob: None,
3406 }
3407 );
3408
3409 {
3410 // Limiting scope of stmt, because it borrows db.
3411 let mut stmt = db
3412 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003413 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003414 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3415 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3416 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003417
3418 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003419 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003420 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003421 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003422 assert!(rows.next().is_none());
3423 }
3424
3425 debug_dump_keyentry_table(&mut db)?;
3426 println!("app_key {:?}", app_key);
3427 println!("selinux_key {:?}", selinux_key);
3428
Janis Danisevskis66784c42021-01-27 08:40:25 -08003429 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3430 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003431
3432 Ok(())
3433 }
3434
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003435 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003436 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3437 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3438
3439 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003440 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003441 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003442 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003443 let mut blob_metadata = BlobMetaData::new();
3444 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3445 db.set_blob(
3446 &key_id,
3447 SubComponentType::KEY_BLOB,
3448 Some(TEST_KEY_BLOB),
3449 Some(&blob_metadata),
3450 )?;
3451 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3452 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003453 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003454
3455 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003456 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003457 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003458 )?;
3459 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003460 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003461 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003462 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003463 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003464 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003465 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003466 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003467 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003468 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003469
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003470 drop(rows);
3471 drop(stmt);
3472
3473 assert_eq!(
3474 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3475 BlobMetaData::load_from_db(id, tx).no_gc()
3476 })
3477 .expect("Should find blob metadata."),
3478 blob_metadata
3479 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003480 Ok(())
3481 }
3482
3483 static TEST_ALIAS: &str = "my super duper key";
3484
3485 #[test]
3486 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3487 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003488 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003489 .context("test_insert_and_load_full_keyentry_domain_app")?
3490 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003491 let (_key_guard, key_entry) = db
3492 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003493 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003494 domain: Domain::APP,
3495 nspace: 0,
3496 alias: Some(TEST_ALIAS.to_string()),
3497 blob: None,
3498 },
3499 KeyType::Client,
3500 KeyEntryLoadBits::BOTH,
3501 1,
3502 |_k, _av| Ok(()),
3503 )
3504 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003505 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003506
3507 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003508 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003509 domain: Domain::APP,
3510 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003511 alias: Some(TEST_ALIAS.to_string()),
3512 blob: None,
3513 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003514 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003515 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003516 |_, _| Ok(()),
3517 )
3518 .unwrap();
3519
3520 assert_eq!(
3521 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3522 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003523 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003524 domain: Domain::APP,
3525 nspace: 0,
3526 alias: Some(TEST_ALIAS.to_string()),
3527 blob: None,
3528 },
3529 KeyType::Client,
3530 KeyEntryLoadBits::NONE,
3531 1,
3532 |_k, _av| Ok(()),
3533 )
3534 .unwrap_err()
3535 .root_cause()
3536 .downcast_ref::<KsError>()
3537 );
3538
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003539 Ok(())
3540 }
3541
3542 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003543 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3544 let mut db = new_test_db()?;
3545
3546 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003547 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003548 domain: Domain::APP,
3549 nspace: 1,
3550 alias: Some(TEST_ALIAS.to_string()),
3551 blob: None,
3552 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003553 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003554 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003555 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003556 )
3557 .expect("Trying to insert cert.");
3558
3559 let (_key_guard, mut key_entry) = db
3560 .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::PUBLIC,
3569 1,
3570 |_k, _av| Ok(()),
3571 )
3572 .expect("Trying to read certificate entry.");
3573
3574 assert!(key_entry.pure_cert());
3575 assert!(key_entry.cert().is_none());
3576 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3577
3578 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003579 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003580 domain: Domain::APP,
3581 nspace: 1,
3582 alias: Some(TEST_ALIAS.to_string()),
3583 blob: None,
3584 },
3585 KeyType::Client,
3586 1,
3587 |_, _| Ok(()),
3588 )
3589 .unwrap();
3590
3591 assert_eq!(
3592 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3593 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003594 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003595 domain: Domain::APP,
3596 nspace: 1,
3597 alias: Some(TEST_ALIAS.to_string()),
3598 blob: None,
3599 },
3600 KeyType::Client,
3601 KeyEntryLoadBits::NONE,
3602 1,
3603 |_k, _av| Ok(()),
3604 )
3605 .unwrap_err()
3606 .root_cause()
3607 .downcast_ref::<KsError>()
3608 );
3609
3610 Ok(())
3611 }
3612
3613 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003614 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3615 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003616 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003617 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3618 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003619 let (_key_guard, key_entry) = db
3620 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003621 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003622 domain: Domain::SELINUX,
3623 nspace: 1,
3624 alias: Some(TEST_ALIAS.to_string()),
3625 blob: None,
3626 },
3627 KeyType::Client,
3628 KeyEntryLoadBits::BOTH,
3629 1,
3630 |_k, _av| Ok(()),
3631 )
3632 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003633 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003634
3635 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003636 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003637 domain: Domain::SELINUX,
3638 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003639 alias: Some(TEST_ALIAS.to_string()),
3640 blob: None,
3641 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003642 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003643 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003644 |_, _| Ok(()),
3645 )
3646 .unwrap();
3647
3648 assert_eq!(
3649 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3650 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003651 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003652 domain: Domain::SELINUX,
3653 nspace: 1,
3654 alias: Some(TEST_ALIAS.to_string()),
3655 blob: None,
3656 },
3657 KeyType::Client,
3658 KeyEntryLoadBits::NONE,
3659 1,
3660 |_k, _av| Ok(()),
3661 )
3662 .unwrap_err()
3663 .root_cause()
3664 .downcast_ref::<KsError>()
3665 );
3666
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003667 Ok(())
3668 }
3669
3670 #[test]
3671 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3672 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003673 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003674 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3675 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003676 let (_, key_entry) = db
3677 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003678 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003679 KeyType::Client,
3680 KeyEntryLoadBits::BOTH,
3681 1,
3682 |_k, _av| Ok(()),
3683 )
3684 .unwrap();
3685
Qi Wub9433b52020-12-01 14:52:46 +08003686 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003687
3688 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003689 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003690 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003691 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003692 |_, _| Ok(()),
3693 )
3694 .unwrap();
3695
3696 assert_eq!(
3697 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3698 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003699 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003700 KeyType::Client,
3701 KeyEntryLoadBits::NONE,
3702 1,
3703 |_k, _av| Ok(()),
3704 )
3705 .unwrap_err()
3706 .root_cause()
3707 .downcast_ref::<KsError>()
3708 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003709
3710 Ok(())
3711 }
3712
3713 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003714 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3715 let mut db = new_test_db()?;
3716 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3717 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3718 .0;
3719 // Update the usage count of the limited use key.
3720 db.check_and_update_key_usage_count(key_id)?;
3721
3722 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003723 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003724 KeyType::Client,
3725 KeyEntryLoadBits::BOTH,
3726 1,
3727 |_k, _av| Ok(()),
3728 )?;
3729
3730 // The usage count is decremented now.
3731 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3732
3733 Ok(())
3734 }
3735
3736 #[test]
3737 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3738 let mut db = new_test_db()?;
3739 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3740 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3741 .0;
3742 // Update the usage count of the limited use key.
3743 db.check_and_update_key_usage_count(key_id).expect(concat!(
3744 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3745 "This should succeed."
3746 ));
3747
3748 // Try to update the exhausted limited use key.
3749 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3750 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3751 "This should fail."
3752 ));
3753 assert_eq!(
3754 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3755 e.root_cause().downcast_ref::<KsError>().unwrap()
3756 );
3757
3758 Ok(())
3759 }
3760
3761 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003762 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3763 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003764 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003765 .context("test_insert_and_load_full_keyentry_from_grant")?
3766 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003767
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003768 let granted_key = db
3769 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003770 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003771 domain: Domain::APP,
3772 nspace: 0,
3773 alias: Some(TEST_ALIAS.to_string()),
3774 blob: None,
3775 },
3776 1,
3777 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003778 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003779 |_k, _av| Ok(()),
3780 )
3781 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003782
3783 debug_dump_grant_table(&mut db)?;
3784
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003785 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003786 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3787 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003788 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003789 Ok(())
3790 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003791 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003792
Qi Wub9433b52020-12-01 14:52:46 +08003793 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003794
Janis Danisevskis66784c42021-01-27 08:40:25 -08003795 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003796
3797 assert_eq!(
3798 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3799 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003800 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003801 KeyType::Client,
3802 KeyEntryLoadBits::NONE,
3803 2,
3804 |_k, _av| Ok(()),
3805 )
3806 .unwrap_err()
3807 .root_cause()
3808 .downcast_ref::<KsError>()
3809 );
3810
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003811 Ok(())
3812 }
3813
Janis Danisevskis45760022021-01-19 16:34:10 -08003814 // This test attempts to load a key by key id while the caller is not the owner
3815 // but a grant exists for the given key and the caller.
3816 #[test]
3817 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3818 let mut db = new_test_db()?;
3819 const OWNER_UID: u32 = 1u32;
3820 const GRANTEE_UID: u32 = 2u32;
3821 const SOMEONE_ELSE_UID: u32 = 3u32;
3822 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3823 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3824 .0;
3825
3826 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003827 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003828 domain: Domain::APP,
3829 nspace: 0,
3830 alias: Some(TEST_ALIAS.to_string()),
3831 blob: None,
3832 },
3833 OWNER_UID,
3834 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003835 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003836 |_k, _av| Ok(()),
3837 )
3838 .unwrap();
3839
3840 debug_dump_grant_table(&mut db)?;
3841
3842 let id_descriptor =
3843 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3844
3845 let (_, key_entry) = db
3846 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003847 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003848 KeyType::Client,
3849 KeyEntryLoadBits::BOTH,
3850 GRANTEE_UID,
3851 |k, av| {
3852 assert_eq!(Domain::APP, k.domain);
3853 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003854 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003855 Ok(())
3856 },
3857 )
3858 .unwrap();
3859
3860 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3861
3862 let (_, key_entry) = db
3863 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003864 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003865 KeyType::Client,
3866 KeyEntryLoadBits::BOTH,
3867 SOMEONE_ELSE_UID,
3868 |k, av| {
3869 assert_eq!(Domain::APP, k.domain);
3870 assert_eq!(OWNER_UID as i64, k.nspace);
3871 assert!(av.is_none());
3872 Ok(())
3873 },
3874 )
3875 .unwrap();
3876
3877 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3878
Janis Danisevskis66784c42021-01-27 08:40:25 -08003879 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003880
3881 assert_eq!(
3882 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3883 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003884 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003885 KeyType::Client,
3886 KeyEntryLoadBits::NONE,
3887 GRANTEE_UID,
3888 |_k, _av| Ok(()),
3889 )
3890 .unwrap_err()
3891 .root_cause()
3892 .downcast_ref::<KsError>()
3893 );
3894
3895 Ok(())
3896 }
3897
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003898 // Creates a key migrates it to a different location and then tries to access it by the old
3899 // and new location.
3900 #[test]
3901 fn test_migrate_key_app_to_app() -> Result<()> {
3902 let mut db = new_test_db()?;
3903 const SOURCE_UID: u32 = 1u32;
3904 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003905 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3906 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003907 let key_id_guard =
3908 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3909 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3910
3911 let source_descriptor: KeyDescriptor = KeyDescriptor {
3912 domain: Domain::APP,
3913 nspace: -1,
3914 alias: Some(SOURCE_ALIAS.to_string()),
3915 blob: None,
3916 };
3917
3918 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3919 domain: Domain::APP,
3920 nspace: -1,
3921 alias: Some(DESTINATION_ALIAS.to_string()),
3922 blob: None,
3923 };
3924
3925 let key_id = key_id_guard.id();
3926
3927 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3928 Ok(())
3929 })
3930 .unwrap();
3931
3932 let (_, key_entry) = db
3933 .load_key_entry(
3934 &destination_descriptor,
3935 KeyType::Client,
3936 KeyEntryLoadBits::BOTH,
3937 DESTINATION_UID,
3938 |k, av| {
3939 assert_eq!(Domain::APP, k.domain);
3940 assert_eq!(DESTINATION_UID as i64, k.nspace);
3941 assert!(av.is_none());
3942 Ok(())
3943 },
3944 )
3945 .unwrap();
3946
3947 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3948
3949 assert_eq!(
3950 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3951 db.load_key_entry(
3952 &source_descriptor,
3953 KeyType::Client,
3954 KeyEntryLoadBits::NONE,
3955 SOURCE_UID,
3956 |_k, _av| Ok(()),
3957 )
3958 .unwrap_err()
3959 .root_cause()
3960 .downcast_ref::<KsError>()
3961 );
3962
3963 Ok(())
3964 }
3965
3966 // Creates a key migrates it to a different location and then tries to access it by the old
3967 // and new location.
3968 #[test]
3969 fn test_migrate_key_app_to_selinux() -> Result<()> {
3970 let mut db = new_test_db()?;
3971 const SOURCE_UID: u32 = 1u32;
3972 const DESTINATION_UID: u32 = 2u32;
3973 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003974 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3975 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003976 let key_id_guard =
3977 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3978 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3979
3980 let source_descriptor: KeyDescriptor = KeyDescriptor {
3981 domain: Domain::APP,
3982 nspace: -1,
3983 alias: Some(SOURCE_ALIAS.to_string()),
3984 blob: None,
3985 };
3986
3987 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3988 domain: Domain::SELINUX,
3989 nspace: DESTINATION_NAMESPACE,
3990 alias: Some(DESTINATION_ALIAS.to_string()),
3991 blob: None,
3992 };
3993
3994 let key_id = key_id_guard.id();
3995
3996 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3997 Ok(())
3998 })
3999 .unwrap();
4000
4001 let (_, key_entry) = db
4002 .load_key_entry(
4003 &destination_descriptor,
4004 KeyType::Client,
4005 KeyEntryLoadBits::BOTH,
4006 DESTINATION_UID,
4007 |k, av| {
4008 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00004009 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004010 assert!(av.is_none());
4011 Ok(())
4012 },
4013 )
4014 .unwrap();
4015
4016 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4017
4018 assert_eq!(
4019 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4020 db.load_key_entry(
4021 &source_descriptor,
4022 KeyType::Client,
4023 KeyEntryLoadBits::NONE,
4024 SOURCE_UID,
4025 |_k, _av| Ok(()),
4026 )
4027 .unwrap_err()
4028 .root_cause()
4029 .downcast_ref::<KsError>()
4030 );
4031
4032 Ok(())
4033 }
4034
4035 // Creates two keys and tries to migrate the first to the location of the second which
4036 // is expected to fail.
4037 #[test]
4038 fn test_migrate_key_destination_occupied() -> Result<()> {
4039 let mut db = new_test_db()?;
4040 const SOURCE_UID: u32 = 1u32;
4041 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004042 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4043 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004044 let key_id_guard =
4045 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4046 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4047 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4048 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4049
4050 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4051 domain: Domain::APP,
4052 nspace: -1,
4053 alias: Some(DESTINATION_ALIAS.to_string()),
4054 blob: None,
4055 };
4056
4057 assert_eq!(
4058 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4059 db.migrate_key_namespace(
4060 key_id_guard,
4061 &destination_descriptor,
4062 DESTINATION_UID,
4063 |_k| Ok(())
4064 )
4065 .unwrap_err()
4066 .root_cause()
4067 .downcast_ref::<KsError>()
4068 );
4069
4070 Ok(())
4071 }
4072
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004073 #[test]
4074 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004075 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4076 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4077 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004078 const UID: u32 = 33;
4079 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4080 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4081 let key_id_untouched1 =
4082 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4083 let key_id_untouched2 =
4084 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4085 let key_id_deleted =
4086 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4087
4088 let (_, key_entry) = db
4089 .load_key_entry(
4090 &KeyDescriptor {
4091 domain: Domain::APP,
4092 nspace: -1,
4093 alias: Some(ALIAS1.to_string()),
4094 blob: None,
4095 },
4096 KeyType::Client,
4097 KeyEntryLoadBits::BOTH,
4098 UID,
4099 |k, av| {
4100 assert_eq!(Domain::APP, k.domain);
4101 assert_eq!(UID as i64, k.nspace);
4102 assert!(av.is_none());
4103 Ok(())
4104 },
4105 )
4106 .unwrap();
4107 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4108 let (_, key_entry) = db
4109 .load_key_entry(
4110 &KeyDescriptor {
4111 domain: Domain::APP,
4112 nspace: -1,
4113 alias: Some(ALIAS2.to_string()),
4114 blob: None,
4115 },
4116 KeyType::Client,
4117 KeyEntryLoadBits::BOTH,
4118 UID,
4119 |k, av| {
4120 assert_eq!(Domain::APP, k.domain);
4121 assert_eq!(UID as i64, k.nspace);
4122 assert!(av.is_none());
4123 Ok(())
4124 },
4125 )
4126 .unwrap();
4127 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4128 let (_, key_entry) = db
4129 .load_key_entry(
4130 &KeyDescriptor {
4131 domain: Domain::APP,
4132 nspace: -1,
4133 alias: Some(ALIAS3.to_string()),
4134 blob: None,
4135 },
4136 KeyType::Client,
4137 KeyEntryLoadBits::BOTH,
4138 UID,
4139 |k, av| {
4140 assert_eq!(Domain::APP, k.domain);
4141 assert_eq!(UID as i64, k.nspace);
4142 assert!(av.is_none());
4143 Ok(())
4144 },
4145 )
4146 .unwrap();
4147 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4148
4149 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4150 KeystoreDB::from_0_to_1(tx).no_gc()
4151 })
4152 .unwrap();
4153
4154 let (_, key_entry) = db
4155 .load_key_entry(
4156 &KeyDescriptor {
4157 domain: Domain::APP,
4158 nspace: -1,
4159 alias: Some(ALIAS1.to_string()),
4160 blob: None,
4161 },
4162 KeyType::Client,
4163 KeyEntryLoadBits::BOTH,
4164 UID,
4165 |k, av| {
4166 assert_eq!(Domain::APP, k.domain);
4167 assert_eq!(UID as i64, k.nspace);
4168 assert!(av.is_none());
4169 Ok(())
4170 },
4171 )
4172 .unwrap();
4173 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4174 let (_, key_entry) = db
4175 .load_key_entry(
4176 &KeyDescriptor {
4177 domain: Domain::APP,
4178 nspace: -1,
4179 alias: Some(ALIAS2.to_string()),
4180 blob: None,
4181 },
4182 KeyType::Client,
4183 KeyEntryLoadBits::BOTH,
4184 UID,
4185 |k, av| {
4186 assert_eq!(Domain::APP, k.domain);
4187 assert_eq!(UID as i64, k.nspace);
4188 assert!(av.is_none());
4189 Ok(())
4190 },
4191 )
4192 .unwrap();
4193 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4194 assert_eq!(
4195 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4196 db.load_key_entry(
4197 &KeyDescriptor {
4198 domain: Domain::APP,
4199 nspace: -1,
4200 alias: Some(ALIAS3.to_string()),
4201 blob: None,
4202 },
4203 KeyType::Client,
4204 KeyEntryLoadBits::BOTH,
4205 UID,
4206 |k, av| {
4207 assert_eq!(Domain::APP, k.domain);
4208 assert_eq!(UID as i64, k.nspace);
4209 assert!(av.is_none());
4210 Ok(())
4211 },
4212 )
4213 .unwrap_err()
4214 .root_cause()
4215 .downcast_ref::<KsError>()
4216 );
4217 }
4218
Janis Danisevskisaec14592020-11-12 09:41:49 -08004219 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4220
Janis Danisevskisaec14592020-11-12 09:41:49 -08004221 #[test]
4222 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4223 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004224 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4225 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004226 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004227 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004228 .context("test_insert_and_load_full_keyentry_domain_app")?
4229 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004230 let (_key_guard, key_entry) = db
4231 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004232 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004233 domain: Domain::APP,
4234 nspace: 0,
4235 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4236 blob: None,
4237 },
4238 KeyType::Client,
4239 KeyEntryLoadBits::BOTH,
4240 33,
4241 |_k, _av| Ok(()),
4242 )
4243 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004244 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004245 let state = Arc::new(AtomicU8::new(1));
4246 let state2 = state.clone();
4247
4248 // Spawning a second thread that attempts to acquire the key id lock
4249 // for the same key as the primary thread. The primary thread then
4250 // waits, thereby forcing the secondary thread into the second stage
4251 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4252 // The test succeeds if the secondary thread observes the transition
4253 // of `state` from 1 to 2, despite having a whole second to overtake
4254 // the primary thread.
4255 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004256 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004257 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004258 assert!(db
4259 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004260 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004261 domain: Domain::APP,
4262 nspace: 0,
4263 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4264 blob: None,
4265 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004266 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004267 KeyEntryLoadBits::BOTH,
4268 33,
4269 |_k, _av| Ok(()),
4270 )
4271 .is_ok());
4272 // We should only see a 2 here because we can only return
4273 // from load_key_entry when the `_key_guard` expires,
4274 // which happens at the end of the scope.
4275 assert_eq!(2, state2.load(Ordering::Relaxed));
4276 });
4277
4278 thread::sleep(std::time::Duration::from_millis(1000));
4279
4280 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4281
4282 // Return the handle from this scope so we can join with the
4283 // secondary thread after the key id lock has expired.
4284 handle
4285 // This is where the `_key_guard` goes out of scope,
4286 // which is the reason for concurrent load_key_entry on the same key
4287 // to unblock.
4288 };
4289 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4290 // main test thread. We will not see failing asserts in secondary threads otherwise.
4291 handle.join().unwrap();
4292 Ok(())
4293 }
4294
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004295 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004296 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004297 let temp_dir =
4298 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4299
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004300 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4301 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004302
4303 let _tx1 = db1
4304 .conn
4305 .transaction_with_behavior(TransactionBehavior::Immediate)
4306 .expect("Failed to create first transaction.");
4307
4308 let error = db2
4309 .conn
4310 .transaction_with_behavior(TransactionBehavior::Immediate)
4311 .context("Transaction begin failed.")
4312 .expect_err("This should fail.");
4313 let root_cause = error.root_cause();
4314 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4315 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4316 {
4317 return;
4318 }
4319 panic!(
4320 "Unexpected error {:?} \n{:?} \n{:?}",
4321 error,
4322 root_cause,
4323 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4324 )
4325 }
4326
4327 #[cfg(disabled)]
4328 #[test]
4329 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4330 let temp_dir = Arc::new(
4331 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4332 .expect("Failed to create temp dir."),
4333 );
4334
4335 let test_begin = Instant::now();
4336
Janis Danisevskis66784c42021-01-27 08:40:25 -08004337 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004338 let mut db =
4339 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004340 const OPEN_DB_COUNT: u32 = 50u32;
4341
4342 let mut actual_key_count = KEY_COUNT;
4343 // First insert KEY_COUNT keys.
4344 for count in 0..KEY_COUNT {
4345 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4346 actual_key_count = count;
4347 break;
4348 }
4349 let alias = format!("test_alias_{}", count);
4350 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4351 .expect("Failed to make key entry.");
4352 }
4353
4354 // Insert more keys from a different thread and into a different namespace.
4355 let temp_dir1 = temp_dir.clone();
4356 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004357 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4358 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004359
4360 for count in 0..actual_key_count {
4361 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4362 return;
4363 }
4364 let alias = format!("test_alias_{}", count);
4365 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4366 .expect("Failed to make key entry.");
4367 }
4368
4369 // then unbind them again.
4370 for count in 0..actual_key_count {
4371 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4372 return;
4373 }
4374 let key = KeyDescriptor {
4375 domain: Domain::APP,
4376 nspace: -1,
4377 alias: Some(format!("test_alias_{}", count)),
4378 blob: None,
4379 };
4380 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4381 }
4382 });
4383
4384 // And start unbinding the first set of keys.
4385 let temp_dir2 = temp_dir.clone();
4386 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004387 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4388 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004389
4390 for count in 0..actual_key_count {
4391 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4392 return;
4393 }
4394 let key = KeyDescriptor {
4395 domain: Domain::APP,
4396 nspace: -1,
4397 alias: Some(format!("test_alias_{}", count)),
4398 blob: None,
4399 };
4400 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4401 }
4402 });
4403
Janis Danisevskis66784c42021-01-27 08:40:25 -08004404 // While a lot of inserting and deleting is going on we have to open database connections
4405 // successfully and use them.
4406 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4407 // out of scope.
4408 #[allow(clippy::redundant_clone)]
4409 let temp_dir4 = temp_dir.clone();
4410 let handle4 = thread::spawn(move || {
4411 for count in 0..OPEN_DB_COUNT {
4412 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4413 return;
4414 }
Seth Moore444b51a2021-06-11 09:49:49 -07004415 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4416 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004417
4418 let alias = format!("test_alias_{}", count);
4419 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4420 .expect("Failed to make key entry.");
4421 let key = KeyDescriptor {
4422 domain: Domain::APP,
4423 nspace: -1,
4424 alias: Some(alias),
4425 blob: None,
4426 };
4427 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4428 }
4429 });
4430
4431 handle1.join().expect("Thread 1 panicked.");
4432 handle2.join().expect("Thread 2 panicked.");
4433 handle4.join().expect("Thread 4 panicked.");
4434
Janis Danisevskis66784c42021-01-27 08:40:25 -08004435 Ok(())
4436 }
4437
4438 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004439 fn list() -> Result<()> {
4440 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004441 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004442 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4443 (Domain::APP, 1, "test1"),
4444 (Domain::APP, 1, "test2"),
4445 (Domain::APP, 1, "test3"),
4446 (Domain::APP, 1, "test4"),
4447 (Domain::APP, 1, "test5"),
4448 (Domain::APP, 1, "test6"),
4449 (Domain::APP, 1, "test7"),
4450 (Domain::APP, 2, "test1"),
4451 (Domain::APP, 2, "test2"),
4452 (Domain::APP, 2, "test3"),
4453 (Domain::APP, 2, "test4"),
4454 (Domain::APP, 2, "test5"),
4455 (Domain::APP, 2, "test6"),
4456 (Domain::APP, 2, "test8"),
4457 (Domain::SELINUX, 100, "test1"),
4458 (Domain::SELINUX, 100, "test2"),
4459 (Domain::SELINUX, 100, "test3"),
4460 (Domain::SELINUX, 100, "test4"),
4461 (Domain::SELINUX, 100, "test5"),
4462 (Domain::SELINUX, 100, "test6"),
4463 (Domain::SELINUX, 100, "test9"),
4464 ];
4465
4466 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4467 .iter()
4468 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004469 let entry =
4470 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004471 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4472 });
4473 (entry.id(), *ns)
4474 })
4475 .collect();
4476
4477 for (domain, namespace) in
4478 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4479 {
4480 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4481 .iter()
4482 .filter_map(|(domain, ns, alias)| match ns {
4483 ns if *ns == *namespace => Some(KeyDescriptor {
4484 domain: *domain,
4485 nspace: *ns,
4486 alias: Some(alias.to_string()),
4487 blob: None,
4488 }),
4489 _ => None,
4490 })
4491 .collect();
4492 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004493 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004494 list_result.sort();
4495 assert_eq!(list_o_descriptors, list_result);
4496
4497 let mut list_o_ids: Vec<i64> = list_o_descriptors
4498 .into_iter()
4499 .map(|d| {
4500 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004501 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004502 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004503 KeyType::Client,
4504 KeyEntryLoadBits::NONE,
4505 *namespace as u32,
4506 |_, _| Ok(()),
4507 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004508 .unwrap();
4509 entry.id()
4510 })
4511 .collect();
4512 list_o_ids.sort_unstable();
4513 let mut loaded_entries: Vec<i64> = list_o_keys
4514 .iter()
4515 .filter_map(|(id, ns)| match ns {
4516 ns if *ns == *namespace => Some(*id),
4517 _ => None,
4518 })
4519 .collect();
4520 loaded_entries.sort_unstable();
4521 assert_eq!(list_o_ids, loaded_entries);
4522 }
Eran Messeri24f31972023-01-25 17:00:33 +00004523 assert_eq!(
4524 Vec::<KeyDescriptor>::new(),
4525 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4526 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004527
4528 Ok(())
4529 }
4530
Joel Galenson0891bc12020-07-20 10:37:03 -07004531 // Helpers
4532
4533 // Checks that the given result is an error containing the given string.
4534 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4535 let error_str = format!(
4536 "{:#?}",
4537 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4538 );
4539 assert!(
4540 error_str.contains(target),
4541 "The string \"{}\" should contain \"{}\"",
4542 error_str,
4543 target
4544 );
4545 }
4546
Joel Galenson2aab4432020-07-22 15:27:57 -07004547 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004548 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004549 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004550 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004551 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004552 namespace: Option<i64>,
4553 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004554 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004555 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004556 }
4557
4558 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4559 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004560 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004561 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004562 Ok(KeyEntryRow {
4563 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004564 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004565 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004566 namespace: row.get(3)?,
4567 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004568 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004569 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004570 })
4571 })?
4572 .map(|r| r.context("Could not read keyentry row."))
4573 .collect::<Result<Vec<_>>>()
4574 }
4575
Eran Messeri4dc27b52024-01-09 12:43:31 +00004576 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4577 make_test_params_with_sids(max_usage_count, &[42])
4578 }
4579
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004580 // Note: The parameters and SecurityLevel associations are nonsensical. This
4581 // collection is only used to check if the parameters are preserved as expected by the
4582 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004583 fn make_test_params_with_sids(
4584 max_usage_count: Option<i32>,
4585 user_secure_ids: &[i64],
4586 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004587 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004588 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4589 KeyParameter::new(
4590 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4591 SecurityLevel::TRUSTED_ENVIRONMENT,
4592 ),
4593 KeyParameter::new(
4594 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4595 SecurityLevel::TRUSTED_ENVIRONMENT,
4596 ),
4597 KeyParameter::new(
4598 KeyParameterValue::Algorithm(Algorithm::RSA),
4599 SecurityLevel::TRUSTED_ENVIRONMENT,
4600 ),
4601 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4602 KeyParameter::new(
4603 KeyParameterValue::BlockMode(BlockMode::ECB),
4604 SecurityLevel::TRUSTED_ENVIRONMENT,
4605 ),
4606 KeyParameter::new(
4607 KeyParameterValue::BlockMode(BlockMode::GCM),
4608 SecurityLevel::TRUSTED_ENVIRONMENT,
4609 ),
4610 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4611 KeyParameter::new(
4612 KeyParameterValue::Digest(Digest::MD5),
4613 SecurityLevel::TRUSTED_ENVIRONMENT,
4614 ),
4615 KeyParameter::new(
4616 KeyParameterValue::Digest(Digest::SHA_2_224),
4617 SecurityLevel::TRUSTED_ENVIRONMENT,
4618 ),
4619 KeyParameter::new(
4620 KeyParameterValue::Digest(Digest::SHA_2_256),
4621 SecurityLevel::STRONGBOX,
4622 ),
4623 KeyParameter::new(
4624 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4625 SecurityLevel::TRUSTED_ENVIRONMENT,
4626 ),
4627 KeyParameter::new(
4628 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4629 SecurityLevel::TRUSTED_ENVIRONMENT,
4630 ),
4631 KeyParameter::new(
4632 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4633 SecurityLevel::STRONGBOX,
4634 ),
4635 KeyParameter::new(
4636 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4637 SecurityLevel::TRUSTED_ENVIRONMENT,
4638 ),
4639 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4640 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4641 KeyParameter::new(
4642 KeyParameterValue::EcCurve(EcCurve::P_224),
4643 SecurityLevel::TRUSTED_ENVIRONMENT,
4644 ),
4645 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4646 KeyParameter::new(
4647 KeyParameterValue::EcCurve(EcCurve::P_384),
4648 SecurityLevel::TRUSTED_ENVIRONMENT,
4649 ),
4650 KeyParameter::new(
4651 KeyParameterValue::EcCurve(EcCurve::P_521),
4652 SecurityLevel::TRUSTED_ENVIRONMENT,
4653 ),
4654 KeyParameter::new(
4655 KeyParameterValue::RSAPublicExponent(3),
4656 SecurityLevel::TRUSTED_ENVIRONMENT,
4657 ),
4658 KeyParameter::new(
4659 KeyParameterValue::IncludeUniqueID,
4660 SecurityLevel::TRUSTED_ENVIRONMENT,
4661 ),
4662 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4663 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4664 KeyParameter::new(
4665 KeyParameterValue::ActiveDateTime(1234567890),
4666 SecurityLevel::STRONGBOX,
4667 ),
4668 KeyParameter::new(
4669 KeyParameterValue::OriginationExpireDateTime(1234567890),
4670 SecurityLevel::TRUSTED_ENVIRONMENT,
4671 ),
4672 KeyParameter::new(
4673 KeyParameterValue::UsageExpireDateTime(1234567890),
4674 SecurityLevel::TRUSTED_ENVIRONMENT,
4675 ),
4676 KeyParameter::new(
4677 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4678 SecurityLevel::TRUSTED_ENVIRONMENT,
4679 ),
4680 KeyParameter::new(
4681 KeyParameterValue::MaxUsesPerBoot(1234567890),
4682 SecurityLevel::TRUSTED_ENVIRONMENT,
4683 ),
4684 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004685 KeyParameter::new(
4686 KeyParameterValue::NoAuthRequired,
4687 SecurityLevel::TRUSTED_ENVIRONMENT,
4688 ),
4689 KeyParameter::new(
4690 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4691 SecurityLevel::TRUSTED_ENVIRONMENT,
4692 ),
4693 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4694 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4695 KeyParameter::new(
4696 KeyParameterValue::TrustedUserPresenceRequired,
4697 SecurityLevel::TRUSTED_ENVIRONMENT,
4698 ),
4699 KeyParameter::new(
4700 KeyParameterValue::TrustedConfirmationRequired,
4701 SecurityLevel::TRUSTED_ENVIRONMENT,
4702 ),
4703 KeyParameter::new(
4704 KeyParameterValue::UnlockedDeviceRequired,
4705 SecurityLevel::TRUSTED_ENVIRONMENT,
4706 ),
4707 KeyParameter::new(
4708 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4709 SecurityLevel::SOFTWARE,
4710 ),
4711 KeyParameter::new(
4712 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4713 SecurityLevel::SOFTWARE,
4714 ),
4715 KeyParameter::new(
4716 KeyParameterValue::CreationDateTime(12345677890),
4717 SecurityLevel::SOFTWARE,
4718 ),
4719 KeyParameter::new(
4720 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4721 SecurityLevel::TRUSTED_ENVIRONMENT,
4722 ),
4723 KeyParameter::new(
4724 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4725 SecurityLevel::TRUSTED_ENVIRONMENT,
4726 ),
4727 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4728 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4729 KeyParameter::new(
4730 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4731 SecurityLevel::SOFTWARE,
4732 ),
4733 KeyParameter::new(
4734 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4735 SecurityLevel::TRUSTED_ENVIRONMENT,
4736 ),
4737 KeyParameter::new(
4738 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4739 SecurityLevel::TRUSTED_ENVIRONMENT,
4740 ),
4741 KeyParameter::new(
4742 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4743 SecurityLevel::TRUSTED_ENVIRONMENT,
4744 ),
4745 KeyParameter::new(
4746 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4747 SecurityLevel::TRUSTED_ENVIRONMENT,
4748 ),
4749 KeyParameter::new(
4750 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4751 SecurityLevel::TRUSTED_ENVIRONMENT,
4752 ),
4753 KeyParameter::new(
4754 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4755 SecurityLevel::TRUSTED_ENVIRONMENT,
4756 ),
4757 KeyParameter::new(
4758 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4759 SecurityLevel::TRUSTED_ENVIRONMENT,
4760 ),
4761 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004762 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4763 SecurityLevel::TRUSTED_ENVIRONMENT,
4764 ),
4765 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004766 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4767 SecurityLevel::TRUSTED_ENVIRONMENT,
4768 ),
4769 KeyParameter::new(
4770 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4771 SecurityLevel::TRUSTED_ENVIRONMENT,
4772 ),
4773 KeyParameter::new(
4774 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4775 SecurityLevel::TRUSTED_ENVIRONMENT,
4776 ),
4777 KeyParameter::new(
4778 KeyParameterValue::VendorPatchLevel(3),
4779 SecurityLevel::TRUSTED_ENVIRONMENT,
4780 ),
4781 KeyParameter::new(
4782 KeyParameterValue::BootPatchLevel(4),
4783 SecurityLevel::TRUSTED_ENVIRONMENT,
4784 ),
4785 KeyParameter::new(
4786 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4787 SecurityLevel::TRUSTED_ENVIRONMENT,
4788 ),
4789 KeyParameter::new(
4790 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4791 SecurityLevel::TRUSTED_ENVIRONMENT,
4792 ),
4793 KeyParameter::new(
4794 KeyParameterValue::MacLength(256),
4795 SecurityLevel::TRUSTED_ENVIRONMENT,
4796 ),
4797 KeyParameter::new(
4798 KeyParameterValue::ResetSinceIdRotation,
4799 SecurityLevel::TRUSTED_ENVIRONMENT,
4800 ),
4801 KeyParameter::new(
4802 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4803 SecurityLevel::TRUSTED_ENVIRONMENT,
4804 ),
Qi Wub9433b52020-12-01 14:52:46 +08004805 ];
4806 if let Some(value) = max_usage_count {
4807 params.push(KeyParameter::new(
4808 KeyParameterValue::UsageCountLimit(value),
4809 SecurityLevel::SOFTWARE,
4810 ));
4811 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004812
4813 for sid in user_secure_ids.iter() {
4814 params.push(KeyParameter::new(
4815 KeyParameterValue::UserSecureID(*sid),
4816 SecurityLevel::STRONGBOX,
4817 ));
4818 }
Qi Wub9433b52020-12-01 14:52:46 +08004819 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004820 }
4821
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004822 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004823 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004824 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004825 namespace: i64,
4826 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004827 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004828 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004829 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4830 }
4831
4832 pub fn make_test_key_entry_with_sids(
4833 db: &mut KeystoreDB,
4834 domain: Domain,
4835 namespace: i64,
4836 alias: &str,
4837 max_usage_count: Option<i32>,
4838 sids: &[i64],
4839 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004840 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004841 let mut blob_metadata = BlobMetaData::new();
4842 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4843 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4844 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4845 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4846 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4847
4848 db.set_blob(
4849 &key_id,
4850 SubComponentType::KEY_BLOB,
4851 Some(TEST_KEY_BLOB),
4852 Some(&blob_metadata),
4853 )?;
4854 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4855 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004856
Eran Messeri4dc27b52024-01-09 12:43:31 +00004857 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004858 db.insert_keyparameter(&key_id, &params)?;
4859
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004860 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004861 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004862 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004863 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004864 Ok(key_id)
4865 }
4866
Qi Wub9433b52020-12-01 14:52:46 +08004867 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4868 let params = make_test_params(max_usage_count);
4869
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004870 let mut blob_metadata = BlobMetaData::new();
4871 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4872 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4873 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4874 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4875 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4876
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004877 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004878 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004879
4880 KeyEntry {
4881 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004882 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004883 cert: Some(TEST_CERT_BLOB.to_vec()),
4884 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004885 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004886 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004887 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004888 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004889 }
4890 }
4891
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004892 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004893 db: &mut KeystoreDB,
4894 domain: Domain,
4895 namespace: i64,
4896 alias: &str,
4897 logical_only: bool,
4898 ) -> Result<KeyIdGuard> {
4899 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4900 let mut blob_metadata = BlobMetaData::new();
4901 if !logical_only {
4902 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4903 }
4904 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4905
4906 db.set_blob(
4907 &key_id,
4908 SubComponentType::KEY_BLOB,
4909 Some(TEST_KEY_BLOB),
4910 Some(&blob_metadata),
4911 )?;
4912 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4913 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4914
4915 let mut params = make_test_params(None);
4916 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4917
4918 db.insert_keyparameter(&key_id, &params)?;
4919
4920 let mut metadata = KeyMetaData::new();
4921 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4922 db.insert_key_metadata(&key_id, &metadata)?;
4923 rebind_alias(db, &key_id, alias, domain, namespace)?;
4924 Ok(key_id)
4925 }
4926
Eric Biggersb0478cf2023-10-27 03:55:29 +00004927 // Creates an app key that is marked as being superencrypted by the given
4928 // super key ID and that has the given authentication and unlocked device
4929 // parameters. This does not actually superencrypt the key blob.
4930 fn make_superencrypted_key_entry(
4931 db: &mut KeystoreDB,
4932 namespace: i64,
4933 alias: &str,
4934 requires_authentication: bool,
4935 requires_unlocked_device: bool,
4936 super_key_id: i64,
4937 ) -> Result<KeyIdGuard> {
4938 let domain = Domain::APP;
4939 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4940
4941 let mut blob_metadata = BlobMetaData::new();
4942 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4943 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4944 db.set_blob(
4945 &key_id,
4946 SubComponentType::KEY_BLOB,
4947 Some(TEST_KEY_BLOB),
4948 Some(&blob_metadata),
4949 )?;
4950
4951 let mut params = vec![];
4952 if requires_unlocked_device {
4953 params.push(KeyParameter::new(
4954 KeyParameterValue::UnlockedDeviceRequired,
4955 SecurityLevel::TRUSTED_ENVIRONMENT,
4956 ));
4957 }
4958 if requires_authentication {
4959 params.push(KeyParameter::new(
4960 KeyParameterValue::UserSecureID(42),
4961 SecurityLevel::TRUSTED_ENVIRONMENT,
4962 ));
4963 }
4964 db.insert_keyparameter(&key_id, &params)?;
4965
4966 let mut metadata = KeyMetaData::new();
4967 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4968 db.insert_key_metadata(&key_id, &metadata)?;
4969
4970 rebind_alias(db, &key_id, alias, domain, namespace)?;
4971 Ok(key_id)
4972 }
4973
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004974 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4975 let mut params = make_test_params(None);
4976 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4977
4978 let mut blob_metadata = BlobMetaData::new();
4979 if !logical_only {
4980 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4981 }
4982 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4983
4984 let mut metadata = KeyMetaData::new();
4985 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4986
4987 KeyEntry {
4988 id: key_id,
4989 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4990 cert: Some(TEST_CERT_BLOB.to_vec()),
4991 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4992 km_uuid: KEYSTORE_UUID,
4993 parameters: params,
4994 metadata,
4995 pure_cert: false,
4996 }
4997 }
4998
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004999 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005000 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005001 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005002 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005003 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005004 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005005 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005006 Ok((
5007 row.get(0)?,
5008 row.get(1)?,
5009 row.get(2)?,
5010 row.get(3)?,
5011 row.get(4)?,
5012 row.get(5)?,
5013 row.get(6)?,
5014 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005015 },
5016 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005017
5018 println!("Key entry table rows:");
5019 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005020 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005021 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005022 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5023 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005024 );
5025 }
5026 Ok(())
5027 }
5028
5029 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005030 let mut stmt = db
5031 .conn
5032 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00005033 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005034 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5035 })?;
5036
5037 println!("Grant table rows:");
5038 for r in rows {
5039 let (id, gt, ki, av) = r.unwrap();
5040 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5041 }
5042 Ok(())
5043 }
5044
Joel Galenson0891bc12020-07-20 10:37:03 -07005045 // Use a custom random number generator that repeats each number once.
5046 // This allows us to test repeated elements.
5047
5048 thread_local! {
Charisee43391152024-04-02 16:16:30 +00005049 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07005050 }
5051
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005052 fn reset_random() {
5053 RANDOM_COUNTER.with(|counter| {
5054 *counter.borrow_mut() = 0;
5055 })
5056 }
5057
Joel Galenson0891bc12020-07-20 10:37:03 -07005058 pub fn random() -> i64 {
5059 RANDOM_COUNTER.with(|counter| {
5060 let result = *counter.borrow() / 2;
5061 *counter.borrow_mut() += 1;
5062 result
5063 })
5064 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005065
5066 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005067 fn test_unbind_keys_for_user() -> Result<()> {
5068 let mut db = new_test_db()?;
5069 db.unbind_keys_for_user(1, false)?;
5070
5071 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5072 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5073 db.unbind_keys_for_user(2, false)?;
5074
Eran Messeri24f31972023-01-25 17:00:33 +00005075 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
5076 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005077
5078 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00005079 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005080
5081 Ok(())
5082 }
5083
5084 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005085 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5086 let mut db = new_test_db()?;
5087 let super_key = keystore2_crypto::generate_aes256_key()?;
5088 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5089 let (encrypted_super_key, metadata) =
5090 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5091
5092 let key_name_enc = SuperKeyType {
5093 alias: "test_super_key_1",
5094 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005095 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005096 };
5097
5098 let key_name_nonenc = SuperKeyType {
5099 alias: "test_super_key_2",
5100 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005101 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005102 };
5103
5104 // Install two super keys.
5105 db.store_super_key(
5106 1,
5107 &key_name_nonenc,
5108 &super_key,
5109 &BlobMetaData::new(),
5110 &KeyMetaData::new(),
5111 )?;
5112 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5113
5114 // Check that both can be found in the database.
5115 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5116 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5117
5118 // Install the same keys for a different user.
5119 db.store_super_key(
5120 2,
5121 &key_name_nonenc,
5122 &super_key,
5123 &BlobMetaData::new(),
5124 &KeyMetaData::new(),
5125 )?;
5126 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5127
5128 // Check that the second pair of keys can be found in the database.
5129 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5130 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5131
5132 // Delete only encrypted keys.
5133 db.unbind_keys_for_user(1, true)?;
5134
5135 // The encrypted superkey should be gone now.
5136 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5137 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5138
5139 // Reinsert the encrypted key.
5140 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5141
5142 // Check that both can be found in the database, again..
5143 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5144 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5145
5146 // Delete all even unencrypted keys.
5147 db.unbind_keys_for_user(1, false)?;
5148
5149 // Both should be gone now.
5150 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5151 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5152
5153 // Check that the second pair of keys was untouched.
5154 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5155 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5156
5157 Ok(())
5158 }
5159
Eric Biggersb0478cf2023-10-27 03:55:29 +00005160 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5161 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5162 }
5163
5164 // Tests the unbind_auth_bound_keys_for_user() function.
5165 #[test]
5166 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5167 let mut db = new_test_db()?;
5168 let user_id = 1;
5169 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5170 let other_user_id = 2;
5171 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5172 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5173
5174 // Create a superencryption key.
5175 let super_key = keystore2_crypto::generate_aes256_key()?;
5176 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5177 let (encrypted_super_key, blob_metadata) =
5178 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5179 db.store_super_key(
5180 user_id,
5181 super_key_type,
5182 &encrypted_super_key,
5183 &blob_metadata,
5184 &KeyMetaData::new(),
5185 )?;
5186 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5187
5188 // Store 4 superencrypted app keys, one for each possible combination of
5189 // (authentication required, unlocked device required).
5190 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5191 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5192 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5193 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5194 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5195 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5196 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5197 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5198
5199 // Also store a key for a different user that requires authentication.
5200 make_superencrypted_key_entry(
5201 &mut db,
5202 other_user_nspace,
5203 "auth_ud",
5204 true,
5205 true,
5206 super_key_id,
5207 )?;
5208
5209 db.unbind_auth_bound_keys_for_user(user_id)?;
5210
5211 // Verify that only the user's app keys that require authentication were
5212 // deleted. Keys that require an unlocked device but not authentication
5213 // should *not* have been deleted, nor should the super key have been
5214 // deleted, nor should other users' keys have been deleted.
5215 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5216 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5217 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5218 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5219 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5220 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5221
5222 Ok(())
5223 }
5224
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005225 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005226 fn test_store_super_key() -> Result<()> {
5227 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005228 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005229 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005230 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005231 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005232 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005233
5234 let (encrypted_super_key, metadata) =
5235 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005236 db.store_super_key(
5237 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005238 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005239 &encrypted_super_key,
5240 &metadata,
5241 &KeyMetaData::new(),
5242 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005243
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005244 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005245 assert!(db.key_exists(
5246 Domain::APP,
5247 1,
5248 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5249 KeyType::Super
5250 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005251
Eric Biggers673d34a2023-10-18 01:54:18 +00005252 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005253 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005254 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005255 key_entry,
5256 &pw,
5257 None,
5258 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005259
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005260 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005261 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005262
Hasini Gunasingheda895552021-01-27 19:34:37 +00005263 Ok(())
5264 }
Seth Moore78c091f2021-04-09 21:38:30 +00005265
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005266 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005267 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005268 MetricsStorage::KEY_ENTRY,
5269 MetricsStorage::KEY_ENTRY_ID_INDEX,
5270 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5271 MetricsStorage::BLOB_ENTRY,
5272 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5273 MetricsStorage::KEY_PARAMETER,
5274 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5275 MetricsStorage::KEY_METADATA,
5276 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5277 MetricsStorage::GRANT,
5278 MetricsStorage::AUTH_TOKEN,
5279 MetricsStorage::BLOB_METADATA,
5280 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005281 ]
5282 }
5283
5284 /// Perform a simple check to ensure that we can query all the storage types
5285 /// that are supported by the DB. Check for reasonable values.
5286 #[test]
5287 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005288 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005289
5290 let mut db = new_test_db()?;
5291
5292 for t in get_valid_statsd_storage_types() {
5293 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005294 // AuthToken can be less than a page since it's in a btree, not sqlite
5295 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005296 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005297 } else {
5298 assert!(stat.size >= PAGE_SIZE);
5299 }
Seth Moore78c091f2021-04-09 21:38:30 +00005300 assert!(stat.size >= stat.unused_size);
5301 }
5302
5303 Ok(())
5304 }
5305
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005306 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005307 get_valid_statsd_storage_types()
5308 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005309 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005310 .collect()
5311 }
5312
5313 fn assert_storage_increased(
5314 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005315 increased_storage_types: Vec<MetricsStorage>,
5316 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005317 ) {
5318 for storage in increased_storage_types {
5319 // Verify the expected storage increased.
5320 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005321 let old = &baseline[&storage.0];
5322 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005323 assert!(
5324 new.unused_size <= old.unused_size,
5325 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005326 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005327 new.unused_size,
5328 old.unused_size
5329 );
5330
5331 // Update the baseline with the new value so that it succeeds in the
5332 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005333 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005334 }
5335
5336 // Get an updated map of the storage and verify there were no unexpected changes.
5337 let updated_stats = get_storage_stats_map(db);
5338 assert_eq!(updated_stats.len(), baseline.len());
5339
5340 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005341 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005342 let mut s = String::new();
5343 for &k in map.keys() {
5344 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5345 .expect("string concat failed");
5346 }
5347 s
5348 };
5349
5350 assert!(
5351 updated_stats[&k].size == baseline[&k].size
5352 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5353 "updated_stats:\n{}\nbaseline:\n{}",
5354 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005355 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005356 );
5357 }
5358 }
5359
5360 #[test]
5361 fn test_verify_key_table_size_reporting() -> Result<()> {
5362 let mut db = new_test_db()?;
5363 let mut working_stats = get_storage_stats_map(&mut db);
5364
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005365 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005366 assert_storage_increased(
5367 &mut db,
5368 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005369 MetricsStorage::KEY_ENTRY,
5370 MetricsStorage::KEY_ENTRY_ID_INDEX,
5371 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005372 ],
5373 &mut working_stats,
5374 );
5375
5376 let mut blob_metadata = BlobMetaData::new();
5377 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5378 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5379 assert_storage_increased(
5380 &mut db,
5381 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005382 MetricsStorage::BLOB_ENTRY,
5383 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5384 MetricsStorage::BLOB_METADATA,
5385 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005386 ],
5387 &mut working_stats,
5388 );
5389
5390 let params = make_test_params(None);
5391 db.insert_keyparameter(&key_id, &params)?;
5392 assert_storage_increased(
5393 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005394 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005395 &mut working_stats,
5396 );
5397
5398 let mut metadata = KeyMetaData::new();
5399 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5400 db.insert_key_metadata(&key_id, &metadata)?;
5401 assert_storage_increased(
5402 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005403 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005404 &mut working_stats,
5405 );
5406
5407 let mut sum = 0;
5408 for stat in working_stats.values() {
5409 sum += stat.size;
5410 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005411 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005412 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5413
5414 Ok(())
5415 }
5416
5417 #[test]
5418 fn test_verify_auth_table_size_reporting() -> Result<()> {
5419 let mut db = new_test_db()?;
5420 let mut working_stats = get_storage_stats_map(&mut db);
5421 db.insert_auth_token(&HardwareAuthToken {
5422 challenge: 123,
5423 userId: 456,
5424 authenticatorId: 789,
5425 authenticatorType: kmhw_authenticator_type::ANY,
5426 timestamp: Timestamp { milliSeconds: 10 },
5427 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005428 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005429 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005430 Ok(())
5431 }
5432
5433 #[test]
5434 fn test_verify_grant_table_size_reporting() -> Result<()> {
5435 const OWNER: i64 = 1;
5436 let mut db = new_test_db()?;
5437 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5438
5439 let mut working_stats = get_storage_stats_map(&mut db);
5440 db.grant(
5441 &KeyDescriptor {
5442 domain: Domain::APP,
5443 nspace: 0,
5444 alias: Some(TEST_ALIAS.to_string()),
5445 blob: None,
5446 },
5447 OWNER as u32,
5448 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005449 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005450 |_, _| Ok(()),
5451 )?;
5452
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005453 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005454
5455 Ok(())
5456 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005457
5458 #[test]
5459 fn find_auth_token_entry_returns_latest() -> Result<()> {
5460 let mut db = new_test_db()?;
5461 db.insert_auth_token(&HardwareAuthToken {
5462 challenge: 123,
5463 userId: 456,
5464 authenticatorId: 789,
5465 authenticatorType: kmhw_authenticator_type::ANY,
5466 timestamp: Timestamp { milliSeconds: 10 },
5467 mac: b"mac0".to_vec(),
5468 });
5469 std::thread::sleep(std::time::Duration::from_millis(1));
5470 db.insert_auth_token(&HardwareAuthToken {
5471 challenge: 123,
5472 userId: 457,
5473 authenticatorId: 789,
5474 authenticatorType: kmhw_authenticator_type::ANY,
5475 timestamp: Timestamp { milliSeconds: 12 },
5476 mac: b"mac1".to_vec(),
5477 });
5478 std::thread::sleep(std::time::Duration::from_millis(1));
5479 db.insert_auth_token(&HardwareAuthToken {
5480 challenge: 123,
5481 userId: 458,
5482 authenticatorId: 789,
5483 authenticatorType: kmhw_authenticator_type::ANY,
5484 timestamp: Timestamp { milliSeconds: 3 },
5485 mac: b"mac2".to_vec(),
5486 });
5487 // All three entries are in the database
5488 assert_eq!(db.perboot.auth_tokens_len(), 3);
5489 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005490 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005491 Ok(())
5492 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005493
5494 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005495 fn test_load_key_descriptor() -> Result<()> {
5496 let mut db = new_test_db()?;
5497 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5498
5499 let key = db.load_key_descriptor(key_id)?.unwrap();
5500
5501 assert_eq!(key.domain, Domain::APP);
5502 assert_eq!(key.nspace, 1);
5503 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5504
5505 // No such id
5506 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5507 Ok(())
5508 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005509
5510 #[test]
5511 fn test_get_list_app_uids_for_sid() -> Result<()> {
5512 let uid: i32 = 1;
5513 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5514 let first_sid = 667;
5515 let second_sid = 669;
5516 let first_app_id: i64 = 123 + uid_offset;
5517 let second_app_id: i64 = 456 + uid_offset;
5518 let third_app_id: i64 = 789 + uid_offset;
5519 let unrelated_app_id: i64 = 1011 + uid_offset;
5520 let mut db = new_test_db()?;
5521 make_test_key_entry_with_sids(
5522 &mut db,
5523 Domain::APP,
5524 first_app_id,
5525 TEST_ALIAS,
5526 None,
5527 &[first_sid],
5528 )
5529 .context("test_get_list_app_uids_for_sid")?;
5530 make_test_key_entry_with_sids(
5531 &mut db,
5532 Domain::APP,
5533 second_app_id,
5534 "alias2",
5535 None,
5536 &[first_sid],
5537 )
5538 .context("test_get_list_app_uids_for_sid")?;
5539 make_test_key_entry_with_sids(
5540 &mut db,
5541 Domain::APP,
5542 second_app_id,
5543 TEST_ALIAS,
5544 None,
5545 &[second_sid],
5546 )
5547 .context("test_get_list_app_uids_for_sid")?;
5548 make_test_key_entry_with_sids(
5549 &mut db,
5550 Domain::APP,
5551 third_app_id,
5552 "alias3",
5553 None,
5554 &[second_sid],
5555 )
5556 .context("test_get_list_app_uids_for_sid")?;
5557 make_test_key_entry_with_sids(
5558 &mut db,
5559 Domain::APP,
5560 unrelated_app_id,
5561 TEST_ALIAS,
5562 None,
5563 &[],
5564 )
5565 .context("test_get_list_app_uids_for_sid")?;
5566
5567 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5568 first_sid_apps.sort();
5569 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5570 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5571 second_sid_apps.sort();
5572 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5573 Ok(())
5574 }
5575
5576 #[test]
5577 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5578 let uid: i32 = 1;
5579 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5580 let first_sid = 667;
5581 let second_sid = 669;
5582 let third_sid = 772;
5583 let first_app_id: i64 = 123 + uid_offset;
5584 let second_app_id: i64 = 456 + uid_offset;
5585 let mut db = new_test_db()?;
5586 make_test_key_entry_with_sids(
5587 &mut db,
5588 Domain::APP,
5589 first_app_id,
5590 TEST_ALIAS,
5591 None,
5592 &[first_sid, second_sid],
5593 )
5594 .context("test_get_list_app_uids_for_sid")?;
5595 make_test_key_entry_with_sids(
5596 &mut db,
5597 Domain::APP,
5598 second_app_id,
5599 "alias2",
5600 None,
5601 &[second_sid, third_sid],
5602 )
5603 .context("test_get_list_app_uids_for_sid")?;
5604
5605 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5606 assert_eq!(first_sid_apps, vec![first_app_id]);
5607
5608 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5609 second_sid_apps.sort();
5610 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5611
5612 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5613 assert_eq!(third_sid_apps, vec![second_app_id]);
5614 Ok(())
5615 }
David Drysdale115c4722024-04-15 14:11:52 +01005616
5617 #[test]
5618 fn test_key_id_guard_immediate() -> Result<()> {
5619 if !keystore2_flags::database_loop_timeout() {
5620 eprintln!("Skipping test as loop timeout flag disabled");
5621 return Ok(());
5622 }
5623 // Emit logging from test.
5624 android_logger::init_once(
5625 android_logger::Config::default()
5626 .with_tag("keystore_database_tests")
5627 .with_max_level(log::LevelFilter::Debug),
5628 );
5629
5630 // Preparation: put a single entry into a test DB.
5631 let temp_dir = Arc::new(TempDir::new("key_id_guard_immediate")?);
5632 let temp_dir_clone_a = temp_dir.clone();
5633 let temp_dir_clone_b = temp_dir.clone();
5634 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5635 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5636
5637 let (a_sender, b_receiver) = std::sync::mpsc::channel();
5638 let (b_sender, a_receiver) = std::sync::mpsc::channel();
5639
5640 // First thread starts an immediate transaction, then waits on a synchronization channel
5641 // before trying to get the `KeyIdGuard`.
5642 let handle_a = thread::spawn(move || {
5643 let temp_dir = temp_dir_clone_a;
5644 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
5645
5646 // Make sure the other thread has initialized its database access before we lock it out.
5647 a_receiver.recv().unwrap();
5648
5649 let _result = db.with_transaction_timeout(
5650 TransactionBehavior::Immediate,
5651 Duration::from_secs(3),
5652 |_tx| {
5653 // Notify the other thread that we're inside the immediate transaction...
5654 a_sender.send(()).unwrap();
5655 // ...then wait to be sure that the other thread has the `KeyIdGuard` before
5656 // this thread also tries to get it.
5657 a_receiver.recv().unwrap();
5658
5659 let _guard = KEY_ID_LOCK.get(key_id);
5660 Ok(()).no_gc()
5661 },
5662 );
5663 });
5664
5665 // Second thread gets the `KeyIdGuard`, then waits before trying to perform an immediate
5666 // transaction.
5667 let handle_b = thread::spawn(move || {
5668 let temp_dir = temp_dir_clone_b;
5669 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
5670 // Notify the other thread that we are initialized (so it can lock the immediate
5671 // transaction).
5672 b_sender.send(()).unwrap();
5673
5674 let _guard = KEY_ID_LOCK.get(key_id);
5675 // Notify the other thread that we have the `KeyIdGuard`...
5676 b_sender.send(()).unwrap();
5677 // ...then wait to be sure that the other thread is in the immediate transaction before
5678 // this thread also tries to do one.
5679 b_receiver.recv().unwrap();
5680
5681 let result = db.with_transaction_timeout(
5682 TransactionBehavior::Immediate,
5683 Duration::from_secs(3),
5684 |_tx| Ok(()).no_gc(),
5685 );
5686 // Expect the attempt to get an immediate transaction to fail, and then this thread will
5687 // exit and release the `KeyIdGuard`, allowing the other thread to complete.
5688 assert!(result.is_err());
5689 check_result_is_error_containing_string(result, "BACKEND_BUSY");
5690 });
5691
5692 let _ = handle_a.join();
5693 let _ = handle_b.join();
5694
5695 Ok(())
5696 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005697}