blob: ee9d2462e718c772fe6209c709942ad103c22f1f [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 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800403}
404
405impl ToSql for DateTime {
406 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
407 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
408 }
409}
410
411impl FromSql for DateTime {
412 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
413 Ok(Self(i64::column_result(value)?))
414 }
415}
416
417impl TryInto<SystemTime> for DateTime {
418 type Error = DateTimeError;
419
420 fn try_into(self) -> Result<SystemTime, Self::Error> {
421 // We want to construct a SystemTime representation equivalent to self, denoting
422 // a point in time THEN, but we cannot set the time directly. We can only construct
423 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
424 // and between EPOCH and THEN. With this common reference we can construct the
425 // duration between NOW and THEN which we can add to our SystemTime representation
426 // of NOW to get a SystemTime representation of THEN.
427 // Durations can only be positive, thus the if statement below.
428 let now = SystemTime::now();
429 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
430 let then_epoch = Duration::from_millis(self.0.try_into()?);
431 Ok(if now_epoch > then_epoch {
432 // then = now - (now_epoch - then_epoch)
433 now_epoch
434 .checked_sub(then_epoch)
435 .and_then(|d| now.checked_sub(d))
436 .ok_or(DateTimeError::TimeArithmetic)?
437 } else {
438 // then = now + (then_epoch - now_epoch)
439 then_epoch
440 .checked_sub(now_epoch)
441 .and_then(|d| now.checked_add(d))
442 .ok_or(DateTimeError::TimeArithmetic)?
443 })
444 }
445}
446
447impl TryFrom<SystemTime> for DateTime {
448 type Error = DateTimeError;
449
450 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
451 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
452 }
453}
454
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800455#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
456enum KeyLifeCycle {
457 /// Existing keys have a key ID but are not fully populated yet.
458 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
459 /// them to Unreferenced for garbage collection.
460 Existing,
461 /// A live key is fully populated and usable by clients.
462 Live,
463 /// An unreferenced key is scheduled for garbage collection.
464 Unreferenced,
465}
466
467impl ToSql for KeyLifeCycle {
468 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
469 match self {
470 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
471 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
472 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
473 }
474 }
475}
476
477impl FromSql for KeyLifeCycle {
478 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
479 match i64::column_result(value)? {
480 0 => Ok(KeyLifeCycle::Existing),
481 1 => Ok(KeyLifeCycle::Live),
482 2 => Ok(KeyLifeCycle::Unreferenced),
483 v => Err(FromSqlError::OutOfRange(v)),
484 }
485 }
486}
487
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700488/// Keys have a KeyMint blob component and optional public certificate and
489/// certificate chain components.
490/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
491/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800492#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700493pub struct KeyEntryLoadBits(u32);
494
495impl KeyEntryLoadBits {
496 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
497 pub const NONE: KeyEntryLoadBits = Self(0);
498 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
499 pub const KM: KeyEntryLoadBits = Self(1);
500 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
501 pub const PUBLIC: KeyEntryLoadBits = Self(2);
502 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
503 pub const BOTH: KeyEntryLoadBits = Self(3);
504
505 /// Returns true if this object indicates that the public components shall be loaded.
506 pub const fn load_public(&self) -> bool {
507 self.0 & Self::PUBLIC.0 != 0
508 }
509
510 /// Returns true if the object indicates that the KeyMint component shall be loaded.
511 pub const fn load_km(&self) -> bool {
512 self.0 & Self::KM.0 != 0
513 }
514}
515
Janis Danisevskisaec14592020-11-12 09:41:49 -0800516lazy_static! {
517 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
518}
519
520struct KeyIdLockDb {
521 locked_keys: Mutex<HashSet<i64>>,
522 cond_var: Condvar,
523}
524
525/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
526/// from the database a second time. Most functions manipulating the key blob database
527/// require a KeyIdGuard.
528#[derive(Debug)]
529pub struct KeyIdGuard(i64);
530
531impl KeyIdLockDb {
532 fn new() -> Self {
533 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
534 }
535
536 /// This function blocks until an exclusive lock for the given key entry id can
537 /// be acquired. It returns a guard object, that represents the lifecycle of the
538 /// acquired lock.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000539 fn get(&self, key_id: i64) -> KeyIdGuard {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800540 let mut locked_keys = self.locked_keys.lock().unwrap();
541 while locked_keys.contains(&key_id) {
542 locked_keys = self.cond_var.wait(locked_keys).unwrap();
543 }
544 locked_keys.insert(key_id);
545 KeyIdGuard(key_id)
546 }
547
548 /// This function attempts to acquire an exclusive lock on a given key id. If the
549 /// given key id is already taken the function returns None immediately. If a lock
550 /// can be acquired this function returns a guard object, that represents the
551 /// lifecycle of the acquired lock.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000552 fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800553 let mut locked_keys = self.locked_keys.lock().unwrap();
554 if locked_keys.insert(key_id) {
555 Some(KeyIdGuard(key_id))
556 } else {
557 None
558 }
559 }
560}
561
562impl KeyIdGuard {
563 /// Get the numeric key id of the locked key.
564 pub fn id(&self) -> i64 {
565 self.0
566 }
567}
568
569impl Drop for KeyIdGuard {
570 fn drop(&mut self) {
571 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
572 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800573 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800574 KEY_ID_LOCK.cond_var.notify_all();
575 }
576}
577
Max Bires8e93d2b2021-01-14 13:17:59 -0800578/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700579#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800580pub struct CertificateInfo {
581 cert: Option<Vec<u8>>,
582 cert_chain: Option<Vec<u8>>,
583}
584
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800585/// This type represents a Blob with its metadata and an optional superseded blob.
586#[derive(Debug)]
587pub struct BlobInfo<'a> {
588 blob: &'a [u8],
589 metadata: &'a BlobMetaData,
590 /// Superseded blobs are an artifact of legacy import. In some rare occasions
591 /// the key blob needs to be upgraded during import. In that case two
592 /// blob are imported, the superseded one will have to be imported first,
593 /// so that the garbage collector can reap it.
594 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
595}
596
597impl<'a> BlobInfo<'a> {
598 /// Create a new instance of blob info with blob and corresponding metadata
599 /// and no superseded blob info.
600 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
601 Self { blob, metadata, superseded_blob: None }
602 }
603
604 /// Create a new instance of blob info with blob and corresponding metadata
605 /// as well as superseded blob info.
606 pub fn new_with_superseded(
607 blob: &'a [u8],
608 metadata: &'a BlobMetaData,
609 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
610 ) -> Self {
611 Self { blob, metadata, superseded_blob }
612 }
613}
614
Max Bires8e93d2b2021-01-14 13:17:59 -0800615impl CertificateInfo {
616 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
617 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
618 Self { cert, cert_chain }
619 }
620
621 /// Take the cert
622 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
623 self.cert.take()
624 }
625
626 /// Take the cert chain
627 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
628 self.cert_chain.take()
629 }
630}
631
Max Bires2b2e6562020-09-22 11:22:36 -0700632/// This type represents a certificate chain with a private key corresponding to the leaf
633/// 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 -0700634pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800635 /// A KM key blob
636 pub private_key: ZVec,
637 /// A batch cert for private_key
638 pub batch_cert: Vec<u8>,
639 /// A full certificate chain from root signing authority to private_key, including batch_cert
640 /// for convenience.
641 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700642}
643
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700644/// This type represents a Keystore 2.0 key entry.
645/// An entry has a unique `id` by which it can be found in the database.
646/// It has a security level field, key parameters, and three optional fields
647/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800648#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700649pub struct KeyEntry {
650 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800651 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700652 cert: Option<Vec<u8>>,
653 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800654 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700655 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800656 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800657 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700658}
659
660impl KeyEntry {
661 /// Returns the unique id of the Key entry.
662 pub fn id(&self) -> i64 {
663 self.id
664 }
665 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800666 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
667 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700668 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800669 /// Extracts the Optional KeyMint blob including its metadata.
670 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
671 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700672 }
673 /// Exposes the optional public certificate.
674 pub fn cert(&self) -> &Option<Vec<u8>> {
675 &self.cert
676 }
677 /// Extracts the optional public certificate.
678 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
679 self.cert.take()
680 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681 /// Extracts the optional public certificate_chain.
682 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
683 self.cert_chain.take()
684 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800685 /// Returns the uuid of the owning KeyMint instance.
686 pub fn km_uuid(&self) -> &Uuid {
687 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700689 /// Consumes this key entry and extracts the keyparameters from it.
690 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
691 self.parameters
692 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800693 /// Exposes the key metadata of this key entry.
694 pub fn metadata(&self) -> &KeyMetaData {
695 &self.metadata
696 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800697 /// This returns true if the entry is a pure certificate entry with no
698 /// private key component.
699 pub fn pure_cert(&self) -> bool {
700 self.pure_cert
701 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700702}
703
704/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800705#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700706pub struct SubComponentType(u32);
707impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800708 /// Persistent identifier for a key blob.
709 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700710 /// Persistent identifier for a certificate blob.
711 pub const CERT: SubComponentType = Self(1);
712 /// Persistent identifier for a certificate chain blob.
713 pub const CERT_CHAIN: SubComponentType = Self(2);
714}
715
716impl ToSql for SubComponentType {
717 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
718 self.0.to_sql()
719 }
720}
721
722impl FromSql for SubComponentType {
723 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
724 Ok(Self(u32::column_result(value)?))
725 }
726}
727
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800728/// This trait is private to the database module. It is used to convey whether or not the garbage
729/// collector shall be invoked after a database access. All closures passed to
730/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
731/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
732/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
733/// `.need_gc()`.
734trait DoGc<T> {
735 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
736
737 fn no_gc(self) -> Result<(bool, T)>;
738
739 fn need_gc(self) -> Result<(bool, T)>;
740}
741
742impl<T> DoGc<T> for Result<T> {
743 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
744 self.map(|r| (need_gc, r))
745 }
746
747 fn no_gc(self) -> Result<(bool, T)> {
748 self.do_gc(false)
749 }
750
751 fn need_gc(self) -> Result<(bool, T)> {
752 self.do_gc(true)
753 }
754}
755
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700756/// KeystoreDB wraps a connection to an SQLite database and tracks its
757/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700758pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700759 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700760 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700761 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700762}
763
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000764/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000765/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000766#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000767pub struct BootTime(i64);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000768
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000769impl BootTime {
770 /// Constructs a new BootTime
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000771 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000772 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000773 }
774
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000775 /// Returns the value of BootTime in milliseconds as i64
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000776 pub fn milliseconds(&self) -> i64 {
777 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000778 }
779
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000780 /// Returns the integer value of BootTime as i64
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000781 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000782 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000783 }
784
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800785 /// Like i64::checked_sub.
786 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
787 self.0.checked_sub(other.0).map(Self)
788 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000789}
790
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000791impl ToSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000792 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
793 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
794 }
795}
796
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000797impl FromSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000798 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
799 Ok(Self(i64::column_result(value)?))
800 }
801}
802
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000803/// This struct encapsulates the information to be stored in the database about the auth tokens
804/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700805#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000806pub struct AuthTokenEntry {
807 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000808 // Time received in milliseconds
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000809 time_received: BootTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000810}
811
812impl AuthTokenEntry {
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000813 fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000814 AuthTokenEntry { auth_token, time_received }
815 }
816
817 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800818 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000819 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800820 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000821 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822 })
823 }
824
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000825 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800826 pub fn auth_token(&self) -> &HardwareAuthToken {
827 &self.auth_token
828 }
829
830 /// Returns the auth token wrapped by the AuthTokenEntry
831 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000832 self.auth_token
833 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800834
835 /// Returns the time that this auth token was received.
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000836 pub fn time_received(&self) -> BootTime {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800837 self.time_received
838 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000839
840 /// Returns the challenge value of the auth token.
841 pub fn challenge(&self) -> i64 {
842 self.auth_token.challenge
843 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000844}
845
Joel Galenson26f4d012020-07-17 14:57:21 -0700846impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800847 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700848 const CURRENT_DB_VERSION: u32 = 1;
849 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800850
Seth Moore78c091f2021-04-09 21:38:30 +0000851 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700852 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000853
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700854 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800855 /// files persistent.sqlite and perboot.sqlite in the given directory.
856 /// It also attempts to initialize all of the tables.
857 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700858 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700859 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700860 let _wp = wd::watch_millis("KeystoreDB::new", 500);
861
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700862 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700863 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800864
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700865 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800866 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700867 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000868 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800869 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 })?;
871 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700872 }
873
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700874 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
875 // cryptographic binding to the boot level keys was implemented.
876 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
877 tx.execute(
878 "UPDATE persistent.keyentry SET state = ?
879 WHERE
880 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
881 AND
882 id NOT IN (
883 SELECT keyentryid FROM persistent.blobentry
884 WHERE id IN (
885 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
886 )
887 );",
888 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
889 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000890 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700891 Ok(1)
892 }
893
Janis Danisevskis66784c42021-01-27 08:40:25 -0800894 fn init_tables(tx: &Transaction) -> Result<()> {
895 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700896 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700897 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800898 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700899 domain INTEGER,
900 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800901 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800902 state INTEGER,
903 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000904 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700905 )
906 .context("Failed to initialize \"keyentry\" table.")?;
907
Janis Danisevskis66784c42021-01-27 08:40:25 -0800908 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800909 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
910 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000911 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800912 )
913 .context("Failed to create index keyentry_id_index.")?;
914
915 tx.execute(
916 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
917 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000918 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800919 )
920 .context("Failed to create index keyentry_domain_namespace_index.")?;
921
922 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700923 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
924 id INTEGER PRIMARY KEY,
925 subcomponent_type INTEGER,
926 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800927 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000928 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700929 )
930 .context("Failed to initialize \"blobentry\" table.")?;
931
Janis Danisevskis66784c42021-01-27 08:40:25 -0800932 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800933 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
934 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000935 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800936 )
937 .context("Failed to create index blobentry_keyentryid_index.")?;
938
939 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800940 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
941 id INTEGER PRIMARY KEY,
942 blobentryid INTEGER,
943 tag INTEGER,
944 data ANY,
945 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000946 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800947 )
948 .context("Failed to initialize \"blobmetadata\" table.")?;
949
950 tx.execute(
951 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
952 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000953 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800954 )
955 .context("Failed to create index blobmetadata_blobentryid_index.")?;
956
957 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700958 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000959 keyentryid INTEGER,
960 tag INTEGER,
961 data ANY,
962 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000963 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700964 )
965 .context("Failed to initialize \"keyparameter\" table.")?;
966
Janis Danisevskis66784c42021-01-27 08:40:25 -0800967 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800968 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
969 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000970 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800971 )
972 .context("Failed to create index keyparameter_keyentryid_index.")?;
973
974 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800975 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
976 keyentryid INTEGER,
977 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000978 data ANY,
979 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000980 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800981 )
982 .context("Failed to initialize \"keymetadata\" 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.keymetadata_keyentryid_index
986 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000987 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800988 )
989 .context("Failed to create index keymetadata_keyentryid_index.")?;
990
991 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800992 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700993 id INTEGER UNIQUE,
994 grantee INTEGER,
995 keyentryid INTEGER,
996 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000997 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700998 )
999 .context("Failed to initialize \"grant\" table.")?;
1000
Joel Galenson0891bc12020-07-20 10:37:03 -07001001 Ok(())
1002 }
1003
Seth Moore472fcbb2021-05-12 10:07:51 -07001004 fn make_persistent_path(db_root: &Path) -> Result<String> {
1005 // Build the path to the sqlite file.
1006 let mut persistent_path = db_root.to_path_buf();
1007 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1008
1009 // Now convert them to strings prefixed with "file:"
1010 let mut persistent_path_str = "file:".to_owned();
1011 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1012
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001013 // Connect to database in specific mode
1014 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1015 "?journal_mode=WAL".to_owned()
1016 } else {
1017 "?journal_mode=DELETE".to_owned()
1018 };
1019 persistent_path_str.push_str(&persistent_path_mode);
1020
Seth Moore472fcbb2021-05-12 10:07:51 -07001021 Ok(persistent_path_str)
1022 }
1023
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001024 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001025 let conn =
1026 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1027
Janis Danisevskis66784c42021-01-27 08:40:25 -08001028 loop {
1029 if let Err(e) = conn
1030 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1031 .context("Failed to attach database persistent.")
1032 {
1033 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001034 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001035 continue;
1036 } else {
1037 return Err(e);
1038 }
1039 }
1040 break;
1041 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001042
Matthew Maurer4fb19112021-05-06 15:40:44 -07001043 // Drop the cache size from default (2M) to 0.5M
1044 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1045 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001046
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047 Ok(conn)
1048 }
1049
Seth Moore78c091f2021-04-09 21:38:30 +00001050 fn do_table_size_query(
1051 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001052 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001053 query: &str,
1054 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001055 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001056 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001057 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001058 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001059 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001060 })
1061 .no_gc()
1062 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001063 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001064 }
1065
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001066 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001067 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001068 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001069 "SELECT page_count * page_size, freelist_count * page_size
1070 FROM pragma_page_count('persistent'),
1071 pragma_page_size('persistent'),
1072 persistent.pragma_freelist_count();",
1073 &[],
1074 )
1075 }
1076
1077 fn get_table_size(
1078 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001079 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001080 schema: &str,
1081 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001082 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001083 self.do_table_size_query(
1084 storage_type,
1085 "SELECT pgsize,unused FROM dbstat(?1)
1086 WHERE name=?2 AND aggregate=TRUE;",
1087 &[schema, table],
1088 )
1089 }
1090
1091 /// Fetches a storage statisitics atom for a given storage type. For storage
1092 /// types that map to a table, information about the table's storage is
1093 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001094 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001095 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1096
Seth Moore78c091f2021-04-09 21:38:30 +00001097 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001098 MetricsStorage::DATABASE => self.get_total_size(),
1099 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001100 self.get_table_size(storage_type, "persistent", "keyentry")
1101 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001102 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001103 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1104 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001105 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001106 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1107 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001108 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001109 self.get_table_size(storage_type, "persistent", "blobentry")
1110 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001111 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001112 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1113 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001114 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001115 self.get_table_size(storage_type, "persistent", "keyparameter")
1116 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001117 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001118 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1119 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001120 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001121 self.get_table_size(storage_type, "persistent", "keymetadata")
1122 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001123 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001124 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1125 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001126 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1127 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001128 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1129 // reportable
1130 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001131 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001132 storage_type,
1133 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001134 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001135 unused_size: 0,
1136 })
Seth Moore78c091f2021-04-09 21:38:30 +00001137 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001138 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001139 self.get_table_size(storage_type, "persistent", "blobmetadata")
1140 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001141 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001142 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1143 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001144 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001145 }
1146 }
1147
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001148 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001149 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1150 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001151 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1152 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001153 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001154 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001155 blob_ids_to_delete: &[i64],
1156 max_blobs: usize,
1157 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001158 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001159 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 // Delete the given blobs.
1161 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001162 tx.execute(
1163 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001164 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001165 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001166 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001167 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001168 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001169 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001170
1171 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1172
Janis Danisevskis3395f862021-05-06 10:54:17 -07001173 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1174 let result: Vec<(i64, Vec<u8>)> = {
1175 let mut stmt = tx
1176 .prepare(
1177 "SELECT id, blob FROM persistent.blobentry
1178 WHERE subcomponent_type = ?
1179 AND (
1180 id NOT IN (
1181 SELECT MAX(id) FROM persistent.blobentry
1182 WHERE subcomponent_type = ?
1183 GROUP BY keyentryid, subcomponent_type
1184 )
1185 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1186 ) LIMIT ?;",
1187 )
1188 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001189
Janis Danisevskis3395f862021-05-06 10:54:17 -07001190 let rows = stmt
1191 .query_map(
1192 params![
1193 SubComponentType::KEY_BLOB,
1194 SubComponentType::KEY_BLOB,
1195 max_blobs as i64,
1196 ],
1197 |row| Ok((row.get(0)?, row.get(1)?)),
1198 )
1199 .context("Trying to query superseded blob.")?;
1200
1201 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1202 .context("Trying to extract superseded blobs.")?
1203 };
1204
1205 let result = result
1206 .into_iter()
1207 .map(|(blob_id, blob)| {
1208 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1209 })
1210 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1211 .context("Trying to load blob metadata.")?;
1212 if !result.is_empty() {
1213 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001214 }
1215
1216 // We did not find any superseded key blob, so let's remove other superseded blob in
1217 // one transaction.
1218 tx.execute(
1219 "DELETE FROM persistent.blobentry
1220 WHERE NOT subcomponent_type = ?
1221 AND (
1222 id NOT IN (
1223 SELECT MAX(id) FROM persistent.blobentry
1224 WHERE NOT subcomponent_type = ?
1225 GROUP BY keyentryid, subcomponent_type
1226 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1227 );",
1228 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1229 )
1230 .context("Trying to purge superseded blobs.")?;
1231
Janis Danisevskis3395f862021-05-06 10:54:17 -07001232 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001233 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001234 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001235 }
1236
1237 /// This maintenance function should be called only once before the database is used for the
1238 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1239 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1240 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1241 /// Keystore crashed at some point during key generation. Callers may want to log such
1242 /// occurrences.
1243 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1244 /// it to `KeyLifeCycle::Live` may have grants.
1245 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001246 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1247
Janis Danisevskis66784c42021-01-27 08:40:25 -08001248 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1249 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001250 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1251 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1252 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001254 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001255 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001256 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001257 }
1258
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001259 /// Checks if a key exists with given key type and key descriptor properties.
1260 pub fn key_exists(
1261 &mut self,
1262 domain: Domain,
1263 nspace: i64,
1264 alias: &str,
1265 key_type: KeyType,
1266 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001267 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1268
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001269 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1270 let key_descriptor =
1271 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001272 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001273 match result {
1274 Ok(_) => Ok(true),
1275 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1276 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001277 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001278 },
1279 }
1280 .no_gc()
1281 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001282 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001283 }
1284
Hasini Gunasingheda895552021-01-27 19:34:37 +00001285 /// Stores a super key in the database.
1286 pub fn store_super_key(
1287 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001288 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001289 key_type: &SuperKeyType,
1290 blob: &[u8],
1291 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001292 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001293 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001294 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1295
Hasini Gunasingheda895552021-01-27 19:34:37 +00001296 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1297 let key_id = Self::insert_with_retry(|id| {
1298 tx.execute(
1299 "INSERT into persistent.keyentry
1300 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001301 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001302 params![
1303 id,
1304 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001305 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001306 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001307 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001308 KeyLifeCycle::Live,
1309 &KEYSTORE_UUID,
1310 ],
1311 )
1312 })
1313 .context("Failed to insert into keyentry table.")?;
1314
Paul Crowley8d5b2532021-03-19 10:53:07 -07001315 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1316
Hasini Gunasingheda895552021-01-27 19:34:37 +00001317 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001318 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001319 key_id,
1320 SubComponentType::KEY_BLOB,
1321 Some(blob),
1322 Some(blob_metadata),
1323 )
1324 .context("Failed to store key blob.")?;
1325
1326 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1327 .context("Trying to load key components.")
1328 .no_gc()
1329 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001330 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001331 }
1332
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001333 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001334 pub fn load_super_key(
1335 &mut self,
1336 key_type: &SuperKeyType,
1337 user_id: u32,
1338 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001339 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1340
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001341 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1342 let key_descriptor = KeyDescriptor {
1343 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001344 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001345 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 blob: None,
1347 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001348 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001349 match id {
1350 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001351 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001352 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001353 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1354 }
1355 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1356 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001357 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001358 },
1359 }
1360 .no_gc()
1361 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001362 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001363 }
1364
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001365 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001366 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1367 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001368 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1369 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001370 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001371 {
David Drysdale115c4722024-04-15 14:11:52 +01001372 self.with_transaction_timeout(behavior, MAX_DB_BUSY_RETRY_PERIOD, f)
1373 }
1374 fn with_transaction_timeout<T, F>(
1375 &mut self,
1376 behavior: TransactionBehavior,
1377 timeout: Duration,
1378 f: F,
1379 ) -> Result<T>
1380 where
1381 F: Fn(&Transaction) -> Result<(bool, T)>,
1382 {
1383 let start = std::time::Instant::now();
Janis Danisevskis66784c42021-01-27 08:40:25 -08001384 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001385 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001386 .conn
1387 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001388 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001389 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1390 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001391 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001392 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001393 });
1394 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001395 Ok(result) => break Ok(result),
1396 Err(e) => {
1397 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001398 check_lock_timeout(&start, timeout)?;
1399 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 continue;
1401 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001402 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001403 }
1404 }
1405 }
1406 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001407 .map(|(need_gc, result)| {
1408 if need_gc {
1409 if let Some(ref gc) = self.gc {
1410 gc.notify_gc();
1411 }
1412 }
1413 result
1414 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001415 }
1416
1417 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001418 matches!(
1419 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1420 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1421 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1422 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001423 }
1424
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001425 fn create_key_entry_internal(
1426 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001427 domain: &Domain,
1428 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001429 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001430 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001431 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001432 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001433 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001434 _ => {
1435 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001436 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001437 }
1438 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001439 Ok(KEY_ID_LOCK.get(
1440 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001441 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001442 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001443 (id, key_type, domain, namespace, alias, state, km_uuid)
1444 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001445 params![
1446 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001447 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001448 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001449 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001450 KeyLifeCycle::Existing,
1451 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001452 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001453 )
1454 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001455 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001456 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001457 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001458
Janis Danisevskis377d1002021-01-27 19:07:48 -08001459 /// Set a new blob and associates it with the given key id. Each blob
1460 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001461 /// Each key can have one of each sub component type associated. If more
1462 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001463 /// will get garbage collected.
1464 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1465 /// removed by setting blob to None.
1466 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001467 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001468 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001469 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001470 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001471 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001472 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001473 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1474
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001475 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001476 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001477 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001478 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001479 }
1480
Janis Danisevskiseed69842021-02-18 20:04:10 -08001481 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1482 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1483 /// We use this to insert key blobs into the database which can then be garbage collected
1484 /// lazily by the key garbage collector.
1485 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001486 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1487
Janis Danisevskiseed69842021-02-18 20:04:10 -08001488 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1489 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001490 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001491 Self::UNASSIGNED_KEY_ID,
1492 SubComponentType::KEY_BLOB,
1493 Some(blob),
1494 Some(blob_metadata),
1495 )
1496 .need_gc()
1497 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001498 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001499 }
1500
Janis Danisevskis377d1002021-01-27 19:07:48 -08001501 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001502 tx: &Transaction,
1503 key_id: i64,
1504 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001505 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001506 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001507 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001508 match (blob, sc_type) {
1509 (Some(blob), _) => {
1510 tx.execute(
1511 "INSERT INTO persistent.blobentry
1512 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1513 params![sc_type, key_id, blob],
1514 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001515 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001516 if let Some(blob_metadata) = blob_metadata {
1517 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001518 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001519 row.get(0)
1520 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001521 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001522 blob_metadata
1523 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001524 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001525 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001526 }
1527 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1528 tx.execute(
1529 "DELETE FROM persistent.blobentry
1530 WHERE subcomponent_type = ? AND keyentryid = ?;",
1531 params![sc_type, key_id],
1532 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001533 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001534 }
1535 (None, _) => {
1536 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001537 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001538 }
1539 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001540 Ok(())
1541 }
1542
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001543 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1544 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001545 #[cfg(test)]
1546 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001547 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001548 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001550 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001551 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001552
Janis Danisevskis66784c42021-01-27 08:40:25 -08001553 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001554 tx: &Transaction,
1555 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001556 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001557 ) -> Result<()> {
1558 let mut stmt = tx
1559 .prepare(
1560 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1561 VALUES (?, ?, ?, ?);",
1562 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001563 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001564
Janis Danisevskis66784c42021-01-27 08:40:25 -08001565 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001566 stmt.insert(params![
1567 key_id.0,
1568 p.get_tag().0,
1569 p.key_parameter_value(),
1570 p.security_level().0
1571 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001572 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001573 }
1574 Ok(())
1575 }
1576
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001577 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001578 #[cfg(test)]
1579 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001580 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001581 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001582 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001583 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001584 }
1585
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001586 /// Updates the alias column of the given key id `newid` with the given alias,
1587 /// and atomically, removes the alias, domain, and namespace from another row
1588 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001589 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1590 /// collector.
1591 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001592 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001593 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001594 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001595 domain: &Domain,
1596 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001597 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001598 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001599 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001600 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001601 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001602 return Err(KsError::sys())
1603 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001604 }
1605 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001606 let updated = tx
1607 .execute(
1608 "UPDATE persistent.keyentry
1609 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001610 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1611 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001612 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001613 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001614 let result = tx
1615 .execute(
1616 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001617 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001618 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001619 params![
1620 alias,
1621 KeyLifeCycle::Live,
1622 newid.0,
1623 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001624 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001625 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001626 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001627 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001628 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001629 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001630 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001631 return Err(KsError::sys()).context(ks_err!(
1632 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001633 result
1634 ));
1635 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001636 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001637 }
1638
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001639 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1640 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1641 pub fn migrate_key_namespace(
1642 &mut self,
1643 key_id_guard: KeyIdGuard,
1644 destination: &KeyDescriptor,
1645 caller_uid: u32,
1646 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1647 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001648 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1649
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001650 let destination = match destination.domain {
1651 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1652 Domain::SELINUX => (*destination).clone(),
1653 domain => {
1654 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1655 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1656 }
1657 };
1658
1659 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001660 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001661
1662 let alias = destination
1663 .alias
1664 .as_ref()
1665 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001666 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001667
1668 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1669 // Query the destination location. If there is a key, the migration request fails.
1670 if tx
1671 .query_row(
1672 "SELECT id FROM persistent.keyentry
1673 WHERE alias = ? AND domain = ? AND namespace = ?;",
1674 params![alias, destination.domain.0, destination.nspace],
1675 |_| Ok(()),
1676 )
1677 .optional()
1678 .context("Failed to query destination.")?
1679 .is_some()
1680 {
1681 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1682 .context("Target already exists.");
1683 }
1684
1685 let updated = tx
1686 .execute(
1687 "UPDATE persistent.keyentry
1688 SET alias = ?, domain = ?, namespace = ?
1689 WHERE id = ?;",
1690 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1691 )
1692 .context("Failed to update key entry.")?;
1693
1694 if updated != 1 {
1695 return Err(KsError::sys())
1696 .context(format!("Update succeeded, but {} rows were updated.", updated));
1697 }
1698 Ok(()).no_gc()
1699 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001700 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001701 }
1702
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001703 /// Store a new key in a single transaction.
1704 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1705 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001706 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1707 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001708 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001709 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001710 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001711 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001712 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001713 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001714 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001715 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001716 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001717 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001718 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001719 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1720
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001721 let (alias, domain, namespace) = match key {
1722 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1723 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1724 (alias, key.domain, nspace)
1725 }
1726 _ => {
1727 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001728 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001729 }
1730 };
1731 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001732 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001734 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1735
1736 // In some occasions the key blob is already upgraded during the import.
1737 // In order to make sure it gets properly deleted it is inserted into the
1738 // database here and then immediately replaced by the superseding blob.
1739 // The garbage collector will then subject the blob to deleteKey of the
1740 // KM back end to permanently invalidate the key.
1741 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1742 Self::set_blob_internal(
1743 tx,
1744 key_id.id(),
1745 SubComponentType::KEY_BLOB,
1746 Some(blob),
1747 Some(blob_metadata),
1748 )
1749 .context("Trying to insert superseded key blob.")?;
1750 true
1751 } else {
1752 false
1753 };
1754
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001755 Self::set_blob_internal(
1756 tx,
1757 key_id.id(),
1758 SubComponentType::KEY_BLOB,
1759 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001760 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001761 )
1762 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001763 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001764 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001765 .context("Trying to insert the certificate.")?;
1766 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001767 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001768 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001769 tx,
1770 key_id.id(),
1771 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001772 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001773 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001774 )
1775 .context("Trying to insert the certificate chain.")?;
1776 }
1777 Self::insert_keyparameter_internal(tx, &key_id, params)
1778 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001779 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001780 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001781 .context("Trying to rebind alias.")?
1782 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001783 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001784 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001785 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001786 }
1787
Janis Danisevskis377d1002021-01-27 19:07:48 -08001788 /// Store a new certificate
1789 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1790 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001791 pub fn store_new_certificate(
1792 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001793 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001794 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001795 cert: &[u8],
1796 km_uuid: &Uuid,
1797 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001798 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1799
Janis Danisevskis377d1002021-01-27 19:07:48 -08001800 let (alias, domain, namespace) = match key {
1801 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1802 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1803 (alias, key.domain, nspace)
1804 }
1805 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001806 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1807 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001808 }
1809 };
1810 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001811 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001812 .context("Trying to create new key entry.")?;
1813
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001814 Self::set_blob_internal(
1815 tx,
1816 key_id.id(),
1817 SubComponentType::CERT_CHAIN,
1818 Some(cert),
1819 None,
1820 )
1821 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001822
1823 let mut metadata = KeyMetaData::new();
1824 metadata.add(KeyMetaEntry::CreationDate(
1825 DateTime::now().context("Trying to make creation time.")?,
1826 ));
1827
1828 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1829
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001830 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001831 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001832 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001833 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001834 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001835 }
1836
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001837 // Helper function loading the key_id given the key descriptor
1838 // tuple comprising domain, namespace, and alias.
1839 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001840 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001841 let alias = key
1842 .alias
1843 .as_ref()
1844 .map_or_else(|| Err(KsError::sys()), Ok)
1845 .context("In load_key_entry_id: Alias must be specified.")?;
1846 let mut stmt = tx
1847 .prepare(
1848 "SELECT id FROM persistent.keyentry
1849 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001850 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001851 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001852 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001853 AND alias = ?
1854 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001855 )
1856 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1857 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001858 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001859 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001860 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001861 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001862 .get(0)
1863 .context("Failed to unpack id.")
1864 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001865 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001866 }
1867
1868 /// This helper function completes the access tuple of a key, which is required
1869 /// to perform access control. The strategy depends on the `domain` field in the
1870 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001871 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001872 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001873 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001874 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001875 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001876 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001877 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001878 /// `namespace`.
1879 /// In each case the information returned is sufficient to perform the access
1880 /// check and the key id can be used to load further key artifacts.
1881 fn load_access_tuple(
1882 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001883 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001884 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001885 caller_uid: u32,
1886 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1887 match key.domain {
1888 // Domain App or SELinux. In this case we load the key_id from
1889 // the keyentry database for further loading of key components.
1890 // We already have the full access tuple to perform access control.
1891 // The only distinction is that we use the caller_uid instead
1892 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001893 // Domain::APP.
1894 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001895 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001896 if access_key.domain == Domain::APP {
1897 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001898 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001899 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001900 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001901
1902 Ok((key_id, access_key, None))
1903 }
1904
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001905 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001906 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001907 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001908 let mut stmt = tx
1909 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001910 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001911 WHERE grantee = ? AND id = ? AND
1912 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001913 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001914 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001915 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001916 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001917 .context("Domain:Grant: query failed.")?;
1918 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001919 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001920 let r =
1921 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001922 Ok((
1923 r.get(0).context("Failed to unpack key_id.")?,
1924 r.get(1).context("Failed to unpack access_vector.")?,
1925 ))
1926 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001927 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001928 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001929 }
1930
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001931 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001932 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001933 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08001934 let (domain, namespace): (Domain, i64) = {
1935 let mut stmt = tx
1936 .prepare(
1937 "SELECT domain, namespace FROM persistent.keyentry
1938 WHERE
1939 id = ?
1940 AND state = ?;",
1941 )
1942 .context("Domain::KEY_ID: prepare statement failed")?;
1943 let mut rows = stmt
1944 .query(params![key.nspace, KeyLifeCycle::Live])
1945 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001946 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001947 let r =
1948 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001949 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001950 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001951 r.get(1).context("Failed to unpack namespace.")?,
1952 ))
1953 })
Janis Danisevskis45760022021-01-19 16:34:10 -08001954 .context("Domain::KEY_ID.")?
1955 };
1956
1957 // We may use a key by id after loading it by grant.
1958 // In this case we have to check if the caller has a grant for this particular
1959 // key. We can skip this if we already know that the caller is the owner.
1960 // But we cannot know this if domain is anything but App. E.g. in the case
1961 // of Domain::SELINUX we have to speculatively check for grants because we have to
1962 // consult the SEPolicy before we know if the caller is the owner.
1963 let access_vector: Option<KeyPermSet> =
1964 if domain != Domain::APP || namespace != caller_uid as i64 {
1965 let access_vector: Option<i32> = tx
1966 .query_row(
1967 "SELECT access_vector FROM persistent.grant
1968 WHERE grantee = ? AND keyentryid = ?;",
1969 params![caller_uid as i64, key.nspace],
1970 |row| row.get(0),
1971 )
1972 .optional()
1973 .context("Domain::KEY_ID: query grant failed.")?;
1974 access_vector.map(|p| p.into())
1975 } else {
1976 None
1977 };
1978
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001979 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001980 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001981 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001982 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001983
Janis Danisevskis45760022021-01-19 16:34:10 -08001984 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001985 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00001986 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001987 }
1988 }
1989
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001990 fn load_blob_components(
1991 key_id: i64,
1992 load_bits: KeyEntryLoadBits,
1993 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001994 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001995 let mut stmt = tx
1996 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001997 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001998 WHERE keyentryid = ? GROUP BY subcomponent_type;",
1999 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002000 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002001
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002002 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002003
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002004 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002005 let mut cert_blob: Option<Vec<u8>> = None;
2006 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002007 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002008 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002009 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002010 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002011 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002012 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2013 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002014 key_blob = Some((
2015 row.get(0).context("Failed to extract key blob id.")?,
2016 row.get(2).context("Failed to extract key blob.")?,
2017 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002018 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002019 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002020 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002021 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002022 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002023 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002024 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002025 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002026 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002027 (SubComponentType::CERT, _, _)
2028 | (SubComponentType::CERT_CHAIN, _, _)
2029 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002030 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2031 }
2032 Ok(())
2033 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002034 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002035
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002036 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2037 Ok(Some((
2038 blob,
2039 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002040 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002041 )))
2042 })?;
2043
2044 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002045 }
2046
2047 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2048 let mut stmt = tx
2049 .prepare(
2050 "SELECT tag, data, security_level from persistent.keyparameter
2051 WHERE keyentryid = ?;",
2052 )
2053 .context("In load_key_parameters: prepare statement failed.")?;
2054
2055 let mut parameters: Vec<KeyParameter> = Vec::new();
2056
2057 let mut rows =
2058 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002059 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002060 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2061 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002062 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002063 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002064 .context("Failed to read KeyParameter.")?,
2065 );
2066 Ok(())
2067 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002068 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002069
2070 Ok(parameters)
2071 }
2072
Qi Wub9433b52020-12-01 14:52:46 +08002073 /// Decrements the usage count of a limited use key. This function first checks whether the
2074 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2075 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2076 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002077 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002078 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2079
Qi Wub9433b52020-12-01 14:52:46 +08002080 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2081 let limit: Option<i32> = tx
2082 .query_row(
2083 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2084 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2085 |row| row.get(0),
2086 )
2087 .optional()
2088 .context("Trying to load usage count")?;
2089
2090 let limit = limit
2091 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2092 .context("The Key no longer exists. Key is exhausted.")?;
2093
2094 tx.execute(
2095 "UPDATE persistent.keyparameter
2096 SET data = data - 1
2097 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2098 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2099 )
2100 .context("Failed to update key usage count.")?;
2101
2102 match limit {
2103 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002104 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002105 .context("Trying to mark limited use key for deletion."),
2106 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002107 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002108 }
2109 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002110 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002111 }
2112
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002113 /// Load a key entry by the given key descriptor.
2114 /// It uses the `check_permission` callback to verify if the access is allowed
2115 /// given the key access tuple read from the database using `load_access_tuple`.
2116 /// With `load_bits` the caller may specify which blobs shall be loaded from
2117 /// the blob database.
2118 pub fn load_key_entry(
2119 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002120 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002121 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002122 load_bits: KeyEntryLoadBits,
2123 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002124 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2125 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002126 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
David Drysdale115c4722024-04-15 14:11:52 +01002127 let start = std::time::Instant::now();
Janis Danisevskis850d4862021-05-05 08:41:14 -07002128
Janis Danisevskis66784c42021-01-27 08:40:25 -08002129 loop {
2130 match self.load_key_entry_internal(
2131 key,
2132 key_type,
2133 load_bits,
2134 caller_uid,
2135 &check_permission,
2136 ) {
2137 Ok(result) => break Ok(result),
2138 Err(e) => {
2139 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01002140 check_lock_timeout(&start, MAX_DB_BUSY_RETRY_PERIOD)?;
2141 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08002142 continue;
2143 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002144 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002145 }
2146 }
2147 }
2148 }
2149 }
2150
2151 fn load_key_entry_internal(
2152 &mut self,
2153 key: &KeyDescriptor,
2154 key_type: KeyType,
2155 load_bits: KeyEntryLoadBits,
2156 caller_uid: u32,
2157 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002158 ) -> Result<(KeyIdGuard, KeyEntry)> {
2159 // KEY ID LOCK 1/2
2160 // If we got a key descriptor with a key id we can get the lock right away.
2161 // Otherwise we have to defer it until we know the key id.
2162 let key_id_guard = match key.domain {
2163 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2164 _ => None,
2165 };
2166
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002167 let tx = self
2168 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002169 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002170 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002171
2172 // Load the key_id and complete the access control tuple.
2173 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002174 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002175
2176 // Perform access control. It is vital that we return here if the permission is denied.
2177 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002178 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002179
Janis Danisevskisaec14592020-11-12 09:41:49 -08002180 // KEY ID LOCK 2/2
2181 // If we did not get a key id lock by now, it was because we got a key descriptor
2182 // without a key id. At this point we got the key id, so we can try and get a lock.
2183 // However, we cannot block here, because we are in the middle of the transaction.
2184 // So first we try to get the lock non blocking. If that fails, we roll back the
2185 // transaction and block until we get the lock. After we successfully got the lock,
2186 // we start a new transaction and load the access tuple again.
2187 //
2188 // We don't need to perform access control again, because we already established
2189 // that the caller had access to the given key. But we need to make sure that the
2190 // key id still exists. So we have to load the key entry by key id this time.
2191 let (key_id_guard, tx) = match key_id_guard {
2192 None => match KEY_ID_LOCK.try_get(key_id) {
2193 None => {
2194 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002195 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002196
Janis Danisevskisaec14592020-11-12 09:41:49 -08002197 // Block until we have a key id lock.
2198 let key_id_guard = KEY_ID_LOCK.get(key_id);
2199
2200 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002201 let tx = self
2202 .conn
2203 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002204 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002205
2206 Self::load_access_tuple(
2207 &tx,
2208 // This time we have to load the key by the retrieved key id, because the
2209 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002210 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002211 domain: Domain::KEY_ID,
2212 nspace: key_id,
2213 ..Default::default()
2214 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002215 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002216 caller_uid,
2217 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002218 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002219 (key_id_guard, tx)
2220 }
2221 Some(l) => (l, tx),
2222 },
2223 Some(key_id_guard) => (key_id_guard, tx),
2224 };
2225
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002226 let key_entry =
2227 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002228
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002229 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002230
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002231 Ok((key_id_guard, key_entry))
2232 }
2233
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002234 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002235 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002236 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2237 .context("Trying to delete keyentry.")?;
2238 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2239 .context("Trying to delete keymetadata.")?;
2240 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2241 .context("Trying to delete keyparameters.")?;
2242 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2243 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002244 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002245 }
2246
2247 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002248 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002249 pub fn unbind_key(
2250 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002251 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002252 key_type: KeyType,
2253 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002254 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002255 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002256 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2257
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002258 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2259 let (key_id, access_key_descriptor, access_vector) =
2260 Self::load_access_tuple(tx, key, key_type, caller_uid)
2261 .context("Trying to get access tuple.")?;
2262
2263 // Perform access control. It is vital that we return here if the permission is denied.
2264 // So do not touch that '?' at the end.
2265 check_permission(&access_key_descriptor, access_vector)
2266 .context("While checking permission.")?;
2267
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002268 Self::mark_unreferenced(tx, key_id)
2269 .map(|need_gc| (need_gc, ()))
2270 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002272 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 }
2274
Max Bires8e93d2b2021-01-14 13:17:59 -08002275 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2276 tx.query_row(
2277 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2278 params![key_id],
2279 |row| row.get(0),
2280 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002281 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002282 }
2283
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002284 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2285 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2286 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002287 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2288
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002289 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002290 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002291 }
2292 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2293 tx.execute(
2294 "DELETE FROM persistent.keymetadata
2295 WHERE keyentryid IN (
2296 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002297 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002298 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002299 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002300 )
2301 .context("Trying to delete keymetadata.")?;
2302 tx.execute(
2303 "DELETE FROM persistent.keyparameter
2304 WHERE keyentryid IN (
2305 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002306 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002307 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002308 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002309 )
2310 .context("Trying to delete keyparameters.")?;
2311 tx.execute(
2312 "DELETE FROM persistent.grant
2313 WHERE keyentryid IN (
2314 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002315 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002316 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002317 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002318 )
2319 .context("Trying to delete grants.")?;
2320 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002321 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002322 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2323 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002324 )
2325 .context("Trying to delete keyentry.")?;
2326 Ok(()).need_gc()
2327 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002328 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002329 }
2330
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002331 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2332 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2333 {
2334 tx.execute(
2335 "DELETE FROM persistent.keymetadata
2336 WHERE keyentryid IN (
2337 SELECT id FROM persistent.keyentry
2338 WHERE state = ?
2339 );",
2340 params![KeyLifeCycle::Unreferenced],
2341 )
2342 .context("Trying to delete keymetadata.")?;
2343 tx.execute(
2344 "DELETE FROM persistent.keyparameter
2345 WHERE keyentryid IN (
2346 SELECT id FROM persistent.keyentry
2347 WHERE state = ?
2348 );",
2349 params![KeyLifeCycle::Unreferenced],
2350 )
2351 .context("Trying to delete keyparameters.")?;
2352 tx.execute(
2353 "DELETE FROM persistent.grant
2354 WHERE keyentryid IN (
2355 SELECT id FROM persistent.keyentry
2356 WHERE state = ?
2357 );",
2358 params![KeyLifeCycle::Unreferenced],
2359 )
2360 .context("Trying to delete grants.")?;
2361 tx.execute(
2362 "DELETE FROM persistent.keyentry
2363 WHERE state = ?;",
2364 params![KeyLifeCycle::Unreferenced],
2365 )
2366 .context("Trying to delete keyentry.")?;
2367 Result::<()>::Ok(())
2368 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002369 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002370 }
2371
Hasini Gunasingheda895552021-01-27 19:34:37 +00002372 /// Delete the keys created on behalf of the user, denoted by the user id.
2373 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2374 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2375 /// The caller of this function should notify the gc if the returned value is true.
2376 pub fn unbind_keys_for_user(
2377 &mut self,
2378 user_id: u32,
2379 keep_non_super_encrypted_keys: bool,
2380 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002381 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2382
Hasini Gunasingheda895552021-01-27 19:34:37 +00002383 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2384 let mut stmt = tx
2385 .prepare(&format!(
2386 "SELECT id from persistent.keyentry
2387 WHERE (
2388 key_type = ?
2389 AND domain = ?
2390 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2391 AND state = ?
2392 ) OR (
2393 key_type = ?
2394 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002395 AND state = ?
2396 );",
2397 aid_user_offset = AID_USER_OFFSET
2398 ))
2399 .context(concat!(
2400 "In unbind_keys_for_user. ",
2401 "Failed to prepare the query to find the keys created by apps."
2402 ))?;
2403
2404 let mut rows = stmt
2405 .query(params![
2406 // WHERE client key:
2407 KeyType::Client,
2408 Domain::APP.0 as u32,
2409 user_id,
2410 KeyLifeCycle::Live,
2411 // OR super key:
2412 KeyType::Super,
2413 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002414 KeyLifeCycle::Live
2415 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002416 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002417
2418 let mut key_ids: Vec<i64> = Vec::new();
2419 db_utils::with_rows_extract_all(&mut rows, |row| {
2420 key_ids
2421 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2422 Ok(())
2423 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002424 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002425
2426 let mut notify_gc = false;
2427 for key_id in key_ids {
2428 if keep_non_super_encrypted_keys {
2429 // Load metadata and filter out non-super-encrypted keys.
2430 if let (_, Some((_, blob_metadata)), _, _) =
2431 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002432 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002433 {
2434 if blob_metadata.encrypted_by().is_none() {
2435 continue;
2436 }
2437 }
2438 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002439 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002440 .context("In unbind_keys_for_user.")?
2441 || notify_gc;
2442 }
2443 Ok(()).do_gc(notify_gc)
2444 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002445 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002446 }
2447
Eric Biggersb0478cf2023-10-27 03:55:29 +00002448 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2449 /// This runs when the user's lock screen is being changed to Swipe or None.
2450 ///
2451 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2452 /// such keys also require user authentication. Keystore's concept of user authentication is
2453 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2454 /// authentication is no longer possible. In contrast, keys that just require that the device
2455 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2456 /// is always considered "unlocked" in that case.
2457 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2458 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2459
2460 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2461 let mut stmt = tx
2462 .prepare(&format!(
2463 "SELECT id from persistent.keyentry
2464 WHERE key_type = ?
2465 AND domain = ?
2466 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2467 AND state = ?;",
2468 aid_user_offset = AID_USER_OFFSET
2469 ))
2470 .context(concat!(
2471 "In unbind_auth_bound_keys_for_user. ",
2472 "Failed to prepare the query to find the keys created by apps."
2473 ))?;
2474
2475 let mut rows = stmt
2476 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2477 .context(ks_err!("Failed to query the keys created by apps."))?;
2478
2479 let mut key_ids: Vec<i64> = Vec::new();
2480 db_utils::with_rows_extract_all(&mut rows, |row| {
2481 key_ids
2482 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2483 Ok(())
2484 })
2485 .context(ks_err!())?;
2486
2487 let mut notify_gc = false;
2488 let mut num_unbound = 0;
2489 for key_id in key_ids {
2490 // Load the key parameters and filter out non-auth-bound keys. To identify
2491 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2492 // could also be used, but UserSecureID is what Keystore treats as authoritative
2493 // when actually enforcing the key parameters (it might not matter, though).
2494 let params = Self::load_key_parameters(key_id, tx)
2495 .context("Failed to load key parameters.")?;
2496 let is_auth_bound_key = params.iter().any(|kp| {
2497 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2498 });
2499 if is_auth_bound_key {
2500 notify_gc = Self::mark_unreferenced(tx, key_id)
2501 .context("In unbind_auth_bound_keys_for_user.")?
2502 || notify_gc;
2503 num_unbound += 1;
2504 }
2505 }
2506 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2507 Ok(()).do_gc(notify_gc)
2508 })
2509 .context(ks_err!())
2510 }
2511
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002512 fn load_key_components(
2513 tx: &Transaction,
2514 load_bits: KeyEntryLoadBits,
2515 key_id: i64,
2516 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002517 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002518
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002519 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002520 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002521
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002522 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002523 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002524
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002525 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002526 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002527
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002528 Ok(KeyEntry {
2529 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002530 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002531 cert: cert_blob,
2532 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002533 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002534 parameters,
2535 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002536 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002537 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002538 }
2539
Eran Messeri24f31972023-01-25 17:00:33 +00002540 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2541 /// aliases are greater than the specified 'start_past_alias'. If no value
2542 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002543 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002544 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002545 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002546 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002547 &mut self,
2548 domain: Domain,
2549 namespace: i64,
2550 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002551 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002552 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002553 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002554
Eran Messeri24f31972023-01-25 17:00:33 +00002555 let query = format!(
2556 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002557 WHERE domain = ?
2558 AND namespace = ?
2559 AND alias IS NOT NULL
2560 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002561 AND key_type = ?
2562 {}
2563 ORDER BY alias ASC;",
2564 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2565 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002566
Eran Messeri24f31972023-01-25 17:00:33 +00002567 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2568 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2569
2570 let mut rows = match start_past_alias {
2571 Some(past_alias) => stmt
2572 .query(params![
2573 domain.0 as u32,
2574 namespace,
2575 KeyLifeCycle::Live,
2576 key_type,
2577 past_alias
2578 ])
2579 .context(ks_err!("Failed to query."))?,
2580 None => stmt
2581 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2582 .context(ks_err!("Failed to query."))?,
2583 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002584
Janis Danisevskis66784c42021-01-27 08:40:25 -08002585 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2586 db_utils::with_rows_extract_all(&mut rows, |row| {
2587 descriptors.push(KeyDescriptor {
2588 domain,
2589 nspace: namespace,
2590 alias: Some(row.get(0).context("Trying to extract alias.")?),
2591 blob: None,
2592 });
2593 Ok(())
2594 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002595 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002596 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002597 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002598 }
2599
Eran Messeri24f31972023-01-25 17:00:33 +00002600 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2601 /// Domain must be APP or SELINUX, the caller must make sure of that.
2602 pub fn count_keys(
2603 &mut self,
2604 domain: Domain,
2605 namespace: i64,
2606 key_type: KeyType,
2607 ) -> Result<usize> {
2608 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2609
2610 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2611 tx.query_row(
2612 "SELECT COUNT(alias) FROM persistent.keyentry
2613 WHERE domain = ?
2614 AND namespace = ?
2615 AND alias IS NOT NULL
2616 AND state = ?
2617 AND key_type = ?;",
2618 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2619 |row| row.get(0),
2620 )
2621 .context(ks_err!("Failed to count number of keys."))
2622 .no_gc()
2623 })?;
2624 Ok(num_keys)
2625 }
2626
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002627 /// Adds a grant to the grant table.
2628 /// Like `load_key_entry` this function loads the access tuple before
2629 /// it uses the callback for a permission check. Upon success,
2630 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2631 /// grant table. The new row will have a randomized id, which is used as
2632 /// grant id in the namespace field of the resulting KeyDescriptor.
2633 pub fn grant(
2634 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002635 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002636 caller_uid: u32,
2637 grantee_uid: u32,
2638 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002639 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002640 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002641 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2642
Janis Danisevskis66784c42021-01-27 08:40:25 -08002643 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2644 // Load the key_id and complete the access control tuple.
2645 // We ignore the access vector here because grants cannot be granted.
2646 // The access vector returned here expresses the permissions the
2647 // grantee has if key.domain == Domain::GRANT. But this vector
2648 // cannot include the grant permission by design, so there is no way the
2649 // subsequent permission check can pass.
2650 // We could check key.domain == Domain::GRANT and fail early.
2651 // But even if we load the access tuple by grant here, the permission
2652 // check denies the attempt to create a grant by grant descriptor.
2653 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002654 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002655
Janis Danisevskis66784c42021-01-27 08:40:25 -08002656 // Perform access control. It is vital that we return here if the permission
2657 // was denied. So do not touch that '?' at the end of the line.
2658 // This permission check checks if the caller has the grant permission
2659 // for the given key and in addition to all of the permissions
2660 // expressed in `access_vector`.
2661 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002662 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002663
Janis Danisevskis66784c42021-01-27 08:40:25 -08002664 let grant_id = if let Some(grant_id) = tx
2665 .query_row(
2666 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002667 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002668 params![key_id, grantee_uid],
2669 |row| row.get(0),
2670 )
2671 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002672 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002673 {
2674 tx.execute(
2675 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002676 SET access_vector = ?
2677 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002678 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002679 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002680 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002681 grant_id
2682 } else {
2683 Self::insert_with_retry(|id| {
2684 tx.execute(
2685 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2686 VALUES (?, ?, ?, ?);",
2687 params![id, grantee_uid, key_id, i32::from(access_vector)],
2688 )
2689 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002690 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002691 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002692
Janis Danisevskis66784c42021-01-27 08:40:25 -08002693 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002694 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002695 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002696 }
2697
2698 /// This function checks permissions like `grant` and `load_key_entry`
2699 /// before removing a grant from the grant table.
2700 pub fn ungrant(
2701 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002702 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002703 caller_uid: u32,
2704 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002705 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002706 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002707 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2708
Janis Danisevskis66784c42021-01-27 08:40:25 -08002709 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2710 // Load the key_id and complete the access control tuple.
2711 // We ignore the access vector here because grants cannot be granted.
2712 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002713 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002714
Janis Danisevskis66784c42021-01-27 08:40:25 -08002715 // Perform access control. We must return here if the permission
2716 // was denied. So do not touch the '?' at the end of this line.
2717 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002718 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002719
Janis Danisevskis66784c42021-01-27 08:40:25 -08002720 tx.execute(
2721 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002722 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002723 params![key_id, grantee_uid],
2724 )
2725 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002726
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002727 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002728 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002729 }
2730
Joel Galenson845f74b2020-09-09 14:11:55 -07002731 // Generates a random id and passes it to the given function, which will
2732 // try to insert it into a database. If that insertion fails, retry;
2733 // otherwise return the id.
2734 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2735 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002736 let newid: i64 = match random() {
2737 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2738 i => i,
2739 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002740 match inserter(newid) {
2741 // If the id already existed, try again.
2742 Err(rusqlite::Error::SqliteFailure(
2743 libsqlite3_sys::Error {
2744 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2745 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2746 },
2747 _,
2748 )) => (),
2749 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002750 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002751 }
2752 _ => return Ok(newid),
2753 }
2754 }
2755 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002756
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002757 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2758 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002759 self.perboot
2760 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002761 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002762
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002763 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002764 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002765 where
2766 F: Fn(&AuthTokenEntry) -> bool,
2767 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002768 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002769 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002770
2771 /// Load descriptor of a key by key id
2772 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2773 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2774
2775 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2776 tx.query_row(
2777 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2778 params![key_id],
2779 |row| {
2780 Ok(KeyDescriptor {
2781 domain: Domain(row.get(0)?),
2782 nspace: row.get(1)?,
2783 alias: row.get(2)?,
2784 blob: None,
2785 })
2786 },
2787 )
2788 .optional()
2789 .context("Trying to load key descriptor")
2790 .no_gc()
2791 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002792 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002793 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002794
2795 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2796 /// (for the given user_id).
2797 /// This is helpful for finding out which apps will have their keys invalidated when
2798 /// the user changes biometrics enrollment or removes their LSKF.
2799 pub fn get_app_uids_affected_by_sid(
2800 &mut self,
2801 user_id: i32,
2802 secure_user_id: i64,
2803 ) -> Result<Vec<i64>> {
2804 let _wp = wd::watch_millis("KeystoreDB::get_app_uids_affected_by_sid", 500);
2805
2806 let key_ids_and_app_uids = self.with_transaction(TransactionBehavior::Immediate, |tx| {
2807 let mut stmt = tx
2808 .prepare(&format!(
2809 "SELECT id, namespace from persistent.keyentry
2810 WHERE key_type = ?
2811 AND domain = ?
2812 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2813 AND state = ?;",
2814 ))
2815 .context(concat!(
2816 "In get_app_uids_affected_by_sid, ",
2817 "failed to prepare the query to find the keys created by apps."
2818 ))?;
2819
2820 let mut rows = stmt
2821 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2822 .context(ks_err!("Failed to query the keys created by apps."))?;
2823
2824 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2825 db_utils::with_rows_extract_all(&mut rows, |row| {
2826 key_ids_and_app_uids.insert(
2827 row.get(0).context("Failed to read key id of a key created by an app.")?,
2828 row.get(1).context("Failed to read the app uid")?,
2829 );
2830 Ok(())
2831 })?;
2832 Ok(key_ids_and_app_uids).no_gc()
2833 })?;
2834 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
2835 for (key_id, app_uid) in key_ids_and_app_uids {
2836 // Read the key parameters for each key in its own transaction. It is OK to ignore
2837 // an error to get the properties of a particular key since it might have been deleted
2838 // under our feet after the previous transaction concluded. If the key was deleted
2839 // then it is no longer applicable if it was auth-bound or not.
2840 if let Ok(is_key_bound_to_sid) =
2841 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2842 let params = Self::load_key_parameters(key_id, tx)
2843 .context("Failed to load key parameters.")?;
2844 // Check if the key is bound to this secure user ID.
2845 let is_key_bound_to_sid = params.iter().any(|kp| {
2846 matches!(
2847 kp.key_parameter_value(),
2848 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2849 )
2850 });
2851 Ok(is_key_bound_to_sid).no_gc()
2852 })
2853 {
2854 if is_key_bound_to_sid {
2855 app_uids_affected_by_sid.insert(app_uid);
2856 }
2857 }
2858 }
2859
2860 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2861 Ok(app_uids_vec)
2862 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002863}
2864
2865#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002866pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002867
2868 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002869 use crate::key_parameter::{
2870 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2871 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2872 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002873 use crate::key_perm_set;
2874 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002875 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002876 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002877 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2878 HardwareAuthToken::HardwareAuthToken,
2879 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002880 };
2881 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002882 Timestamp::Timestamp,
2883 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002884 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07002885 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002886 use std::collections::BTreeMap;
2887 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002888 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002889 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002890 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002891 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002892 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002893 #[cfg(disabled)]
2894 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002895
Seth Moore7ee79f92021-12-07 11:42:49 -08002896 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002897 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002898
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002899 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002900 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002901 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002902 })?;
2903 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002904 }
2905
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002906 fn rebind_alias(
2907 db: &mut KeystoreDB,
2908 newid: &KeyIdGuard,
2909 alias: &str,
2910 domain: Domain,
2911 namespace: i64,
2912 ) -> Result<bool> {
2913 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002914 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002915 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002916 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002917 }
2918
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002919 #[test]
2920 fn datetime() -> Result<()> {
2921 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002922 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002923 let now = SystemTime::now();
2924 let duration = Duration::from_secs(1000);
2925 let then = now.checked_sub(duration).unwrap();
2926 let soon = now.checked_add(duration).unwrap();
2927 conn.execute(
2928 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2929 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2930 )?;
2931 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002932 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002933 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2934 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2935 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2936 assert!(rows.next()?.is_none());
2937 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2938 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2939 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2940 Ok(())
2941 }
2942
Joel Galenson0891bc12020-07-20 10:37:03 -07002943 // Ensure that we're using the "injected" random function, not the real one.
2944 #[test]
2945 fn test_mocked_random() {
2946 let rand1 = random();
2947 let rand2 = random();
2948 let rand3 = random();
2949 if rand1 == rand2 {
2950 assert_eq!(rand2 + 1, rand3);
2951 } else {
2952 assert_eq!(rand1 + 1, rand2);
2953 assert_eq!(rand2, rand3);
2954 }
2955 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002956
Joel Galenson26f4d012020-07-17 14:57:21 -07002957 // Test that we have the correct tables.
2958 #[test]
2959 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002960 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002961 let tables = db
2962 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002963 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002964 .query_map(params![], |row| row.get(0))?
2965 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002966 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002967 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002968 assert_eq!(tables[1], "blobmetadata");
2969 assert_eq!(tables[2], "grant");
2970 assert_eq!(tables[3], "keyentry");
2971 assert_eq!(tables[4], "keymetadata");
2972 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07002973 Ok(())
2974 }
2975
2976 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002977 fn test_auth_token_table_invariant() -> Result<()> {
2978 let mut db = new_test_db()?;
2979 let auth_token1 = HardwareAuthToken {
2980 challenge: i64::MAX,
2981 userId: 200,
2982 authenticatorId: 200,
2983 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2984 timestamp: Timestamp { milliSeconds: 500 },
2985 mac: String::from("mac").into_bytes(),
2986 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002987 db.insert_auth_token(&auth_token1);
2988 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002989 assert_eq!(auth_tokens_returned.len(), 1);
2990
2991 // insert another auth token with the same values for the columns in the UNIQUE constraint
2992 // of the auth token table and different value for timestamp
2993 let auth_token2 = HardwareAuthToken {
2994 challenge: i64::MAX,
2995 userId: 200,
2996 authenticatorId: 200,
2997 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2998 timestamp: Timestamp { milliSeconds: 600 },
2999 mac: String::from("mac").into_bytes(),
3000 };
3001
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003002 db.insert_auth_token(&auth_token2);
3003 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003004 assert_eq!(auth_tokens_returned.len(), 1);
3005
3006 if let Some(auth_token) = auth_tokens_returned.pop() {
3007 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3008 }
3009
3010 // insert another auth token with the different values for the columns in the UNIQUE
3011 // constraint of the auth token table
3012 let auth_token3 = HardwareAuthToken {
3013 challenge: i64::MAX,
3014 userId: 201,
3015 authenticatorId: 200,
3016 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3017 timestamp: Timestamp { milliSeconds: 600 },
3018 mac: String::from("mac").into_bytes(),
3019 };
3020
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003021 db.insert_auth_token(&auth_token3);
3022 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003023 assert_eq!(auth_tokens_returned.len(), 2);
3024
3025 Ok(())
3026 }
3027
3028 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003029 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3030 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003031 }
3032
David Drysdale8c4c4f32023-10-31 12:14:11 +00003033 fn create_key_entry(
3034 db: &mut KeystoreDB,
3035 domain: &Domain,
3036 namespace: &i64,
3037 key_type: KeyType,
3038 km_uuid: &Uuid,
3039 ) -> Result<KeyIdGuard> {
3040 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3041 KeystoreDB::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
3042 })
3043 }
3044
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003045 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003046 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003047 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003048 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003049
David Drysdale8c4c4f32023-10-31 12:14:11 +00003050 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003051 let entries = get_keyentry(&db)?;
3052 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003053
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003054 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003055
3056 let entries_new = get_keyentry(&db)?;
3057 assert_eq!(entries, entries_new);
3058 Ok(())
3059 }
3060
3061 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003062 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003063 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3064 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003065 }
3066
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003067 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003068
David Drysdale8c4c4f32023-10-31 12:14:11 +00003069 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3070 create_key_entry(&mut db, &Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003071
3072 let entries = get_keyentry(&db)?;
3073 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003074 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3075 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003076
3077 // Test that we must pass in a valid Domain.
3078 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003079 create_key_entry(&mut db, &Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003080 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003081 );
3082 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003083 create_key_entry(&mut db, &Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003084 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003085 );
3086 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003087 create_key_entry(&mut db, &Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003088 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003089 );
3090
3091 Ok(())
3092 }
3093
Joel Galenson33c04ad2020-08-03 11:04:38 -07003094 #[test]
3095 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003096 fn extractor(
3097 ke: &KeyEntryRow,
3098 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3099 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003100 }
3101
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003102 let mut db = new_test_db()?;
David Drysdale8c4c4f32023-10-31 12:14:11 +00003103 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3104 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003105 let entries = get_keyentry(&db)?;
3106 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003107 assert_eq!(
3108 extractor(&entries[0]),
3109 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3110 );
3111 assert_eq!(
3112 extractor(&entries[1]),
3113 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3114 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003115
3116 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003117 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003118 let entries = get_keyentry(&db)?;
3119 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003120 assert_eq!(
3121 extractor(&entries[0]),
3122 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3123 );
3124 assert_eq!(
3125 extractor(&entries[1]),
3126 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3127 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003128
3129 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003130 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003131 let entries = get_keyentry(&db)?;
3132 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003133 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3134 assert_eq!(
3135 extractor(&entries[1]),
3136 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3137 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003138
3139 // Test that we must pass in a valid Domain.
3140 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003141 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003142 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003143 );
3144 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003145 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003146 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003147 );
3148 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003149 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003150 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003151 );
3152
3153 // Test that we correctly handle setting an alias for something that does not exist.
3154 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003155 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003156 "Expected to update a single entry but instead updated 0",
3157 );
3158 // Test that we correctly abort the transaction in this case.
3159 let entries = get_keyentry(&db)?;
3160 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003161 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3162 assert_eq!(
3163 extractor(&entries[1]),
3164 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3165 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003166
3167 Ok(())
3168 }
3169
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003170 #[test]
3171 fn test_grant_ungrant() -> Result<()> {
3172 const CALLER_UID: u32 = 15;
3173 const GRANTEE_UID: u32 = 12;
3174 const SELINUX_NAMESPACE: i64 = 7;
3175
3176 let mut db = new_test_db()?;
3177 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003178 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3179 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3180 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003181 )?;
3182 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003183 domain: super::Domain::APP,
3184 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003185 alias: Some("key".to_string()),
3186 blob: None,
3187 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003188 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3189 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003190
3191 // Reset totally predictable random number generator in case we
3192 // are not the first test running on this thread.
3193 reset_random();
3194 let next_random = 0i64;
3195
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003196 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003197 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003198 assert_eq!(*a, PVEC1);
3199 assert_eq!(
3200 *k,
3201 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003202 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003203 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003204 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003205 alias: Some("key".to_string()),
3206 blob: None,
3207 }
3208 );
3209 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003210 })
3211 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003212
3213 assert_eq!(
3214 app_granted_key,
3215 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003216 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003217 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003218 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003219 alias: None,
3220 blob: None,
3221 }
3222 );
3223
3224 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003225 domain: super::Domain::SELINUX,
3226 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003227 alias: Some("yek".to_string()),
3228 blob: None,
3229 };
3230
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003231 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003232 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003233 assert_eq!(*a, PVEC1);
3234 assert_eq!(
3235 *k,
3236 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003237 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003238 // namespace must be the supplied SELinux
3239 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003240 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003241 alias: Some("yek".to_string()),
3242 blob: None,
3243 }
3244 );
3245 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003246 })
3247 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003248
3249 assert_eq!(
3250 selinux_granted_key,
3251 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003252 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003253 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003254 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003255 alias: None,
3256 blob: None,
3257 }
3258 );
3259
3260 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003261 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003262 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003263 assert_eq!(*a, PVEC2);
3264 assert_eq!(
3265 *k,
3266 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003267 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003268 // namespace must be the supplied SELinux
3269 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003270 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003271 alias: Some("yek".to_string()),
3272 blob: None,
3273 }
3274 );
3275 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003276 })
3277 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003278
3279 assert_eq!(
3280 selinux_granted_key,
3281 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003282 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003283 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003284 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003285 alias: None,
3286 blob: None,
3287 }
3288 );
3289
3290 {
3291 // Limiting scope of stmt, because it borrows db.
3292 let mut stmt = db
3293 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003294 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003295 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3296 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3297 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003298
3299 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003300 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003301 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003302 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303 assert!(rows.next().is_none());
3304 }
3305
3306 debug_dump_keyentry_table(&mut db)?;
3307 println!("app_key {:?}", app_key);
3308 println!("selinux_key {:?}", selinux_key);
3309
Janis Danisevskis66784c42021-01-27 08:40:25 -08003310 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3311 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003312
3313 Ok(())
3314 }
3315
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003316 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003317 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3318 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3319
3320 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003321 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003322 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003323 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003324 let mut blob_metadata = BlobMetaData::new();
3325 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3326 db.set_blob(
3327 &key_id,
3328 SubComponentType::KEY_BLOB,
3329 Some(TEST_KEY_BLOB),
3330 Some(&blob_metadata),
3331 )?;
3332 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3333 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003334 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003335
3336 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003337 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003338 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003339 )?;
3340 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003341 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003342 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003343 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003344 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003345 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003346 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003347 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003348 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003349 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003350
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003351 drop(rows);
3352 drop(stmt);
3353
3354 assert_eq!(
3355 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3356 BlobMetaData::load_from_db(id, tx).no_gc()
3357 })
3358 .expect("Should find blob metadata."),
3359 blob_metadata
3360 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003361 Ok(())
3362 }
3363
3364 static TEST_ALIAS: &str = "my super duper key";
3365
3366 #[test]
3367 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3368 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003369 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003370 .context("test_insert_and_load_full_keyentry_domain_app")?
3371 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003372 let (_key_guard, key_entry) = db
3373 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003374 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003375 domain: Domain::APP,
3376 nspace: 0,
3377 alias: Some(TEST_ALIAS.to_string()),
3378 blob: None,
3379 },
3380 KeyType::Client,
3381 KeyEntryLoadBits::BOTH,
3382 1,
3383 |_k, _av| Ok(()),
3384 )
3385 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003386 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003387
3388 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003389 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003390 domain: Domain::APP,
3391 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003392 alias: Some(TEST_ALIAS.to_string()),
3393 blob: None,
3394 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003395 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003396 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003397 |_, _| Ok(()),
3398 )
3399 .unwrap();
3400
3401 assert_eq!(
3402 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3403 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003404 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003405 domain: Domain::APP,
3406 nspace: 0,
3407 alias: Some(TEST_ALIAS.to_string()),
3408 blob: None,
3409 },
3410 KeyType::Client,
3411 KeyEntryLoadBits::NONE,
3412 1,
3413 |_k, _av| Ok(()),
3414 )
3415 .unwrap_err()
3416 .root_cause()
3417 .downcast_ref::<KsError>()
3418 );
3419
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003420 Ok(())
3421 }
3422
3423 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003424 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3425 let mut db = new_test_db()?;
3426
3427 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003428 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003429 domain: Domain::APP,
3430 nspace: 1,
3431 alias: Some(TEST_ALIAS.to_string()),
3432 blob: None,
3433 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003434 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003435 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003436 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003437 )
3438 .expect("Trying to insert cert.");
3439
3440 let (_key_guard, mut key_entry) = db
3441 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003442 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003443 domain: Domain::APP,
3444 nspace: 1,
3445 alias: Some(TEST_ALIAS.to_string()),
3446 blob: None,
3447 },
3448 KeyType::Client,
3449 KeyEntryLoadBits::PUBLIC,
3450 1,
3451 |_k, _av| Ok(()),
3452 )
3453 .expect("Trying to read certificate entry.");
3454
3455 assert!(key_entry.pure_cert());
3456 assert!(key_entry.cert().is_none());
3457 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3458
3459 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003460 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003461 domain: Domain::APP,
3462 nspace: 1,
3463 alias: Some(TEST_ALIAS.to_string()),
3464 blob: None,
3465 },
3466 KeyType::Client,
3467 1,
3468 |_, _| Ok(()),
3469 )
3470 .unwrap();
3471
3472 assert_eq!(
3473 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3474 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003475 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003476 domain: Domain::APP,
3477 nspace: 1,
3478 alias: Some(TEST_ALIAS.to_string()),
3479 blob: None,
3480 },
3481 KeyType::Client,
3482 KeyEntryLoadBits::NONE,
3483 1,
3484 |_k, _av| Ok(()),
3485 )
3486 .unwrap_err()
3487 .root_cause()
3488 .downcast_ref::<KsError>()
3489 );
3490
3491 Ok(())
3492 }
3493
3494 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003495 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3496 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003497 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003498 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3499 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003500 let (_key_guard, key_entry) = db
3501 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003502 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003503 domain: Domain::SELINUX,
3504 nspace: 1,
3505 alias: Some(TEST_ALIAS.to_string()),
3506 blob: None,
3507 },
3508 KeyType::Client,
3509 KeyEntryLoadBits::BOTH,
3510 1,
3511 |_k, _av| Ok(()),
3512 )
3513 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003514 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003515
3516 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003517 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003518 domain: Domain::SELINUX,
3519 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003520 alias: Some(TEST_ALIAS.to_string()),
3521 blob: None,
3522 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003523 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003524 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003525 |_, _| Ok(()),
3526 )
3527 .unwrap();
3528
3529 assert_eq!(
3530 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3531 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003532 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003533 domain: Domain::SELINUX,
3534 nspace: 1,
3535 alias: Some(TEST_ALIAS.to_string()),
3536 blob: None,
3537 },
3538 KeyType::Client,
3539 KeyEntryLoadBits::NONE,
3540 1,
3541 |_k, _av| Ok(()),
3542 )
3543 .unwrap_err()
3544 .root_cause()
3545 .downcast_ref::<KsError>()
3546 );
3547
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003548 Ok(())
3549 }
3550
3551 #[test]
3552 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3553 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003554 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003555 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3556 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003557 let (_, key_entry) = db
3558 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003559 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003560 KeyType::Client,
3561 KeyEntryLoadBits::BOTH,
3562 1,
3563 |_k, _av| Ok(()),
3564 )
3565 .unwrap();
3566
Qi Wub9433b52020-12-01 14:52:46 +08003567 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003568
3569 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003570 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003571 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003572 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003573 |_, _| Ok(()),
3574 )
3575 .unwrap();
3576
3577 assert_eq!(
3578 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3579 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003580 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003581 KeyType::Client,
3582 KeyEntryLoadBits::NONE,
3583 1,
3584 |_k, _av| Ok(()),
3585 )
3586 .unwrap_err()
3587 .root_cause()
3588 .downcast_ref::<KsError>()
3589 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003590
3591 Ok(())
3592 }
3593
3594 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003595 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3596 let mut db = new_test_db()?;
3597 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3598 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3599 .0;
3600 // Update the usage count of the limited use key.
3601 db.check_and_update_key_usage_count(key_id)?;
3602
3603 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003604 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003605 KeyType::Client,
3606 KeyEntryLoadBits::BOTH,
3607 1,
3608 |_k, _av| Ok(()),
3609 )?;
3610
3611 // The usage count is decremented now.
3612 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3613
3614 Ok(())
3615 }
3616
3617 #[test]
3618 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3619 let mut db = new_test_db()?;
3620 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3621 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3622 .0;
3623 // Update the usage count of the limited use key.
3624 db.check_and_update_key_usage_count(key_id).expect(concat!(
3625 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3626 "This should succeed."
3627 ));
3628
3629 // Try to update the exhausted limited use key.
3630 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3631 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3632 "This should fail."
3633 ));
3634 assert_eq!(
3635 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3636 e.root_cause().downcast_ref::<KsError>().unwrap()
3637 );
3638
3639 Ok(())
3640 }
3641
3642 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003643 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3644 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003645 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003646 .context("test_insert_and_load_full_keyentry_from_grant")?
3647 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003648
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003649 let granted_key = db
3650 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003651 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003652 domain: Domain::APP,
3653 nspace: 0,
3654 alias: Some(TEST_ALIAS.to_string()),
3655 blob: None,
3656 },
3657 1,
3658 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003659 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003660 |_k, _av| Ok(()),
3661 )
3662 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003663
3664 debug_dump_grant_table(&mut db)?;
3665
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003666 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003667 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3668 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003669 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003670 Ok(())
3671 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003672 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003673
Qi Wub9433b52020-12-01 14:52:46 +08003674 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003675
Janis Danisevskis66784c42021-01-27 08:40:25 -08003676 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003677
3678 assert_eq!(
3679 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3680 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003681 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003682 KeyType::Client,
3683 KeyEntryLoadBits::NONE,
3684 2,
3685 |_k, _av| Ok(()),
3686 )
3687 .unwrap_err()
3688 .root_cause()
3689 .downcast_ref::<KsError>()
3690 );
3691
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003692 Ok(())
3693 }
3694
Janis Danisevskis45760022021-01-19 16:34:10 -08003695 // This test attempts to load a key by key id while the caller is not the owner
3696 // but a grant exists for the given key and the caller.
3697 #[test]
3698 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3699 let mut db = new_test_db()?;
3700 const OWNER_UID: u32 = 1u32;
3701 const GRANTEE_UID: u32 = 2u32;
3702 const SOMEONE_ELSE_UID: u32 = 3u32;
3703 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3704 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3705 .0;
3706
3707 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003708 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003709 domain: Domain::APP,
3710 nspace: 0,
3711 alias: Some(TEST_ALIAS.to_string()),
3712 blob: None,
3713 },
3714 OWNER_UID,
3715 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003716 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003717 |_k, _av| Ok(()),
3718 )
3719 .unwrap();
3720
3721 debug_dump_grant_table(&mut db)?;
3722
3723 let id_descriptor =
3724 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3725
3726 let (_, key_entry) = db
3727 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003728 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003729 KeyType::Client,
3730 KeyEntryLoadBits::BOTH,
3731 GRANTEE_UID,
3732 |k, av| {
3733 assert_eq!(Domain::APP, k.domain);
3734 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003735 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003736 Ok(())
3737 },
3738 )
3739 .unwrap();
3740
3741 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3742
3743 let (_, key_entry) = db
3744 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003745 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003746 KeyType::Client,
3747 KeyEntryLoadBits::BOTH,
3748 SOMEONE_ELSE_UID,
3749 |k, av| {
3750 assert_eq!(Domain::APP, k.domain);
3751 assert_eq!(OWNER_UID as i64, k.nspace);
3752 assert!(av.is_none());
3753 Ok(())
3754 },
3755 )
3756 .unwrap();
3757
3758 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3759
Janis Danisevskis66784c42021-01-27 08:40:25 -08003760 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003761
3762 assert_eq!(
3763 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3764 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003765 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003766 KeyType::Client,
3767 KeyEntryLoadBits::NONE,
3768 GRANTEE_UID,
3769 |_k, _av| Ok(()),
3770 )
3771 .unwrap_err()
3772 .root_cause()
3773 .downcast_ref::<KsError>()
3774 );
3775
3776 Ok(())
3777 }
3778
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003779 // Creates a key migrates it to a different location and then tries to access it by the old
3780 // and new location.
3781 #[test]
3782 fn test_migrate_key_app_to_app() -> Result<()> {
3783 let mut db = new_test_db()?;
3784 const SOURCE_UID: u32 = 1u32;
3785 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003786 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3787 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003788 let key_id_guard =
3789 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3790 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3791
3792 let source_descriptor: KeyDescriptor = KeyDescriptor {
3793 domain: Domain::APP,
3794 nspace: -1,
3795 alias: Some(SOURCE_ALIAS.to_string()),
3796 blob: None,
3797 };
3798
3799 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3800 domain: Domain::APP,
3801 nspace: -1,
3802 alias: Some(DESTINATION_ALIAS.to_string()),
3803 blob: None,
3804 };
3805
3806 let key_id = key_id_guard.id();
3807
3808 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3809 Ok(())
3810 })
3811 .unwrap();
3812
3813 let (_, key_entry) = db
3814 .load_key_entry(
3815 &destination_descriptor,
3816 KeyType::Client,
3817 KeyEntryLoadBits::BOTH,
3818 DESTINATION_UID,
3819 |k, av| {
3820 assert_eq!(Domain::APP, k.domain);
3821 assert_eq!(DESTINATION_UID as i64, k.nspace);
3822 assert!(av.is_none());
3823 Ok(())
3824 },
3825 )
3826 .unwrap();
3827
3828 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3829
3830 assert_eq!(
3831 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3832 db.load_key_entry(
3833 &source_descriptor,
3834 KeyType::Client,
3835 KeyEntryLoadBits::NONE,
3836 SOURCE_UID,
3837 |_k, _av| Ok(()),
3838 )
3839 .unwrap_err()
3840 .root_cause()
3841 .downcast_ref::<KsError>()
3842 );
3843
3844 Ok(())
3845 }
3846
3847 // Creates a key migrates it to a different location and then tries to access it by the old
3848 // and new location.
3849 #[test]
3850 fn test_migrate_key_app_to_selinux() -> Result<()> {
3851 let mut db = new_test_db()?;
3852 const SOURCE_UID: u32 = 1u32;
3853 const DESTINATION_UID: u32 = 2u32;
3854 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003855 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3856 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003857 let key_id_guard =
3858 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3859 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3860
3861 let source_descriptor: KeyDescriptor = KeyDescriptor {
3862 domain: Domain::APP,
3863 nspace: -1,
3864 alias: Some(SOURCE_ALIAS.to_string()),
3865 blob: None,
3866 };
3867
3868 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3869 domain: Domain::SELINUX,
3870 nspace: DESTINATION_NAMESPACE,
3871 alias: Some(DESTINATION_ALIAS.to_string()),
3872 blob: None,
3873 };
3874
3875 let key_id = key_id_guard.id();
3876
3877 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3878 Ok(())
3879 })
3880 .unwrap();
3881
3882 let (_, key_entry) = db
3883 .load_key_entry(
3884 &destination_descriptor,
3885 KeyType::Client,
3886 KeyEntryLoadBits::BOTH,
3887 DESTINATION_UID,
3888 |k, av| {
3889 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003890 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003891 assert!(av.is_none());
3892 Ok(())
3893 },
3894 )
3895 .unwrap();
3896
3897 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3898
3899 assert_eq!(
3900 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3901 db.load_key_entry(
3902 &source_descriptor,
3903 KeyType::Client,
3904 KeyEntryLoadBits::NONE,
3905 SOURCE_UID,
3906 |_k, _av| Ok(()),
3907 )
3908 .unwrap_err()
3909 .root_cause()
3910 .downcast_ref::<KsError>()
3911 );
3912
3913 Ok(())
3914 }
3915
3916 // Creates two keys and tries to migrate the first to the location of the second which
3917 // is expected to fail.
3918 #[test]
3919 fn test_migrate_key_destination_occupied() -> Result<()> {
3920 let mut db = new_test_db()?;
3921 const SOURCE_UID: u32 = 1u32;
3922 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003923 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3924 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003925 let key_id_guard =
3926 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3927 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3928 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3929 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3930
3931 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3932 domain: Domain::APP,
3933 nspace: -1,
3934 alias: Some(DESTINATION_ALIAS.to_string()),
3935 blob: None,
3936 };
3937
3938 assert_eq!(
3939 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3940 db.migrate_key_namespace(
3941 key_id_guard,
3942 &destination_descriptor,
3943 DESTINATION_UID,
3944 |_k| Ok(())
3945 )
3946 .unwrap_err()
3947 .root_cause()
3948 .downcast_ref::<KsError>()
3949 );
3950
3951 Ok(())
3952 }
3953
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003954 #[test]
3955 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003956 const ALIAS1: &str = "test_upgrade_0_to_1_1";
3957 const ALIAS2: &str = "test_upgrade_0_to_1_2";
3958 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003959 const UID: u32 = 33;
3960 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3961 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3962 let key_id_untouched1 =
3963 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3964 let key_id_untouched2 =
3965 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
3966 let key_id_deleted =
3967 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
3968
3969 let (_, key_entry) = db
3970 .load_key_entry(
3971 &KeyDescriptor {
3972 domain: Domain::APP,
3973 nspace: -1,
3974 alias: Some(ALIAS1.to_string()),
3975 blob: None,
3976 },
3977 KeyType::Client,
3978 KeyEntryLoadBits::BOTH,
3979 UID,
3980 |k, av| {
3981 assert_eq!(Domain::APP, k.domain);
3982 assert_eq!(UID as i64, k.nspace);
3983 assert!(av.is_none());
3984 Ok(())
3985 },
3986 )
3987 .unwrap();
3988 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
3989 let (_, key_entry) = db
3990 .load_key_entry(
3991 &KeyDescriptor {
3992 domain: Domain::APP,
3993 nspace: -1,
3994 alias: Some(ALIAS2.to_string()),
3995 blob: None,
3996 },
3997 KeyType::Client,
3998 KeyEntryLoadBits::BOTH,
3999 UID,
4000 |k, av| {
4001 assert_eq!(Domain::APP, k.domain);
4002 assert_eq!(UID as i64, k.nspace);
4003 assert!(av.is_none());
4004 Ok(())
4005 },
4006 )
4007 .unwrap();
4008 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4009 let (_, key_entry) = db
4010 .load_key_entry(
4011 &KeyDescriptor {
4012 domain: Domain::APP,
4013 nspace: -1,
4014 alias: Some(ALIAS3.to_string()),
4015 blob: None,
4016 },
4017 KeyType::Client,
4018 KeyEntryLoadBits::BOTH,
4019 UID,
4020 |k, av| {
4021 assert_eq!(Domain::APP, k.domain);
4022 assert_eq!(UID as i64, k.nspace);
4023 assert!(av.is_none());
4024 Ok(())
4025 },
4026 )
4027 .unwrap();
4028 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4029
4030 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4031 KeystoreDB::from_0_to_1(tx).no_gc()
4032 })
4033 .unwrap();
4034
4035 let (_, key_entry) = db
4036 .load_key_entry(
4037 &KeyDescriptor {
4038 domain: Domain::APP,
4039 nspace: -1,
4040 alias: Some(ALIAS1.to_string()),
4041 blob: None,
4042 },
4043 KeyType::Client,
4044 KeyEntryLoadBits::BOTH,
4045 UID,
4046 |k, av| {
4047 assert_eq!(Domain::APP, k.domain);
4048 assert_eq!(UID as i64, k.nspace);
4049 assert!(av.is_none());
4050 Ok(())
4051 },
4052 )
4053 .unwrap();
4054 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4055 let (_, key_entry) = db
4056 .load_key_entry(
4057 &KeyDescriptor {
4058 domain: Domain::APP,
4059 nspace: -1,
4060 alias: Some(ALIAS2.to_string()),
4061 blob: None,
4062 },
4063 KeyType::Client,
4064 KeyEntryLoadBits::BOTH,
4065 UID,
4066 |k, av| {
4067 assert_eq!(Domain::APP, k.domain);
4068 assert_eq!(UID as i64, k.nspace);
4069 assert!(av.is_none());
4070 Ok(())
4071 },
4072 )
4073 .unwrap();
4074 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4075 assert_eq!(
4076 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4077 db.load_key_entry(
4078 &KeyDescriptor {
4079 domain: Domain::APP,
4080 nspace: -1,
4081 alias: Some(ALIAS3.to_string()),
4082 blob: None,
4083 },
4084 KeyType::Client,
4085 KeyEntryLoadBits::BOTH,
4086 UID,
4087 |k, av| {
4088 assert_eq!(Domain::APP, k.domain);
4089 assert_eq!(UID as i64, k.nspace);
4090 assert!(av.is_none());
4091 Ok(())
4092 },
4093 )
4094 .unwrap_err()
4095 .root_cause()
4096 .downcast_ref::<KsError>()
4097 );
4098 }
4099
Janis Danisevskisaec14592020-11-12 09:41:49 -08004100 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4101
Janis Danisevskisaec14592020-11-12 09:41:49 -08004102 #[test]
4103 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4104 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004105 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4106 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004107 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004108 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004109 .context("test_insert_and_load_full_keyentry_domain_app")?
4110 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004111 let (_key_guard, key_entry) = db
4112 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004113 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004114 domain: Domain::APP,
4115 nspace: 0,
4116 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4117 blob: None,
4118 },
4119 KeyType::Client,
4120 KeyEntryLoadBits::BOTH,
4121 33,
4122 |_k, _av| Ok(()),
4123 )
4124 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004125 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004126 let state = Arc::new(AtomicU8::new(1));
4127 let state2 = state.clone();
4128
4129 // Spawning a second thread that attempts to acquire the key id lock
4130 // for the same key as the primary thread. The primary thread then
4131 // waits, thereby forcing the secondary thread into the second stage
4132 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4133 // The test succeeds if the secondary thread observes the transition
4134 // of `state` from 1 to 2, despite having a whole second to overtake
4135 // the primary thread.
4136 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004137 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004138 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004139 assert!(db
4140 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004141 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004142 domain: Domain::APP,
4143 nspace: 0,
4144 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4145 blob: None,
4146 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004147 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004148 KeyEntryLoadBits::BOTH,
4149 33,
4150 |_k, _av| Ok(()),
4151 )
4152 .is_ok());
4153 // We should only see a 2 here because we can only return
4154 // from load_key_entry when the `_key_guard` expires,
4155 // which happens at the end of the scope.
4156 assert_eq!(2, state2.load(Ordering::Relaxed));
4157 });
4158
4159 thread::sleep(std::time::Duration::from_millis(1000));
4160
4161 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4162
4163 // Return the handle from this scope so we can join with the
4164 // secondary thread after the key id lock has expired.
4165 handle
4166 // This is where the `_key_guard` goes out of scope,
4167 // which is the reason for concurrent load_key_entry on the same key
4168 // to unblock.
4169 };
4170 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4171 // main test thread. We will not see failing asserts in secondary threads otherwise.
4172 handle.join().unwrap();
4173 Ok(())
4174 }
4175
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004176 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004177 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004178 let temp_dir =
4179 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4180
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004181 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4182 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004183
4184 let _tx1 = db1
4185 .conn
4186 .transaction_with_behavior(TransactionBehavior::Immediate)
4187 .expect("Failed to create first transaction.");
4188
4189 let error = db2
4190 .conn
4191 .transaction_with_behavior(TransactionBehavior::Immediate)
4192 .context("Transaction begin failed.")
4193 .expect_err("This should fail.");
4194 let root_cause = error.root_cause();
4195 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4196 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4197 {
4198 return;
4199 }
4200 panic!(
4201 "Unexpected error {:?} \n{:?} \n{:?}",
4202 error,
4203 root_cause,
4204 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4205 )
4206 }
4207
4208 #[cfg(disabled)]
4209 #[test]
4210 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4211 let temp_dir = Arc::new(
4212 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4213 .expect("Failed to create temp dir."),
4214 );
4215
4216 let test_begin = Instant::now();
4217
Janis Danisevskis66784c42021-01-27 08:40:25 -08004218 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004219 let mut db =
4220 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004221 const OPEN_DB_COUNT: u32 = 50u32;
4222
4223 let mut actual_key_count = KEY_COUNT;
4224 // First insert KEY_COUNT keys.
4225 for count in 0..KEY_COUNT {
4226 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4227 actual_key_count = count;
4228 break;
4229 }
4230 let alias = format!("test_alias_{}", count);
4231 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4232 .expect("Failed to make key entry.");
4233 }
4234
4235 // Insert more keys from a different thread and into a different namespace.
4236 let temp_dir1 = temp_dir.clone();
4237 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004238 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4239 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004240
4241 for count in 0..actual_key_count {
4242 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4243 return;
4244 }
4245 let alias = format!("test_alias_{}", count);
4246 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4247 .expect("Failed to make key entry.");
4248 }
4249
4250 // then unbind them again.
4251 for count in 0..actual_key_count {
4252 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4253 return;
4254 }
4255 let key = KeyDescriptor {
4256 domain: Domain::APP,
4257 nspace: -1,
4258 alias: Some(format!("test_alias_{}", count)),
4259 blob: None,
4260 };
4261 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4262 }
4263 });
4264
4265 // And start unbinding the first set of keys.
4266 let temp_dir2 = temp_dir.clone();
4267 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004268 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4269 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004270
4271 for count in 0..actual_key_count {
4272 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4273 return;
4274 }
4275 let key = KeyDescriptor {
4276 domain: Domain::APP,
4277 nspace: -1,
4278 alias: Some(format!("test_alias_{}", count)),
4279 blob: None,
4280 };
4281 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4282 }
4283 });
4284
Janis Danisevskis66784c42021-01-27 08:40:25 -08004285 // While a lot of inserting and deleting is going on we have to open database connections
4286 // successfully and use them.
4287 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4288 // out of scope.
4289 #[allow(clippy::redundant_clone)]
4290 let temp_dir4 = temp_dir.clone();
4291 let handle4 = thread::spawn(move || {
4292 for count in 0..OPEN_DB_COUNT {
4293 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4294 return;
4295 }
Seth Moore444b51a2021-06-11 09:49:49 -07004296 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4297 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004298
4299 let alias = format!("test_alias_{}", count);
4300 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4301 .expect("Failed to make key entry.");
4302 let key = KeyDescriptor {
4303 domain: Domain::APP,
4304 nspace: -1,
4305 alias: Some(alias),
4306 blob: None,
4307 };
4308 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4309 }
4310 });
4311
4312 handle1.join().expect("Thread 1 panicked.");
4313 handle2.join().expect("Thread 2 panicked.");
4314 handle4.join().expect("Thread 4 panicked.");
4315
Janis Danisevskis66784c42021-01-27 08:40:25 -08004316 Ok(())
4317 }
4318
4319 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004320 fn list() -> Result<()> {
4321 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004322 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004323 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4324 (Domain::APP, 1, "test1"),
4325 (Domain::APP, 1, "test2"),
4326 (Domain::APP, 1, "test3"),
4327 (Domain::APP, 1, "test4"),
4328 (Domain::APP, 1, "test5"),
4329 (Domain::APP, 1, "test6"),
4330 (Domain::APP, 1, "test7"),
4331 (Domain::APP, 2, "test1"),
4332 (Domain::APP, 2, "test2"),
4333 (Domain::APP, 2, "test3"),
4334 (Domain::APP, 2, "test4"),
4335 (Domain::APP, 2, "test5"),
4336 (Domain::APP, 2, "test6"),
4337 (Domain::APP, 2, "test8"),
4338 (Domain::SELINUX, 100, "test1"),
4339 (Domain::SELINUX, 100, "test2"),
4340 (Domain::SELINUX, 100, "test3"),
4341 (Domain::SELINUX, 100, "test4"),
4342 (Domain::SELINUX, 100, "test5"),
4343 (Domain::SELINUX, 100, "test6"),
4344 (Domain::SELINUX, 100, "test9"),
4345 ];
4346
4347 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4348 .iter()
4349 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004350 let entry =
4351 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004352 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4353 });
4354 (entry.id(), *ns)
4355 })
4356 .collect();
4357
4358 for (domain, namespace) in
4359 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4360 {
4361 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4362 .iter()
4363 .filter_map(|(domain, ns, alias)| match ns {
4364 ns if *ns == *namespace => Some(KeyDescriptor {
4365 domain: *domain,
4366 nspace: *ns,
4367 alias: Some(alias.to_string()),
4368 blob: None,
4369 }),
4370 _ => None,
4371 })
4372 .collect();
4373 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004374 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004375 list_result.sort();
4376 assert_eq!(list_o_descriptors, list_result);
4377
4378 let mut list_o_ids: Vec<i64> = list_o_descriptors
4379 .into_iter()
4380 .map(|d| {
4381 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004382 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004383 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004384 KeyType::Client,
4385 KeyEntryLoadBits::NONE,
4386 *namespace as u32,
4387 |_, _| Ok(()),
4388 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004389 .unwrap();
4390 entry.id()
4391 })
4392 .collect();
4393 list_o_ids.sort_unstable();
4394 let mut loaded_entries: Vec<i64> = list_o_keys
4395 .iter()
4396 .filter_map(|(id, ns)| match ns {
4397 ns if *ns == *namespace => Some(*id),
4398 _ => None,
4399 })
4400 .collect();
4401 loaded_entries.sort_unstable();
4402 assert_eq!(list_o_ids, loaded_entries);
4403 }
Eran Messeri24f31972023-01-25 17:00:33 +00004404 assert_eq!(
4405 Vec::<KeyDescriptor>::new(),
4406 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4407 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004408
4409 Ok(())
4410 }
4411
Joel Galenson0891bc12020-07-20 10:37:03 -07004412 // Helpers
4413
4414 // Checks that the given result is an error containing the given string.
4415 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4416 let error_str = format!(
4417 "{:#?}",
4418 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4419 );
4420 assert!(
4421 error_str.contains(target),
4422 "The string \"{}\" should contain \"{}\"",
4423 error_str,
4424 target
4425 );
4426 }
4427
Joel Galenson2aab4432020-07-22 15:27:57 -07004428 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004429 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004430 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004431 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004432 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004433 namespace: Option<i64>,
4434 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004435 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004436 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004437 }
4438
4439 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4440 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004441 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004442 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004443 Ok(KeyEntryRow {
4444 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004445 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004446 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004447 namespace: row.get(3)?,
4448 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004449 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004450 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004451 })
4452 })?
4453 .map(|r| r.context("Could not read keyentry row."))
4454 .collect::<Result<Vec<_>>>()
4455 }
4456
Eran Messeri4dc27b52024-01-09 12:43:31 +00004457 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4458 make_test_params_with_sids(max_usage_count, &[42])
4459 }
4460
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004461 // Note: The parameters and SecurityLevel associations are nonsensical. This
4462 // collection is only used to check if the parameters are preserved as expected by the
4463 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004464 fn make_test_params_with_sids(
4465 max_usage_count: Option<i32>,
4466 user_secure_ids: &[i64],
4467 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004468 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004469 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4470 KeyParameter::new(
4471 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4472 SecurityLevel::TRUSTED_ENVIRONMENT,
4473 ),
4474 KeyParameter::new(
4475 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4476 SecurityLevel::TRUSTED_ENVIRONMENT,
4477 ),
4478 KeyParameter::new(
4479 KeyParameterValue::Algorithm(Algorithm::RSA),
4480 SecurityLevel::TRUSTED_ENVIRONMENT,
4481 ),
4482 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4483 KeyParameter::new(
4484 KeyParameterValue::BlockMode(BlockMode::ECB),
4485 SecurityLevel::TRUSTED_ENVIRONMENT,
4486 ),
4487 KeyParameter::new(
4488 KeyParameterValue::BlockMode(BlockMode::GCM),
4489 SecurityLevel::TRUSTED_ENVIRONMENT,
4490 ),
4491 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4492 KeyParameter::new(
4493 KeyParameterValue::Digest(Digest::MD5),
4494 SecurityLevel::TRUSTED_ENVIRONMENT,
4495 ),
4496 KeyParameter::new(
4497 KeyParameterValue::Digest(Digest::SHA_2_224),
4498 SecurityLevel::TRUSTED_ENVIRONMENT,
4499 ),
4500 KeyParameter::new(
4501 KeyParameterValue::Digest(Digest::SHA_2_256),
4502 SecurityLevel::STRONGBOX,
4503 ),
4504 KeyParameter::new(
4505 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4506 SecurityLevel::TRUSTED_ENVIRONMENT,
4507 ),
4508 KeyParameter::new(
4509 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4510 SecurityLevel::TRUSTED_ENVIRONMENT,
4511 ),
4512 KeyParameter::new(
4513 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4514 SecurityLevel::STRONGBOX,
4515 ),
4516 KeyParameter::new(
4517 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4518 SecurityLevel::TRUSTED_ENVIRONMENT,
4519 ),
4520 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4521 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4522 KeyParameter::new(
4523 KeyParameterValue::EcCurve(EcCurve::P_224),
4524 SecurityLevel::TRUSTED_ENVIRONMENT,
4525 ),
4526 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4527 KeyParameter::new(
4528 KeyParameterValue::EcCurve(EcCurve::P_384),
4529 SecurityLevel::TRUSTED_ENVIRONMENT,
4530 ),
4531 KeyParameter::new(
4532 KeyParameterValue::EcCurve(EcCurve::P_521),
4533 SecurityLevel::TRUSTED_ENVIRONMENT,
4534 ),
4535 KeyParameter::new(
4536 KeyParameterValue::RSAPublicExponent(3),
4537 SecurityLevel::TRUSTED_ENVIRONMENT,
4538 ),
4539 KeyParameter::new(
4540 KeyParameterValue::IncludeUniqueID,
4541 SecurityLevel::TRUSTED_ENVIRONMENT,
4542 ),
4543 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4544 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4545 KeyParameter::new(
4546 KeyParameterValue::ActiveDateTime(1234567890),
4547 SecurityLevel::STRONGBOX,
4548 ),
4549 KeyParameter::new(
4550 KeyParameterValue::OriginationExpireDateTime(1234567890),
4551 SecurityLevel::TRUSTED_ENVIRONMENT,
4552 ),
4553 KeyParameter::new(
4554 KeyParameterValue::UsageExpireDateTime(1234567890),
4555 SecurityLevel::TRUSTED_ENVIRONMENT,
4556 ),
4557 KeyParameter::new(
4558 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4559 SecurityLevel::TRUSTED_ENVIRONMENT,
4560 ),
4561 KeyParameter::new(
4562 KeyParameterValue::MaxUsesPerBoot(1234567890),
4563 SecurityLevel::TRUSTED_ENVIRONMENT,
4564 ),
4565 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004566 KeyParameter::new(
4567 KeyParameterValue::NoAuthRequired,
4568 SecurityLevel::TRUSTED_ENVIRONMENT,
4569 ),
4570 KeyParameter::new(
4571 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4572 SecurityLevel::TRUSTED_ENVIRONMENT,
4573 ),
4574 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4575 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4576 KeyParameter::new(
4577 KeyParameterValue::TrustedUserPresenceRequired,
4578 SecurityLevel::TRUSTED_ENVIRONMENT,
4579 ),
4580 KeyParameter::new(
4581 KeyParameterValue::TrustedConfirmationRequired,
4582 SecurityLevel::TRUSTED_ENVIRONMENT,
4583 ),
4584 KeyParameter::new(
4585 KeyParameterValue::UnlockedDeviceRequired,
4586 SecurityLevel::TRUSTED_ENVIRONMENT,
4587 ),
4588 KeyParameter::new(
4589 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4590 SecurityLevel::SOFTWARE,
4591 ),
4592 KeyParameter::new(
4593 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4594 SecurityLevel::SOFTWARE,
4595 ),
4596 KeyParameter::new(
4597 KeyParameterValue::CreationDateTime(12345677890),
4598 SecurityLevel::SOFTWARE,
4599 ),
4600 KeyParameter::new(
4601 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4602 SecurityLevel::TRUSTED_ENVIRONMENT,
4603 ),
4604 KeyParameter::new(
4605 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4606 SecurityLevel::TRUSTED_ENVIRONMENT,
4607 ),
4608 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4609 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4610 KeyParameter::new(
4611 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4612 SecurityLevel::SOFTWARE,
4613 ),
4614 KeyParameter::new(
4615 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4616 SecurityLevel::TRUSTED_ENVIRONMENT,
4617 ),
4618 KeyParameter::new(
4619 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4620 SecurityLevel::TRUSTED_ENVIRONMENT,
4621 ),
4622 KeyParameter::new(
4623 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4624 SecurityLevel::TRUSTED_ENVIRONMENT,
4625 ),
4626 KeyParameter::new(
4627 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4628 SecurityLevel::TRUSTED_ENVIRONMENT,
4629 ),
4630 KeyParameter::new(
4631 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4632 SecurityLevel::TRUSTED_ENVIRONMENT,
4633 ),
4634 KeyParameter::new(
4635 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4636 SecurityLevel::TRUSTED_ENVIRONMENT,
4637 ),
4638 KeyParameter::new(
4639 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4640 SecurityLevel::TRUSTED_ENVIRONMENT,
4641 ),
4642 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004643 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4644 SecurityLevel::TRUSTED_ENVIRONMENT,
4645 ),
4646 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004647 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4648 SecurityLevel::TRUSTED_ENVIRONMENT,
4649 ),
4650 KeyParameter::new(
4651 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4652 SecurityLevel::TRUSTED_ENVIRONMENT,
4653 ),
4654 KeyParameter::new(
4655 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4656 SecurityLevel::TRUSTED_ENVIRONMENT,
4657 ),
4658 KeyParameter::new(
4659 KeyParameterValue::VendorPatchLevel(3),
4660 SecurityLevel::TRUSTED_ENVIRONMENT,
4661 ),
4662 KeyParameter::new(
4663 KeyParameterValue::BootPatchLevel(4),
4664 SecurityLevel::TRUSTED_ENVIRONMENT,
4665 ),
4666 KeyParameter::new(
4667 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4668 SecurityLevel::TRUSTED_ENVIRONMENT,
4669 ),
4670 KeyParameter::new(
4671 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4672 SecurityLevel::TRUSTED_ENVIRONMENT,
4673 ),
4674 KeyParameter::new(
4675 KeyParameterValue::MacLength(256),
4676 SecurityLevel::TRUSTED_ENVIRONMENT,
4677 ),
4678 KeyParameter::new(
4679 KeyParameterValue::ResetSinceIdRotation,
4680 SecurityLevel::TRUSTED_ENVIRONMENT,
4681 ),
4682 KeyParameter::new(
4683 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4684 SecurityLevel::TRUSTED_ENVIRONMENT,
4685 ),
Qi Wub9433b52020-12-01 14:52:46 +08004686 ];
4687 if let Some(value) = max_usage_count {
4688 params.push(KeyParameter::new(
4689 KeyParameterValue::UsageCountLimit(value),
4690 SecurityLevel::SOFTWARE,
4691 ));
4692 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004693
4694 for sid in user_secure_ids.iter() {
4695 params.push(KeyParameter::new(
4696 KeyParameterValue::UserSecureID(*sid),
4697 SecurityLevel::STRONGBOX,
4698 ));
4699 }
Qi Wub9433b52020-12-01 14:52:46 +08004700 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004701 }
4702
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004703 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004704 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004705 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004706 namespace: i64,
4707 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004708 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004709 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004710 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4711 }
4712
4713 pub fn make_test_key_entry_with_sids(
4714 db: &mut KeystoreDB,
4715 domain: Domain,
4716 namespace: i64,
4717 alias: &str,
4718 max_usage_count: Option<i32>,
4719 sids: &[i64],
4720 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004721 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004722 let mut blob_metadata = BlobMetaData::new();
4723 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4724 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4725 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4726 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4727 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4728
4729 db.set_blob(
4730 &key_id,
4731 SubComponentType::KEY_BLOB,
4732 Some(TEST_KEY_BLOB),
4733 Some(&blob_metadata),
4734 )?;
4735 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4736 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004737
Eran Messeri4dc27b52024-01-09 12:43:31 +00004738 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004739 db.insert_keyparameter(&key_id, &params)?;
4740
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004741 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004742 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004743 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004744 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004745 Ok(key_id)
4746 }
4747
Qi Wub9433b52020-12-01 14:52:46 +08004748 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4749 let params = make_test_params(max_usage_count);
4750
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004751 let mut blob_metadata = BlobMetaData::new();
4752 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4753 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4754 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4755 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4756 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4757
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004758 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004759 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004760
4761 KeyEntry {
4762 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004763 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004764 cert: Some(TEST_CERT_BLOB.to_vec()),
4765 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004766 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004767 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004768 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004769 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004770 }
4771 }
4772
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004773 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004774 db: &mut KeystoreDB,
4775 domain: Domain,
4776 namespace: i64,
4777 alias: &str,
4778 logical_only: bool,
4779 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004780 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004781 let mut blob_metadata = BlobMetaData::new();
4782 if !logical_only {
4783 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4784 }
4785 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4786
4787 db.set_blob(
4788 &key_id,
4789 SubComponentType::KEY_BLOB,
4790 Some(TEST_KEY_BLOB),
4791 Some(&blob_metadata),
4792 )?;
4793 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4794 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4795
4796 let mut params = make_test_params(None);
4797 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4798
4799 db.insert_keyparameter(&key_id, &params)?;
4800
4801 let mut metadata = KeyMetaData::new();
4802 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4803 db.insert_key_metadata(&key_id, &metadata)?;
4804 rebind_alias(db, &key_id, alias, domain, namespace)?;
4805 Ok(key_id)
4806 }
4807
Eric Biggersb0478cf2023-10-27 03:55:29 +00004808 // Creates an app key that is marked as being superencrypted by the given
4809 // super key ID and that has the given authentication and unlocked device
4810 // parameters. This does not actually superencrypt the key blob.
4811 fn make_superencrypted_key_entry(
4812 db: &mut KeystoreDB,
4813 namespace: i64,
4814 alias: &str,
4815 requires_authentication: bool,
4816 requires_unlocked_device: bool,
4817 super_key_id: i64,
4818 ) -> Result<KeyIdGuard> {
4819 let domain = Domain::APP;
David Drysdale8c4c4f32023-10-31 12:14:11 +00004820 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Eric Biggersb0478cf2023-10-27 03:55:29 +00004821
4822 let mut blob_metadata = BlobMetaData::new();
4823 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4824 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4825 db.set_blob(
4826 &key_id,
4827 SubComponentType::KEY_BLOB,
4828 Some(TEST_KEY_BLOB),
4829 Some(&blob_metadata),
4830 )?;
4831
4832 let mut params = vec![];
4833 if requires_unlocked_device {
4834 params.push(KeyParameter::new(
4835 KeyParameterValue::UnlockedDeviceRequired,
4836 SecurityLevel::TRUSTED_ENVIRONMENT,
4837 ));
4838 }
4839 if requires_authentication {
4840 params.push(KeyParameter::new(
4841 KeyParameterValue::UserSecureID(42),
4842 SecurityLevel::TRUSTED_ENVIRONMENT,
4843 ));
4844 }
4845 db.insert_keyparameter(&key_id, &params)?;
4846
4847 let mut metadata = KeyMetaData::new();
4848 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4849 db.insert_key_metadata(&key_id, &metadata)?;
4850
4851 rebind_alias(db, &key_id, alias, domain, namespace)?;
4852 Ok(key_id)
4853 }
4854
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004855 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4856 let mut params = make_test_params(None);
4857 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4858
4859 let mut blob_metadata = BlobMetaData::new();
4860 if !logical_only {
4861 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4862 }
4863 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4864
4865 let mut metadata = KeyMetaData::new();
4866 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4867
4868 KeyEntry {
4869 id: key_id,
4870 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4871 cert: Some(TEST_CERT_BLOB.to_vec()),
4872 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4873 km_uuid: KEYSTORE_UUID,
4874 parameters: params,
4875 metadata,
4876 pure_cert: false,
4877 }
4878 }
4879
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004880 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004881 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004882 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004883 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004884 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004885 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004886 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004887 Ok((
4888 row.get(0)?,
4889 row.get(1)?,
4890 row.get(2)?,
4891 row.get(3)?,
4892 row.get(4)?,
4893 row.get(5)?,
4894 row.get(6)?,
4895 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004896 },
4897 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004898
4899 println!("Key entry table rows:");
4900 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004901 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004902 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004903 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4904 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004905 );
4906 }
4907 Ok(())
4908 }
4909
4910 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004911 let mut stmt = db
4912 .conn
4913 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004914 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004915 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4916 })?;
4917
4918 println!("Grant table rows:");
4919 for r in rows {
4920 let (id, gt, ki, av) = r.unwrap();
4921 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4922 }
4923 Ok(())
4924 }
4925
Joel Galenson0891bc12020-07-20 10:37:03 -07004926 // Use a custom random number generator that repeats each number once.
4927 // This allows us to test repeated elements.
4928
4929 thread_local! {
Charisee43391152024-04-02 16:16:30 +00004930 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07004931 }
4932
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004933 fn reset_random() {
4934 RANDOM_COUNTER.with(|counter| {
4935 *counter.borrow_mut() = 0;
4936 })
4937 }
4938
Joel Galenson0891bc12020-07-20 10:37:03 -07004939 pub fn random() -> i64 {
4940 RANDOM_COUNTER.with(|counter| {
4941 let result = *counter.borrow() / 2;
4942 *counter.borrow_mut() += 1;
4943 result
4944 })
4945 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004946
4947 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00004948 fn test_unbind_keys_for_user() -> Result<()> {
4949 let mut db = new_test_db()?;
4950 db.unbind_keys_for_user(1, false)?;
4951
4952 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4953 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4954 db.unbind_keys_for_user(2, false)?;
4955
Eran Messeri24f31972023-01-25 17:00:33 +00004956 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4957 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004958
4959 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004960 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004961
4962 Ok(())
4963 }
4964
4965 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004966 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4967 let mut db = new_test_db()?;
4968 let super_key = keystore2_crypto::generate_aes256_key()?;
4969 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4970 let (encrypted_super_key, metadata) =
4971 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4972
4973 let key_name_enc = SuperKeyType {
4974 alias: "test_super_key_1",
4975 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004976 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004977 };
4978
4979 let key_name_nonenc = SuperKeyType {
4980 alias: "test_super_key_2",
4981 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004982 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004983 };
4984
4985 // Install two super keys.
4986 db.store_super_key(
4987 1,
4988 &key_name_nonenc,
4989 &super_key,
4990 &BlobMetaData::new(),
4991 &KeyMetaData::new(),
4992 )?;
4993 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4994
4995 // Check that both can be found in the database.
4996 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
4997 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
4998
4999 // Install the same keys for a different user.
5000 db.store_super_key(
5001 2,
5002 &key_name_nonenc,
5003 &super_key,
5004 &BlobMetaData::new(),
5005 &KeyMetaData::new(),
5006 )?;
5007 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5008
5009 // Check that the second pair of keys can be found in the database.
5010 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5011 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5012
5013 // Delete only encrypted keys.
5014 db.unbind_keys_for_user(1, true)?;
5015
5016 // The encrypted superkey should be gone now.
5017 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5018 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5019
5020 // Reinsert the encrypted key.
5021 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5022
5023 // Check that both can be found in the database, again..
5024 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5025 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5026
5027 // Delete all even unencrypted keys.
5028 db.unbind_keys_for_user(1, false)?;
5029
5030 // Both should be gone now.
5031 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5032 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5033
5034 // Check that the second pair of keys was untouched.
5035 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5036 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5037
5038 Ok(())
5039 }
5040
Eric Biggersb0478cf2023-10-27 03:55:29 +00005041 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5042 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5043 }
5044
5045 // Tests the unbind_auth_bound_keys_for_user() function.
5046 #[test]
5047 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5048 let mut db = new_test_db()?;
5049 let user_id = 1;
5050 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5051 let other_user_id = 2;
5052 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5053 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5054
5055 // Create a superencryption key.
5056 let super_key = keystore2_crypto::generate_aes256_key()?;
5057 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5058 let (encrypted_super_key, blob_metadata) =
5059 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5060 db.store_super_key(
5061 user_id,
5062 super_key_type,
5063 &encrypted_super_key,
5064 &blob_metadata,
5065 &KeyMetaData::new(),
5066 )?;
5067 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5068
5069 // Store 4 superencrypted app keys, one for each possible combination of
5070 // (authentication required, unlocked device required).
5071 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5072 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5073 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5074 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5075 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5076 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5077 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5078 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5079
5080 // Also store a key for a different user that requires authentication.
5081 make_superencrypted_key_entry(
5082 &mut db,
5083 other_user_nspace,
5084 "auth_ud",
5085 true,
5086 true,
5087 super_key_id,
5088 )?;
5089
5090 db.unbind_auth_bound_keys_for_user(user_id)?;
5091
5092 // Verify that only the user's app keys that require authentication were
5093 // deleted. Keys that require an unlocked device but not authentication
5094 // should *not* have been deleted, nor should the super key have been
5095 // deleted, nor should other users' keys have been deleted.
5096 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5097 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5098 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5099 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5100 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5101 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5102
5103 Ok(())
5104 }
5105
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005106 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005107 fn test_store_super_key() -> Result<()> {
5108 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005109 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005110 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005111 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005112 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005113 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005114
5115 let (encrypted_super_key, metadata) =
5116 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005117 db.store_super_key(
5118 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005119 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005120 &encrypted_super_key,
5121 &metadata,
5122 &KeyMetaData::new(),
5123 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005124
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005125 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005126 assert!(db.key_exists(
5127 Domain::APP,
5128 1,
5129 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5130 KeyType::Super
5131 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005132
Eric Biggers673d34a2023-10-18 01:54:18 +00005133 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005134 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005135 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005136 key_entry,
5137 &pw,
5138 None,
5139 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005140
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005141 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005142 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005143
Hasini Gunasingheda895552021-01-27 19:34:37 +00005144 Ok(())
5145 }
Seth Moore78c091f2021-04-09 21:38:30 +00005146
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005147 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005148 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005149 MetricsStorage::KEY_ENTRY,
5150 MetricsStorage::KEY_ENTRY_ID_INDEX,
5151 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5152 MetricsStorage::BLOB_ENTRY,
5153 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5154 MetricsStorage::KEY_PARAMETER,
5155 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5156 MetricsStorage::KEY_METADATA,
5157 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5158 MetricsStorage::GRANT,
5159 MetricsStorage::AUTH_TOKEN,
5160 MetricsStorage::BLOB_METADATA,
5161 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005162 ]
5163 }
5164
5165 /// Perform a simple check to ensure that we can query all the storage types
5166 /// that are supported by the DB. Check for reasonable values.
5167 #[test]
5168 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005169 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005170
5171 let mut db = new_test_db()?;
5172
5173 for t in get_valid_statsd_storage_types() {
5174 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005175 // AuthToken can be less than a page since it's in a btree, not sqlite
5176 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005177 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005178 } else {
5179 assert!(stat.size >= PAGE_SIZE);
5180 }
Seth Moore78c091f2021-04-09 21:38:30 +00005181 assert!(stat.size >= stat.unused_size);
5182 }
5183
5184 Ok(())
5185 }
5186
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005187 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005188 get_valid_statsd_storage_types()
5189 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005190 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005191 .collect()
5192 }
5193
5194 fn assert_storage_increased(
5195 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005196 increased_storage_types: Vec<MetricsStorage>,
5197 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005198 ) {
5199 for storage in increased_storage_types {
5200 // Verify the expected storage increased.
5201 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005202 let old = &baseline[&storage.0];
5203 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005204 assert!(
5205 new.unused_size <= old.unused_size,
5206 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005207 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005208 new.unused_size,
5209 old.unused_size
5210 );
5211
5212 // Update the baseline with the new value so that it succeeds in the
5213 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005214 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005215 }
5216
5217 // Get an updated map of the storage and verify there were no unexpected changes.
5218 let updated_stats = get_storage_stats_map(db);
5219 assert_eq!(updated_stats.len(), baseline.len());
5220
5221 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005222 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005223 let mut s = String::new();
5224 for &k in map.keys() {
5225 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5226 .expect("string concat failed");
5227 }
5228 s
5229 };
5230
5231 assert!(
5232 updated_stats[&k].size == baseline[&k].size
5233 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5234 "updated_stats:\n{}\nbaseline:\n{}",
5235 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005236 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005237 );
5238 }
5239 }
5240
5241 #[test]
5242 fn test_verify_key_table_size_reporting() -> Result<()> {
5243 let mut db = new_test_db()?;
5244 let mut working_stats = get_storage_stats_map(&mut db);
5245
David Drysdale8c4c4f32023-10-31 12:14:11 +00005246 let key_id = create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005247 assert_storage_increased(
5248 &mut db,
5249 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005250 MetricsStorage::KEY_ENTRY,
5251 MetricsStorage::KEY_ENTRY_ID_INDEX,
5252 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005253 ],
5254 &mut working_stats,
5255 );
5256
5257 let mut blob_metadata = BlobMetaData::new();
5258 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5259 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5260 assert_storage_increased(
5261 &mut db,
5262 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005263 MetricsStorage::BLOB_ENTRY,
5264 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5265 MetricsStorage::BLOB_METADATA,
5266 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005267 ],
5268 &mut working_stats,
5269 );
5270
5271 let params = make_test_params(None);
5272 db.insert_keyparameter(&key_id, &params)?;
5273 assert_storage_increased(
5274 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005275 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005276 &mut working_stats,
5277 );
5278
5279 let mut metadata = KeyMetaData::new();
5280 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5281 db.insert_key_metadata(&key_id, &metadata)?;
5282 assert_storage_increased(
5283 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005284 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005285 &mut working_stats,
5286 );
5287
5288 let mut sum = 0;
5289 for stat in working_stats.values() {
5290 sum += stat.size;
5291 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005292 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005293 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5294
5295 Ok(())
5296 }
5297
5298 #[test]
5299 fn test_verify_auth_table_size_reporting() -> Result<()> {
5300 let mut db = new_test_db()?;
5301 let mut working_stats = get_storage_stats_map(&mut db);
5302 db.insert_auth_token(&HardwareAuthToken {
5303 challenge: 123,
5304 userId: 456,
5305 authenticatorId: 789,
5306 authenticatorType: kmhw_authenticator_type::ANY,
5307 timestamp: Timestamp { milliSeconds: 10 },
5308 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005309 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005310 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005311 Ok(())
5312 }
5313
5314 #[test]
5315 fn test_verify_grant_table_size_reporting() -> Result<()> {
5316 const OWNER: i64 = 1;
5317 let mut db = new_test_db()?;
5318 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5319
5320 let mut working_stats = get_storage_stats_map(&mut db);
5321 db.grant(
5322 &KeyDescriptor {
5323 domain: Domain::APP,
5324 nspace: 0,
5325 alias: Some(TEST_ALIAS.to_string()),
5326 blob: None,
5327 },
5328 OWNER as u32,
5329 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005330 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005331 |_, _| Ok(()),
5332 )?;
5333
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005334 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005335
5336 Ok(())
5337 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005338
5339 #[test]
5340 fn find_auth_token_entry_returns_latest() -> Result<()> {
5341 let mut db = new_test_db()?;
5342 db.insert_auth_token(&HardwareAuthToken {
5343 challenge: 123,
5344 userId: 456,
5345 authenticatorId: 789,
5346 authenticatorType: kmhw_authenticator_type::ANY,
5347 timestamp: Timestamp { milliSeconds: 10 },
5348 mac: b"mac0".to_vec(),
5349 });
5350 std::thread::sleep(std::time::Duration::from_millis(1));
5351 db.insert_auth_token(&HardwareAuthToken {
5352 challenge: 123,
5353 userId: 457,
5354 authenticatorId: 789,
5355 authenticatorType: kmhw_authenticator_type::ANY,
5356 timestamp: Timestamp { milliSeconds: 12 },
5357 mac: b"mac1".to_vec(),
5358 });
5359 std::thread::sleep(std::time::Duration::from_millis(1));
5360 db.insert_auth_token(&HardwareAuthToken {
5361 challenge: 123,
5362 userId: 458,
5363 authenticatorId: 789,
5364 authenticatorType: kmhw_authenticator_type::ANY,
5365 timestamp: Timestamp { milliSeconds: 3 },
5366 mac: b"mac2".to_vec(),
5367 });
5368 // All three entries are in the database
5369 assert_eq!(db.perboot.auth_tokens_len(), 3);
5370 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005371 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005372 Ok(())
5373 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005374
5375 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005376 fn test_load_key_descriptor() -> Result<()> {
5377 let mut db = new_test_db()?;
5378 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5379
5380 let key = db.load_key_descriptor(key_id)?.unwrap();
5381
5382 assert_eq!(key.domain, Domain::APP);
5383 assert_eq!(key.nspace, 1);
5384 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5385
5386 // No such id
5387 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5388 Ok(())
5389 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005390
5391 #[test]
5392 fn test_get_list_app_uids_for_sid() -> Result<()> {
5393 let uid: i32 = 1;
5394 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5395 let first_sid = 667;
5396 let second_sid = 669;
5397 let first_app_id: i64 = 123 + uid_offset;
5398 let second_app_id: i64 = 456 + uid_offset;
5399 let third_app_id: i64 = 789 + uid_offset;
5400 let unrelated_app_id: i64 = 1011 + uid_offset;
5401 let mut db = new_test_db()?;
5402 make_test_key_entry_with_sids(
5403 &mut db,
5404 Domain::APP,
5405 first_app_id,
5406 TEST_ALIAS,
5407 None,
5408 &[first_sid],
5409 )
5410 .context("test_get_list_app_uids_for_sid")?;
5411 make_test_key_entry_with_sids(
5412 &mut db,
5413 Domain::APP,
5414 second_app_id,
5415 "alias2",
5416 None,
5417 &[first_sid],
5418 )
5419 .context("test_get_list_app_uids_for_sid")?;
5420 make_test_key_entry_with_sids(
5421 &mut db,
5422 Domain::APP,
5423 second_app_id,
5424 TEST_ALIAS,
5425 None,
5426 &[second_sid],
5427 )
5428 .context("test_get_list_app_uids_for_sid")?;
5429 make_test_key_entry_with_sids(
5430 &mut db,
5431 Domain::APP,
5432 third_app_id,
5433 "alias3",
5434 None,
5435 &[second_sid],
5436 )
5437 .context("test_get_list_app_uids_for_sid")?;
5438 make_test_key_entry_with_sids(
5439 &mut db,
5440 Domain::APP,
5441 unrelated_app_id,
5442 TEST_ALIAS,
5443 None,
5444 &[],
5445 )
5446 .context("test_get_list_app_uids_for_sid")?;
5447
5448 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5449 first_sid_apps.sort();
5450 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5451 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5452 second_sid_apps.sort();
5453 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5454 Ok(())
5455 }
5456
5457 #[test]
5458 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5459 let uid: i32 = 1;
5460 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5461 let first_sid = 667;
5462 let second_sid = 669;
5463 let third_sid = 772;
5464 let first_app_id: i64 = 123 + uid_offset;
5465 let second_app_id: i64 = 456 + uid_offset;
5466 let mut db = new_test_db()?;
5467 make_test_key_entry_with_sids(
5468 &mut db,
5469 Domain::APP,
5470 first_app_id,
5471 TEST_ALIAS,
5472 None,
5473 &[first_sid, second_sid],
5474 )
5475 .context("test_get_list_app_uids_for_sid")?;
5476 make_test_key_entry_with_sids(
5477 &mut db,
5478 Domain::APP,
5479 second_app_id,
5480 "alias2",
5481 None,
5482 &[second_sid, third_sid],
5483 )
5484 .context("test_get_list_app_uids_for_sid")?;
5485
5486 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5487 assert_eq!(first_sid_apps, vec![first_app_id]);
5488
5489 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5490 second_sid_apps.sort();
5491 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5492
5493 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5494 assert_eq!(third_sid_apps, vec![second_app_id]);
5495 Ok(())
5496 }
David Drysdale115c4722024-04-15 14:11:52 +01005497
5498 #[test]
5499 fn test_key_id_guard_immediate() -> Result<()> {
5500 if !keystore2_flags::database_loop_timeout() {
5501 eprintln!("Skipping test as loop timeout flag disabled");
5502 return Ok(());
5503 }
5504 // Emit logging from test.
5505 android_logger::init_once(
5506 android_logger::Config::default()
5507 .with_tag("keystore_database_tests")
5508 .with_max_level(log::LevelFilter::Debug),
5509 );
5510
5511 // Preparation: put a single entry into a test DB.
5512 let temp_dir = Arc::new(TempDir::new("key_id_guard_immediate")?);
5513 let temp_dir_clone_a = temp_dir.clone();
5514 let temp_dir_clone_b = temp_dir.clone();
5515 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5516 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5517
5518 let (a_sender, b_receiver) = std::sync::mpsc::channel();
5519 let (b_sender, a_receiver) = std::sync::mpsc::channel();
5520
5521 // First thread starts an immediate transaction, then waits on a synchronization channel
5522 // before trying to get the `KeyIdGuard`.
5523 let handle_a = thread::spawn(move || {
5524 let temp_dir = temp_dir_clone_a;
5525 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
5526
5527 // Make sure the other thread has initialized its database access before we lock it out.
5528 a_receiver.recv().unwrap();
5529
5530 let _result = db.with_transaction_timeout(
5531 TransactionBehavior::Immediate,
5532 Duration::from_secs(3),
5533 |_tx| {
5534 // Notify the other thread that we're inside the immediate transaction...
5535 a_sender.send(()).unwrap();
5536 // ...then wait to be sure that the other thread has the `KeyIdGuard` before
5537 // this thread also tries to get it.
5538 a_receiver.recv().unwrap();
5539
5540 let _guard = KEY_ID_LOCK.get(key_id);
5541 Ok(()).no_gc()
5542 },
5543 );
5544 });
5545
5546 // Second thread gets the `KeyIdGuard`, then waits before trying to perform an immediate
5547 // transaction.
5548 let handle_b = thread::spawn(move || {
5549 let temp_dir = temp_dir_clone_b;
5550 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
5551 // Notify the other thread that we are initialized (so it can lock the immediate
5552 // transaction).
5553 b_sender.send(()).unwrap();
5554
5555 let _guard = KEY_ID_LOCK.get(key_id);
5556 // Notify the other thread that we have the `KeyIdGuard`...
5557 b_sender.send(()).unwrap();
5558 // ...then wait to be sure that the other thread is in the immediate transaction before
5559 // this thread also tries to do one.
5560 b_receiver.recv().unwrap();
5561
5562 let result = db.with_transaction_timeout(
5563 TransactionBehavior::Immediate,
5564 Duration::from_secs(3),
5565 |_tx| Ok(()).no_gc(),
5566 );
5567 // Expect the attempt to get an immediate transaction to fail, and then this thread will
5568 // exit and release the `KeyIdGuard`, allowing the other thread to complete.
5569 assert!(result.is_err());
5570 check_result_is_error_containing_string(result, "BACKEND_BUSY");
5571 });
5572
5573 let _ = handle_a.join();
5574 let _ = handle_b.join();
5575
5576 Ok(())
5577 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005578}