blob: a7f6a22f658363f5c958bd697ad6ef8b0ae6e7b5 [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},
David Drysdale7b9ca232024-05-23 18:19:46 +010085 Connection, OptionalExtension, ToSql, Transaction,
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
David Drysdale7b9ca232024-05-23 18:19:46 +010095use TransactionBehavior::Immediate;
96
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
David Drysdale7b9ca232024-05-23 18:19:46 +0100100/// Wrapper for `rusqlite::TransactionBehavior` which includes information about the transaction
101/// being performed.
102#[derive(Clone, Copy)]
103enum TransactionBehavior {
104 Deferred,
105 Immediate(&'static str),
106}
107
108impl From<TransactionBehavior> for rusqlite::TransactionBehavior {
109 fn from(val: TransactionBehavior) -> Self {
110 match val {
111 TransactionBehavior::Deferred => rusqlite::TransactionBehavior::Deferred,
112 TransactionBehavior::Immediate(_) => rusqlite::TransactionBehavior::Immediate,
113 }
114 }
115}
116
117impl TransactionBehavior {
118 fn name(&self) -> Option<&'static str> {
119 match self {
120 TransactionBehavior::Deferred => None,
121 TransactionBehavior::Immediate(v) => Some(v),
122 }
123 }
124}
125
David Drysdale115c4722024-04-15 14:11:52 +0100126/// If the database returns a busy error code, retry after this interval.
127const DB_BUSY_RETRY_INTERVAL: Duration = Duration::from_micros(500);
David Drysdale115c4722024-04-15 14:11:52 +0100128
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800129impl_metadata!(
130 /// A set of metadata for key entries.
131 #[derive(Debug, Default, Eq, PartialEq)]
132 pub struct KeyMetaData;
133 /// A metadata entry for key entries.
134 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
135 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800136 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 CreationDate(DateTime) with accessor creation_date,
138 /// Expiration date for attestation keys.
139 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700140 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
141 /// provisioning
142 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
143 /// Vector representing the raw public key so results from the server can be matched
144 /// to the right entry
145 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700146 /// SEC1 public key for ECDH encryption
147 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800148 // --- ADD NEW META DATA FIELDS HERE ---
149 // For backwards compatibility add new entries only to
150 // end of this list and above this comment.
151 };
152);
153
154impl KeyMetaData {
155 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
156 let mut stmt = tx
157 .prepare(
158 "SELECT tag, data from persistent.keymetadata
159 WHERE keyentryid = ?;",
160 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000161 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800162
163 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
164
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000165 let mut rows = stmt
166 .query(params![key_id])
167 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800168 db_utils::with_rows_extract_all(&mut rows, |row| {
169 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
170 metadata.insert(
171 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700172 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800173 .context("Failed to read KeyMetaEntry.")?,
174 );
175 Ok(())
176 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000177 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800178
179 Ok(Self { data: metadata })
180 }
181
182 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
183 let mut stmt = tx
184 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000185 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800186 VALUES (?, ?, ?);",
187 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000188 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800189
190 let iter = self.data.iter();
191 for (tag, entry) in iter {
192 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000193 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800194 })?;
195 }
196 Ok(())
197 }
198}
199
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800200impl_metadata!(
201 /// A set of metadata for key blobs.
202 #[derive(Debug, Default, Eq, PartialEq)]
203 pub struct BlobMetaData;
204 /// A metadata entry for key blobs.
205 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
206 pub enum BlobMetaEntry {
207 /// If present, indicates that the blob is encrypted with another key or a key derived
208 /// from a password.
209 EncryptedBy(EncryptedBy) with accessor encrypted_by,
210 /// If the blob is password encrypted this field is set to the
211 /// salt used for the key derivation.
212 Salt(Vec<u8>) with accessor salt,
213 /// If the blob is encrypted, this field is set to the initialization vector.
214 Iv(Vec<u8>) with accessor iv,
215 /// If the blob is encrypted, this field holds the AEAD TAG.
216 AeadTag(Vec<u8>) with accessor aead_tag,
217 /// The uuid of the owning KeyMint instance.
218 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700219 /// If the key is ECDH encrypted, this is the ephemeral public key
220 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000221 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
222 /// of that key
223 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800224 // --- ADD NEW META DATA FIELDS HERE ---
225 // For backwards compatibility add new entries only to
226 // end of this list and above this comment.
227 };
228);
229
230impl BlobMetaData {
231 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
232 let mut stmt = tx
233 .prepare(
234 "SELECT tag, data from persistent.blobmetadata
235 WHERE blobentryid = ?;",
236 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000237 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800238
239 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
240
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000241 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800242 db_utils::with_rows_extract_all(&mut rows, |row| {
243 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
244 metadata.insert(
245 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700246 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800247 .context("Failed to read BlobMetaEntry.")?,
248 );
249 Ok(())
250 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000251 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800252
253 Ok(Self { data: metadata })
254 }
255
256 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
257 let mut stmt = tx
258 .prepare(
259 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
260 VALUES (?, ?, ?);",
261 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000262 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800263
264 let iter = self.data.iter();
265 for (tag, entry) in iter {
266 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000267 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800268 })?;
269 }
270 Ok(())
271 }
272}
273
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800274/// Indicates the type of the keyentry.
275#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
276pub enum KeyType {
277 /// This is a client key type. These keys are created or imported through the Keystore 2.0
278 /// AIDL interface android.system.keystore2.
279 Client,
280 /// This is a super key type. These keys are created by keystore itself and used to encrypt
281 /// other key blobs to provide LSKF binding.
282 Super,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800283}
284
285impl ToSql for KeyType {
286 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
287 Ok(ToSqlOutput::Owned(Value::Integer(match self {
288 KeyType::Client => 0,
289 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800290 })))
291 }
292}
293
294impl FromSql for KeyType {
295 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
296 match i64::column_result(value)? {
297 0 => Ok(KeyType::Client),
298 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800299 v => Err(FromSqlError::OutOfRange(v)),
300 }
301 }
302}
303
Max Bires8e93d2b2021-01-14 13:17:59 -0800304/// Uuid representation that can be stored in the database.
305/// Right now it can only be initialized from SecurityLevel.
306/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
307#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
308pub struct Uuid([u8; 16]);
309
310impl Deref for Uuid {
311 type Target = [u8; 16];
312
313 fn deref(&self) -> &Self::Target {
314 &self.0
315 }
316}
317
318impl From<SecurityLevel> for Uuid {
319 fn from(sec_level: SecurityLevel) -> Self {
320 Self((sec_level.0 as u128).to_be_bytes())
321 }
322}
323
324impl ToSql for Uuid {
325 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
326 self.0.to_sql()
327 }
328}
329
330impl FromSql for Uuid {
331 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
332 let blob = Vec::<u8>::column_result(value)?;
333 if blob.len() != 16 {
334 return Err(FromSqlError::OutOfRange(blob.len() as i64));
335 }
336 let mut arr = [0u8; 16];
337 arr.copy_from_slice(&blob);
338 Ok(Self(arr))
339 }
340}
341
342/// Key entries that are not associated with any KeyMint instance, such as pure certificate
343/// entries are associated with this UUID.
344pub static KEYSTORE_UUID: Uuid = Uuid([
345 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
346]);
347
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800348/// Indicates how the sensitive part of this key blob is encrypted.
349#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
350pub enum EncryptedBy {
351 /// The keyblob is encrypted by a user password.
352 /// In the database this variant is represented as NULL.
353 Password,
354 /// The keyblob is encrypted by another key with wrapped key id.
355 /// In the database this variant is represented as non NULL value
356 /// that is convertible to i64, typically NUMERIC.
357 KeyId(i64),
358}
359
360impl ToSql for EncryptedBy {
361 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
362 match self {
363 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
364 Self::KeyId(id) => id.to_sql(),
365 }
366 }
367}
368
369impl FromSql for EncryptedBy {
370 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
371 match value {
372 ValueRef::Null => Ok(Self::Password),
373 _ => Ok(Self::KeyId(i64::column_result(value)?)),
374 }
375 }
376}
377
378/// A database representation of wall clock time. DateTime stores unix epoch time as
379/// i64 in milliseconds.
380#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
381pub struct DateTime(i64);
382
383/// Error type returned when creating DateTime or converting it from and to
384/// SystemTime.
385#[derive(thiserror::Error, Debug)]
386pub enum DateTimeError {
387 /// This is returned when SystemTime and Duration computations fail.
388 #[error(transparent)]
389 SystemTimeError(#[from] SystemTimeError),
390
391 /// This is returned when type conversions fail.
392 #[error(transparent)]
393 TypeConversion(#[from] std::num::TryFromIntError),
394
395 /// This is returned when checked time arithmetic failed.
396 #[error("Time arithmetic failed.")]
397 TimeArithmetic,
398}
399
400impl DateTime {
401 /// Constructs a new DateTime object denoting the current time. This may fail during
402 /// conversion to unix epoch time and during conversion to the internal i64 representation.
403 pub fn now() -> Result<Self, DateTimeError> {
404 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
405 }
406
407 /// Constructs a new DateTime object from milliseconds.
408 pub fn from_millis_epoch(millis: i64) -> Self {
409 Self(millis)
410 }
411
412 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700413 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800414 self.0
415 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800416}
417
418impl ToSql for DateTime {
419 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
420 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
421 }
422}
423
424impl FromSql for DateTime {
425 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
426 Ok(Self(i64::column_result(value)?))
427 }
428}
429
430impl TryInto<SystemTime> for DateTime {
431 type Error = DateTimeError;
432
433 fn try_into(self) -> Result<SystemTime, Self::Error> {
434 // We want to construct a SystemTime representation equivalent to self, denoting
435 // a point in time THEN, but we cannot set the time directly. We can only construct
436 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
437 // and between EPOCH and THEN. With this common reference we can construct the
438 // duration between NOW and THEN which we can add to our SystemTime representation
439 // of NOW to get a SystemTime representation of THEN.
440 // Durations can only be positive, thus the if statement below.
441 let now = SystemTime::now();
442 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
443 let then_epoch = Duration::from_millis(self.0.try_into()?);
444 Ok(if now_epoch > then_epoch {
445 // then = now - (now_epoch - then_epoch)
446 now_epoch
447 .checked_sub(then_epoch)
448 .and_then(|d| now.checked_sub(d))
449 .ok_or(DateTimeError::TimeArithmetic)?
450 } else {
451 // then = now + (then_epoch - now_epoch)
452 then_epoch
453 .checked_sub(now_epoch)
454 .and_then(|d| now.checked_add(d))
455 .ok_or(DateTimeError::TimeArithmetic)?
456 })
457 }
458}
459
460impl TryFrom<SystemTime> for DateTime {
461 type Error = DateTimeError;
462
463 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
464 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
465 }
466}
467
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800468#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
469enum KeyLifeCycle {
470 /// Existing keys have a key ID but are not fully populated yet.
471 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
472 /// them to Unreferenced for garbage collection.
473 Existing,
474 /// A live key is fully populated and usable by clients.
475 Live,
476 /// An unreferenced key is scheduled for garbage collection.
477 Unreferenced,
478}
479
480impl ToSql for KeyLifeCycle {
481 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
482 match self {
483 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
484 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
485 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
486 }
487 }
488}
489
490impl FromSql for KeyLifeCycle {
491 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
492 match i64::column_result(value)? {
493 0 => Ok(KeyLifeCycle::Existing),
494 1 => Ok(KeyLifeCycle::Live),
495 2 => Ok(KeyLifeCycle::Unreferenced),
496 v => Err(FromSqlError::OutOfRange(v)),
497 }
498 }
499}
500
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700501/// Keys have a KeyMint blob component and optional public certificate and
502/// certificate chain components.
503/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
504/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800505#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700506pub struct KeyEntryLoadBits(u32);
507
508impl KeyEntryLoadBits {
509 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
510 pub const NONE: KeyEntryLoadBits = Self(0);
511 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
512 pub const KM: KeyEntryLoadBits = Self(1);
513 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
514 pub const PUBLIC: KeyEntryLoadBits = Self(2);
515 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
516 pub const BOTH: KeyEntryLoadBits = Self(3);
517
518 /// Returns true if this object indicates that the public components shall be loaded.
519 pub const fn load_public(&self) -> bool {
520 self.0 & Self::PUBLIC.0 != 0
521 }
522
523 /// Returns true if the object indicates that the KeyMint component shall be loaded.
524 pub const fn load_km(&self) -> bool {
525 self.0 & Self::KM.0 != 0
526 }
527}
528
Janis Danisevskisaec14592020-11-12 09:41:49 -0800529lazy_static! {
530 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
531}
532
533struct KeyIdLockDb {
534 locked_keys: Mutex<HashSet<i64>>,
535 cond_var: Condvar,
536}
537
538/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
539/// from the database a second time. Most functions manipulating the key blob database
540/// require a KeyIdGuard.
541#[derive(Debug)]
542pub struct KeyIdGuard(i64);
543
544impl KeyIdLockDb {
545 fn new() -> Self {
546 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
547 }
548
549 /// This function blocks until an exclusive lock for the given key entry id can
550 /// be acquired. It returns a guard object, that represents the lifecycle of the
551 /// acquired lock.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000552 fn get(&self, key_id: i64) -> KeyIdGuard {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800553 let mut locked_keys = self.locked_keys.lock().unwrap();
554 while locked_keys.contains(&key_id) {
555 locked_keys = self.cond_var.wait(locked_keys).unwrap();
556 }
557 locked_keys.insert(key_id);
558 KeyIdGuard(key_id)
559 }
560
561 /// This function attempts to acquire an exclusive lock on a given key id. If the
562 /// given key id is already taken the function returns None immediately. If a lock
563 /// can be acquired this function returns a guard object, that represents the
564 /// lifecycle of the acquired lock.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000565 fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800566 let mut locked_keys = self.locked_keys.lock().unwrap();
567 if locked_keys.insert(key_id) {
568 Some(KeyIdGuard(key_id))
569 } else {
570 None
571 }
572 }
573}
574
575impl KeyIdGuard {
576 /// Get the numeric key id of the locked key.
577 pub fn id(&self) -> i64 {
578 self.0
579 }
580}
581
582impl Drop for KeyIdGuard {
583 fn drop(&mut self) {
584 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
585 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800586 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800587 KEY_ID_LOCK.cond_var.notify_all();
588 }
589}
590
Max Bires8e93d2b2021-01-14 13:17:59 -0800591/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700592#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800593pub struct CertificateInfo {
594 cert: Option<Vec<u8>>,
595 cert_chain: Option<Vec<u8>>,
596}
597
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800598/// This type represents a Blob with its metadata and an optional superseded blob.
599#[derive(Debug)]
600pub struct BlobInfo<'a> {
601 blob: &'a [u8],
602 metadata: &'a BlobMetaData,
603 /// Superseded blobs are an artifact of legacy import. In some rare occasions
604 /// the key blob needs to be upgraded during import. In that case two
605 /// blob are imported, the superseded one will have to be imported first,
606 /// so that the garbage collector can reap it.
607 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
608}
609
610impl<'a> BlobInfo<'a> {
611 /// Create a new instance of blob info with blob and corresponding metadata
612 /// and no superseded blob info.
613 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
614 Self { blob, metadata, superseded_blob: None }
615 }
616
617 /// Create a new instance of blob info with blob and corresponding metadata
618 /// as well as superseded blob info.
619 pub fn new_with_superseded(
620 blob: &'a [u8],
621 metadata: &'a BlobMetaData,
622 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
623 ) -> Self {
624 Self { blob, metadata, superseded_blob }
625 }
626}
627
Max Bires8e93d2b2021-01-14 13:17:59 -0800628impl CertificateInfo {
629 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
630 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
631 Self { cert, cert_chain }
632 }
633
634 /// Take the cert
635 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
636 self.cert.take()
637 }
638
639 /// Take the cert chain
640 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
641 self.cert_chain.take()
642 }
643}
644
Max Bires2b2e6562020-09-22 11:22:36 -0700645/// This type represents a certificate chain with a private key corresponding to the leaf
646/// 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 -0700647pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800648 /// A KM key blob
649 pub private_key: ZVec,
650 /// A batch cert for private_key
651 pub batch_cert: Vec<u8>,
652 /// A full certificate chain from root signing authority to private_key, including batch_cert
653 /// for convenience.
654 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700655}
656
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700657/// This type represents a Keystore 2.0 key entry.
658/// An entry has a unique `id` by which it can be found in the database.
659/// It has a security level field, key parameters, and three optional fields
660/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800661#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700662pub struct KeyEntry {
663 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800664 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700665 cert: Option<Vec<u8>>,
666 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800667 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700668 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800669 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800670 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700671}
672
673impl KeyEntry {
674 /// Returns the unique id of the Key entry.
675 pub fn id(&self) -> i64 {
676 self.id
677 }
678 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800679 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
680 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800682 /// Extracts the Optional KeyMint blob including its metadata.
683 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
684 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 }
686 /// Exposes the optional public certificate.
687 pub fn cert(&self) -> &Option<Vec<u8>> {
688 &self.cert
689 }
690 /// Extracts the optional public certificate.
691 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
692 self.cert.take()
693 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700694 /// Extracts the optional public certificate_chain.
695 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
696 self.cert_chain.take()
697 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800698 /// Returns the uuid of the owning KeyMint instance.
699 pub fn km_uuid(&self) -> &Uuid {
700 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700701 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700702 /// Consumes this key entry and extracts the keyparameters from it.
703 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
704 self.parameters
705 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800706 /// Exposes the key metadata of this key entry.
707 pub fn metadata(&self) -> &KeyMetaData {
708 &self.metadata
709 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800710 /// This returns true if the entry is a pure certificate entry with no
711 /// private key component.
712 pub fn pure_cert(&self) -> bool {
713 self.pure_cert
714 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700715}
716
717/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800718#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700719pub struct SubComponentType(u32);
720impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800721 /// Persistent identifier for a key blob.
722 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700723 /// Persistent identifier for a certificate blob.
724 pub const CERT: SubComponentType = Self(1);
725 /// Persistent identifier for a certificate chain blob.
726 pub const CERT_CHAIN: SubComponentType = Self(2);
727}
728
729impl ToSql for SubComponentType {
730 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
731 self.0.to_sql()
732 }
733}
734
735impl FromSql for SubComponentType {
736 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
737 Ok(Self(u32::column_result(value)?))
738 }
739}
740
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800741/// This trait is private to the database module. It is used to convey whether or not the garbage
742/// collector shall be invoked after a database access. All closures passed to
743/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
744/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
745/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
746/// `.need_gc()`.
747trait DoGc<T> {
748 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
749
750 fn no_gc(self) -> Result<(bool, T)>;
751
752 fn need_gc(self) -> Result<(bool, T)>;
753}
754
755impl<T> DoGc<T> for Result<T> {
756 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
757 self.map(|r| (need_gc, r))
758 }
759
760 fn no_gc(self) -> Result<(bool, T)> {
761 self.do_gc(false)
762 }
763
764 fn need_gc(self) -> Result<(bool, T)> {
765 self.do_gc(true)
766 }
767}
768
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700769/// KeystoreDB wraps a connection to an SQLite database and tracks its
770/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700771pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700772 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700773 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700774 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700775}
776
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000777/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000778/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000779#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000780pub struct BootTime(i64);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000781
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000782impl BootTime {
783 /// Constructs a new BootTime
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000784 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000785 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000786 }
787
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000788 /// Returns the value of BootTime in milliseconds as i64
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000789 pub fn milliseconds(&self) -> i64 {
790 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000791 }
792
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000793 /// Returns the integer value of BootTime as i64
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000794 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000795 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000796 }
797
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 /// Like i64::checked_sub.
799 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
800 self.0.checked_sub(other.0).map(Self)
801 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000802}
803
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000804impl ToSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000805 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
806 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
807 }
808}
809
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000810impl FromSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000811 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
812 Ok(Self(i64::column_result(value)?))
813 }
814}
815
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000816/// This struct encapsulates the information to be stored in the database about the auth tokens
817/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700818#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000819pub struct AuthTokenEntry {
820 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000821 // Time received in milliseconds
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000822 time_received: BootTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000823}
824
825impl AuthTokenEntry {
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000826 fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000827 AuthTokenEntry { auth_token, time_received }
828 }
829
830 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800831 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000832 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800833 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000834 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000835 })
836 }
837
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000838 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800839 pub fn auth_token(&self) -> &HardwareAuthToken {
840 &self.auth_token
841 }
842
843 /// Returns the auth token wrapped by the AuthTokenEntry
844 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000845 self.auth_token
846 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800847
848 /// Returns the time that this auth token was received.
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000849 pub fn time_received(&self) -> BootTime {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800850 self.time_received
851 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000852
853 /// Returns the challenge value of the auth token.
854 pub fn challenge(&self) -> i64 {
855 self.auth_token.challenge
856 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000857}
858
Joel Galenson26f4d012020-07-17 14:57:21 -0700859impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800860 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700861 const CURRENT_DB_VERSION: u32 = 1;
862 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800863
Seth Moore78c091f2021-04-09 21:38:30 +0000864 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700865 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000866
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700867 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868 /// files persistent.sqlite and perboot.sqlite in the given directory.
869 /// It also attempts to initialize all of the tables.
870 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700871 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700872 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
David Drysdale541846b2024-05-23 13:16:07 +0100873 let _wp = wd::watch("KeystoreDB::new");
Janis Danisevskis850d4862021-05-05 08:41:14 -0700874
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700875 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700876 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800877
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700878 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
David Drysdale7b9ca232024-05-23 18:19:46 +0100879 db.with_transaction(Immediate("TX_new"), |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700880 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000881 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800882 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800883 })?;
884 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700885 }
886
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700887 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
888 // cryptographic binding to the boot level keys was implemented.
889 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
890 tx.execute(
891 "UPDATE persistent.keyentry SET state = ?
892 WHERE
893 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
894 AND
895 id NOT IN (
896 SELECT keyentryid FROM persistent.blobentry
897 WHERE id IN (
898 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
899 )
900 );",
901 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
902 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000903 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700904 Ok(1)
905 }
906
Janis Danisevskis66784c42021-01-27 08:40:25 -0800907 fn init_tables(tx: &Transaction) -> Result<()> {
908 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700910 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800911 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700912 domain INTEGER,
913 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800914 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800915 state INTEGER,
916 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000917 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700918 )
919 .context("Failed to initialize \"keyentry\" table.")?;
920
Janis Danisevskis66784c42021-01-27 08:40:25 -0800921 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800922 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
923 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000924 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800925 )
926 .context("Failed to create index keyentry_id_index.")?;
927
928 tx.execute(
929 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
930 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000931 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800932 )
933 .context("Failed to create index keyentry_domain_namespace_index.")?;
934
935 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700936 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
937 id INTEGER PRIMARY KEY,
938 subcomponent_type INTEGER,
939 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800940 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000941 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700942 )
943 .context("Failed to initialize \"blobentry\" table.")?;
944
Janis Danisevskis66784c42021-01-27 08:40:25 -0800945 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800946 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
947 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000948 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800949 )
950 .context("Failed to create index blobentry_keyentryid_index.")?;
951
952 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800953 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
954 id INTEGER PRIMARY KEY,
955 blobentryid INTEGER,
956 tag INTEGER,
957 data ANY,
958 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000959 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800960 )
961 .context("Failed to initialize \"blobmetadata\" table.")?;
962
963 tx.execute(
964 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
965 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000966 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800967 )
968 .context("Failed to create index blobmetadata_blobentryid_index.")?;
969
970 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700971 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000972 keyentryid INTEGER,
973 tag INTEGER,
974 data ANY,
975 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000976 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700977 )
978 .context("Failed to initialize \"keyparameter\" table.")?;
979
Janis Danisevskis66784c42021-01-27 08:40:25 -0800980 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800981 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
982 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000983 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800984 )
985 .context("Failed to create index keyparameter_keyentryid_index.")?;
986
987 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800988 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
989 keyentryid INTEGER,
990 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000991 data ANY,
992 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000993 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800994 )
995 .context("Failed to initialize \"keymetadata\" table.")?;
996
Janis Danisevskis66784c42021-01-27 08:40:25 -0800997 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800998 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
999 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001000 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -08001001 )
1002 .context("Failed to create index keymetadata_keyentryid_index.")?;
1003
1004 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001005 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001006 id INTEGER UNIQUE,
1007 grantee INTEGER,
1008 keyentryid INTEGER,
1009 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001010 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001011 )
1012 .context("Failed to initialize \"grant\" table.")?;
1013
Joel Galenson0891bc12020-07-20 10:37:03 -07001014 Ok(())
1015 }
1016
Seth Moore472fcbb2021-05-12 10:07:51 -07001017 fn make_persistent_path(db_root: &Path) -> Result<String> {
1018 // Build the path to the sqlite file.
1019 let mut persistent_path = db_root.to_path_buf();
1020 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1021
1022 // Now convert them to strings prefixed with "file:"
1023 let mut persistent_path_str = "file:".to_owned();
1024 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1025
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001026 // Connect to database in specific mode
1027 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1028 "?journal_mode=WAL".to_owned()
1029 } else {
1030 "?journal_mode=DELETE".to_owned()
1031 };
1032 persistent_path_str.push_str(&persistent_path_mode);
1033
Seth Moore472fcbb2021-05-12 10:07:51 -07001034 Ok(persistent_path_str)
1035 }
1036
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001037 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001038 let conn =
1039 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1040
Janis Danisevskis66784c42021-01-27 08:40:25 -08001041 loop {
1042 if let Err(e) = conn
1043 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1044 .context("Failed to attach database persistent.")
1045 {
1046 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001047 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001048 continue;
1049 } else {
1050 return Err(e);
1051 }
1052 }
1053 break;
1054 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001055
Matthew Maurer4fb19112021-05-06 15:40:44 -07001056 // Drop the cache size from default (2M) to 0.5M
1057 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1058 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001059
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001060 Ok(conn)
1061 }
1062
Seth Moore78c091f2021-04-09 21:38:30 +00001063 fn do_table_size_query(
1064 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001065 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001066 query: &str,
1067 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001068 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001069 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001070 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001071 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001072 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001073 })
1074 .no_gc()
1075 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001076 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001077 }
1078
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001079 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001080 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001081 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001082 "SELECT page_count * page_size, freelist_count * page_size
1083 FROM pragma_page_count('persistent'),
1084 pragma_page_size('persistent'),
1085 persistent.pragma_freelist_count();",
1086 &[],
1087 )
1088 }
1089
1090 fn get_table_size(
1091 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001092 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001093 schema: &str,
1094 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001095 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001096 self.do_table_size_query(
1097 storage_type,
1098 "SELECT pgsize,unused FROM dbstat(?1)
1099 WHERE name=?2 AND aggregate=TRUE;",
1100 &[schema, table],
1101 )
1102 }
1103
1104 /// Fetches a storage statisitics atom for a given storage type. For storage
1105 /// types that map to a table, information about the table's storage is
1106 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
David Drysdale541846b2024-05-23 13:16:07 +01001108 let _wp = wd::watch("KeystoreDB::get_storage_stat");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001109
Seth Moore78c091f2021-04-09 21:38:30 +00001110 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001111 MetricsStorage::DATABASE => self.get_total_size(),
1112 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001113 self.get_table_size(storage_type, "persistent", "keyentry")
1114 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001115 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001116 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1117 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001118 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001119 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1120 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001121 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001122 self.get_table_size(storage_type, "persistent", "blobentry")
1123 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001124 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001125 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1126 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001128 self.get_table_size(storage_type, "persistent", "keyparameter")
1129 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001131 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1132 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001133 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001134 self.get_table_size(storage_type, "persistent", "keymetadata")
1135 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001137 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1138 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1140 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001141 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1142 // reportable
1143 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001144 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001145 storage_type,
1146 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001147 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001148 unused_size: 0,
1149 })
Seth Moore78c091f2021-04-09 21:38:30 +00001150 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001151 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001152 self.get_table_size(storage_type, "persistent", "blobmetadata")
1153 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001154 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001155 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1156 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001157 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001158 }
1159 }
1160
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001162 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1163 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1165 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001166 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001168 blob_ids_to_delete: &[i64],
1169 max_blobs: usize,
1170 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
David Drysdale541846b2024-05-23 13:16:07 +01001171 let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob");
David Drysdale7b9ca232024-05-23 18:19:46 +01001172 self.with_transaction(Immediate("TX_handle_next_superseded_blob"), |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001173 // Delete the given blobs.
1174 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001175 tx.execute(
1176 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001177 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001178 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001179 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001180 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001181 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001182 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001183
1184 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1185
Janis Danisevskis3395f862021-05-06 10:54:17 -07001186 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1187 let result: Vec<(i64, Vec<u8>)> = {
1188 let mut stmt = tx
1189 .prepare(
1190 "SELECT id, blob FROM persistent.blobentry
1191 WHERE subcomponent_type = ?
1192 AND (
1193 id NOT IN (
1194 SELECT MAX(id) FROM persistent.blobentry
1195 WHERE subcomponent_type = ?
1196 GROUP BY keyentryid, subcomponent_type
1197 )
1198 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1199 ) LIMIT ?;",
1200 )
1201 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001202
Janis Danisevskis3395f862021-05-06 10:54:17 -07001203 let rows = stmt
1204 .query_map(
1205 params![
1206 SubComponentType::KEY_BLOB,
1207 SubComponentType::KEY_BLOB,
1208 max_blobs as i64,
1209 ],
1210 |row| Ok((row.get(0)?, row.get(1)?)),
1211 )
1212 .context("Trying to query superseded blob.")?;
1213
1214 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1215 .context("Trying to extract superseded blobs.")?
1216 };
1217
1218 let result = result
1219 .into_iter()
1220 .map(|(blob_id, blob)| {
1221 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1222 })
1223 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1224 .context("Trying to load blob metadata.")?;
1225 if !result.is_empty() {
1226 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001227 }
1228
1229 // We did not find any superseded key blob, so let's remove other superseded blob in
1230 // one transaction.
1231 tx.execute(
1232 "DELETE FROM persistent.blobentry
1233 WHERE NOT subcomponent_type = ?
1234 AND (
1235 id NOT IN (
1236 SELECT MAX(id) FROM persistent.blobentry
1237 WHERE NOT subcomponent_type = ?
1238 GROUP BY keyentryid, subcomponent_type
1239 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1240 );",
1241 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1242 )
1243 .context("Trying to purge superseded blobs.")?;
1244
Janis Danisevskis3395f862021-05-06 10:54:17 -07001245 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001246 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001247 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001248 }
1249
1250 /// This maintenance function should be called only once before the database is used for the
1251 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1252 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1253 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1254 /// Keystore crashed at some point during key generation. Callers may want to log such
1255 /// occurrences.
1256 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1257 /// it to `KeyLifeCycle::Live` may have grants.
1258 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01001259 let _wp = wd::watch("KeystoreDB::cleanup_leftovers");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001260
David Drysdale7b9ca232024-05-23 18:19:46 +01001261 self.with_transaction(Immediate("TX_cleanup_leftovers"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001262 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001263 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1264 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1265 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001266 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001267 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001268 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001269 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001270 }
1271
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001272 /// Checks if a key exists with given key type and key descriptor properties.
1273 pub fn key_exists(
1274 &mut self,
1275 domain: Domain,
1276 nspace: i64,
1277 alias: &str,
1278 key_type: KeyType,
1279 ) -> Result<bool> {
David Drysdale541846b2024-05-23 13:16:07 +01001280 let _wp = wd::watch("KeystoreDB::key_exists");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001281
David Drysdale7b9ca232024-05-23 18:19:46 +01001282 self.with_transaction(Immediate("TX_key_exists"), |tx| {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001283 let key_descriptor =
1284 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001285 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001286 match result {
1287 Ok(_) => Ok(true),
1288 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1289 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001290 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001291 },
1292 }
1293 .no_gc()
1294 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001295 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001296 }
1297
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 /// Stores a super key in the database.
1299 pub fn store_super_key(
1300 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001301 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001302 key_type: &SuperKeyType,
1303 blob: &[u8],
1304 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001305 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001306 ) -> Result<KeyEntry> {
David Drysdale541846b2024-05-23 13:16:07 +01001307 let _wp = wd::watch("KeystoreDB::store_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001308
David Drysdale7b9ca232024-05-23 18:19:46 +01001309 self.with_transaction(Immediate("TX_store_super_key"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00001310 let key_id = Self::insert_with_retry(|id| {
1311 tx.execute(
1312 "INSERT into persistent.keyentry
1313 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001314 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001315 params![
1316 id,
1317 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001318 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001319 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001320 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001321 KeyLifeCycle::Live,
1322 &KEYSTORE_UUID,
1323 ],
1324 )
1325 })
1326 .context("Failed to insert into keyentry table.")?;
1327
Paul Crowley8d5b2532021-03-19 10:53:07 -07001328 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1329
Hasini Gunasingheda895552021-01-27 19:34:37 +00001330 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001331 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001332 key_id,
1333 SubComponentType::KEY_BLOB,
1334 Some(blob),
1335 Some(blob_metadata),
1336 )
1337 .context("Failed to store key blob.")?;
1338
1339 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1340 .context("Trying to load key components.")
1341 .no_gc()
1342 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001343 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001344 }
1345
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001347 pub fn load_super_key(
1348 &mut self,
1349 key_type: &SuperKeyType,
1350 user_id: u32,
1351 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
David Drysdale541846b2024-05-23 13:16:07 +01001352 let _wp = wd::watch("KeystoreDB::load_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001353
David Drysdale7b9ca232024-05-23 18:19:46 +01001354 self.with_transaction(Immediate("TX_load_super_key"), |tx| {
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001355 let key_descriptor = KeyDescriptor {
1356 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001357 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001358 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001359 blob: None,
1360 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001361 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001362 match id {
1363 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001364 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001365 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001366 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1367 }
1368 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1369 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001370 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001371 },
1372 }
1373 .no_gc()
1374 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001375 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001376 }
1377
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001378 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001379 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1380 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001381 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1382 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001383 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001384 {
David Drysdale7b9ca232024-05-23 18:19:46 +01001385 let name = behavior.name();
Janis Danisevskis66784c42021-01-27 08:40:25 -08001386 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001387 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001388 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01001389 .transaction_with_behavior(behavior.into())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001390 .context(ks_err!())
David Drysdale7b9ca232024-05-23 18:19:46 +01001391 .and_then(|tx| {
1392 let _wp = name.map(wd::watch);
1393 f(&tx).map(|result| (result, tx))
1394 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001395 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001396 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001398 });
1399 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 Ok(result) => break Ok(result),
1401 Err(e) => {
1402 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001403 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 continue;
1405 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001406 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 }
1408 }
1409 }
1410 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001411 .map(|(need_gc, result)| {
1412 if need_gc {
1413 if let Some(ref gc) = self.gc {
1414 gc.notify_gc();
1415 }
1416 }
1417 result
1418 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 }
1420
1421 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001422 matches!(
1423 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1424 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1425 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1426 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001427 }
1428
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001429 fn create_key_entry_internal(
1430 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001431 domain: &Domain,
1432 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001433 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001434 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001435 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001436 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001437 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001438 _ => {
1439 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001440 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001441 }
1442 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001443 Ok(KEY_ID_LOCK.get(
1444 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001445 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001446 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001447 (id, key_type, domain, namespace, alias, state, km_uuid)
1448 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001449 params![
1450 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001451 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001452 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001453 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001454 KeyLifeCycle::Existing,
1455 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001456 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001457 )
1458 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001459 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001460 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001461 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001462
Janis Danisevskis377d1002021-01-27 19:07:48 -08001463 /// Set a new blob and associates it with the given key id. Each blob
1464 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001465 /// Each key can have one of each sub component type associated. If more
1466 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001467 /// will get garbage collected.
1468 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1469 /// removed by setting blob to None.
1470 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001471 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001472 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001473 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001474 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001475 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001476 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001477 let _wp = wd::watch("KeystoreDB::set_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001478
David Drysdale7b9ca232024-05-23 18:19:46 +01001479 self.with_transaction(Immediate("TX_set_blob"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001480 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001481 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001482 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001483 }
1484
Janis Danisevskiseed69842021-02-18 20:04:10 -08001485 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1486 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1487 /// We use this to insert key blobs into the database which can then be garbage collected
1488 /// lazily by the key garbage collector.
1489 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001490 let _wp = wd::watch("KeystoreDB::set_deleted_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001491
David Drysdale7b9ca232024-05-23 18:19:46 +01001492 self.with_transaction(Immediate("TX_set_deleted_blob"), |tx| {
Janis Danisevskiseed69842021-02-18 20:04:10 -08001493 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001494 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001495 Self::UNASSIGNED_KEY_ID,
1496 SubComponentType::KEY_BLOB,
1497 Some(blob),
1498 Some(blob_metadata),
1499 )
1500 .need_gc()
1501 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001502 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001503 }
1504
Janis Danisevskis377d1002021-01-27 19:07:48 -08001505 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001506 tx: &Transaction,
1507 key_id: i64,
1508 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001509 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001510 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001511 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001512 match (blob, sc_type) {
1513 (Some(blob), _) => {
1514 tx.execute(
1515 "INSERT INTO persistent.blobentry
1516 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1517 params![sc_type, key_id, blob],
1518 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001519 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001520 if let Some(blob_metadata) = blob_metadata {
1521 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001522 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001523 row.get(0)
1524 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001525 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001526 blob_metadata
1527 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001528 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001529 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001530 }
1531 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1532 tx.execute(
1533 "DELETE FROM persistent.blobentry
1534 WHERE subcomponent_type = ? AND keyentryid = ?;",
1535 params![sc_type, key_id],
1536 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001537 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001538 }
1539 (None, _) => {
1540 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001541 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001542 }
1543 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001544 Ok(())
1545 }
1546
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001547 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1548 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001549 #[cfg(test)]
1550 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001551 self.with_transaction(Immediate("TX_insert_keyparameter"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001552 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001553 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001554 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001555 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001556
Janis Danisevskis66784c42021-01-27 08:40:25 -08001557 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001558 tx: &Transaction,
1559 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001560 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001561 ) -> Result<()> {
1562 let mut stmt = tx
1563 .prepare(
1564 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1565 VALUES (?, ?, ?, ?);",
1566 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001567 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001568
Janis Danisevskis66784c42021-01-27 08:40:25 -08001569 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001570 stmt.insert(params![
1571 key_id.0,
1572 p.get_tag().0,
1573 p.key_parameter_value(),
1574 p.security_level().0
1575 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001576 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001577 }
1578 Ok(())
1579 }
1580
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001581 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001582 #[cfg(test)]
1583 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001584 self.with_transaction(Immediate("TX_insert_key_metadata"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001585 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001586 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001587 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001588 }
1589
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001590 /// Updates the alias column of the given key id `newid` with the given alias,
1591 /// and atomically, removes the alias, domain, and namespace from another row
1592 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001593 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1594 /// collector.
1595 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001596 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001597 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001598 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001599 domain: &Domain,
1600 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001601 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001602 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001603 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001604 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001605 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001606 return Err(KsError::sys())
1607 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001608 }
1609 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001610 let updated = tx
1611 .execute(
1612 "UPDATE persistent.keyentry
1613 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001614 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1615 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001616 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001617 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001618 let result = tx
1619 .execute(
1620 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001621 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001622 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001623 params![
1624 alias,
1625 KeyLifeCycle::Live,
1626 newid.0,
1627 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001628 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001629 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001630 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001631 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001632 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001633 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001634 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001635 return Err(KsError::sys()).context(ks_err!(
1636 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001637 result
1638 ));
1639 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001640 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001641 }
1642
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001643 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1644 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1645 pub fn migrate_key_namespace(
1646 &mut self,
1647 key_id_guard: KeyIdGuard,
1648 destination: &KeyDescriptor,
1649 caller_uid: u32,
1650 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1651 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001652 let _wp = wd::watch("KeystoreDB::migrate_key_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001653
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001654 let destination = match destination.domain {
1655 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1656 Domain::SELINUX => (*destination).clone(),
1657 domain => {
1658 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1659 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1660 }
1661 };
1662
1663 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001664 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001665
1666 let alias = destination
1667 .alias
1668 .as_ref()
1669 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001670 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001671
David Drysdale7b9ca232024-05-23 18:19:46 +01001672 self.with_transaction(Immediate("TX_migrate_key_namespace"), |tx| {
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001673 // Query the destination location. If there is a key, the migration request fails.
1674 if tx
1675 .query_row(
1676 "SELECT id FROM persistent.keyentry
1677 WHERE alias = ? AND domain = ? AND namespace = ?;",
1678 params![alias, destination.domain.0, destination.nspace],
1679 |_| Ok(()),
1680 )
1681 .optional()
1682 .context("Failed to query destination.")?
1683 .is_some()
1684 {
1685 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1686 .context("Target already exists.");
1687 }
1688
1689 let updated = tx
1690 .execute(
1691 "UPDATE persistent.keyentry
1692 SET alias = ?, domain = ?, namespace = ?
1693 WHERE id = ?;",
1694 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1695 )
1696 .context("Failed to update key entry.")?;
1697
1698 if updated != 1 {
1699 return Err(KsError::sys())
1700 .context(format!("Update succeeded, but {} rows were updated.", updated));
1701 }
1702 Ok(()).no_gc()
1703 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001704 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001705 }
1706
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001707 /// Store a new key in a single transaction.
1708 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1709 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001710 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1711 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001712 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001713 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001714 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001715 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001716 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001717 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001718 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001719 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001720 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001721 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001722 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001723 let _wp = wd::watch("KeystoreDB::store_new_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001724
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001725 let (alias, domain, namespace) = match key {
1726 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1727 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1728 (alias, key.domain, nspace)
1729 }
1730 _ => {
1731 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001732 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 }
1734 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001735 self.with_transaction(Immediate("TX_store_new_key"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001736 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001737 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001738 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1739
1740 // In some occasions the key blob is already upgraded during the import.
1741 // In order to make sure it gets properly deleted it is inserted into the
1742 // database here and then immediately replaced by the superseding blob.
1743 // The garbage collector will then subject the blob to deleteKey of the
1744 // KM back end to permanently invalidate the key.
1745 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1746 Self::set_blob_internal(
1747 tx,
1748 key_id.id(),
1749 SubComponentType::KEY_BLOB,
1750 Some(blob),
1751 Some(blob_metadata),
1752 )
1753 .context("Trying to insert superseded key blob.")?;
1754 true
1755 } else {
1756 false
1757 };
1758
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001759 Self::set_blob_internal(
1760 tx,
1761 key_id.id(),
1762 SubComponentType::KEY_BLOB,
1763 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001764 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001765 )
1766 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001767 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001768 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001769 .context("Trying to insert the certificate.")?;
1770 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001771 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001772 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001773 tx,
1774 key_id.id(),
1775 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001776 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001777 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001778 )
1779 .context("Trying to insert the certificate chain.")?;
1780 }
1781 Self::insert_keyparameter_internal(tx, &key_id, params)
1782 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001783 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001784 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001785 .context("Trying to rebind alias.")?
1786 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001787 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001788 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001789 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001790 }
1791
Janis Danisevskis377d1002021-01-27 19:07:48 -08001792 /// Store a new certificate
1793 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1794 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001795 pub fn store_new_certificate(
1796 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001797 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001798 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001799 cert: &[u8],
1800 km_uuid: &Uuid,
1801 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001802 let _wp = wd::watch("KeystoreDB::store_new_certificate");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001803
Janis Danisevskis377d1002021-01-27 19:07:48 -08001804 let (alias, domain, namespace) = match key {
1805 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1806 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1807 (alias, key.domain, nspace)
1808 }
1809 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001810 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1811 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001812 }
1813 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001814 self.with_transaction(Immediate("TX_store_new_certificate"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001815 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001816 .context("Trying to create new key entry.")?;
1817
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001818 Self::set_blob_internal(
1819 tx,
1820 key_id.id(),
1821 SubComponentType::CERT_CHAIN,
1822 Some(cert),
1823 None,
1824 )
1825 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001826
1827 let mut metadata = KeyMetaData::new();
1828 metadata.add(KeyMetaEntry::CreationDate(
1829 DateTime::now().context("Trying to make creation time.")?,
1830 ));
1831
1832 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1833
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001834 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001835 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001836 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001837 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001838 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001839 }
1840
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001841 // Helper function loading the key_id given the key descriptor
1842 // tuple comprising domain, namespace, and alias.
1843 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001844 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001845 let alias = key
1846 .alias
1847 .as_ref()
1848 .map_or_else(|| Err(KsError::sys()), Ok)
1849 .context("In load_key_entry_id: Alias must be specified.")?;
1850 let mut stmt = tx
1851 .prepare(
1852 "SELECT id FROM persistent.keyentry
1853 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001854 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001855 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001856 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001857 AND alias = ?
1858 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001859 )
1860 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1861 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001862 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001863 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001864 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001865 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001866 .get(0)
1867 .context("Failed to unpack id.")
1868 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001869 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001870 }
1871
1872 /// This helper function completes the access tuple of a key, which is required
1873 /// to perform access control. The strategy depends on the `domain` field in the
1874 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001875 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001876 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001877 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001878 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001879 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001880 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001881 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001882 /// `namespace`.
1883 /// In each case the information returned is sufficient to perform the access
1884 /// check and the key id can be used to load further key artifacts.
1885 fn load_access_tuple(
1886 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001887 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001888 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001889 caller_uid: u32,
1890 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1891 match key.domain {
1892 // Domain App or SELinux. In this case we load the key_id from
1893 // the keyentry database for further loading of key components.
1894 // We already have the full access tuple to perform access control.
1895 // The only distinction is that we use the caller_uid instead
1896 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001897 // Domain::APP.
1898 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001899 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001900 if access_key.domain == Domain::APP {
1901 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001902 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001903 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001904 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001905
1906 Ok((key_id, access_key, None))
1907 }
1908
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001909 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001910 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001911 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001912 let mut stmt = tx
1913 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001914 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001915 WHERE grantee = ? AND id = ? AND
1916 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001917 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001918 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001919 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001920 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001921 .context("Domain:Grant: query failed.")?;
1922 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001923 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001924 let r =
1925 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001926 Ok((
1927 r.get(0).context("Failed to unpack key_id.")?,
1928 r.get(1).context("Failed to unpack access_vector.")?,
1929 ))
1930 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001931 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001932 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001933 }
1934
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001935 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001936 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001937 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08001938 let (domain, namespace): (Domain, i64) = {
1939 let mut stmt = tx
1940 .prepare(
1941 "SELECT domain, namespace FROM persistent.keyentry
1942 WHERE
1943 id = ?
1944 AND state = ?;",
1945 )
1946 .context("Domain::KEY_ID: prepare statement failed")?;
1947 let mut rows = stmt
1948 .query(params![key.nspace, KeyLifeCycle::Live])
1949 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001950 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001951 let r =
1952 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001953 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001954 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001955 r.get(1).context("Failed to unpack namespace.")?,
1956 ))
1957 })
Janis Danisevskis45760022021-01-19 16:34:10 -08001958 .context("Domain::KEY_ID.")?
1959 };
1960
1961 // We may use a key by id after loading it by grant.
1962 // In this case we have to check if the caller has a grant for this particular
1963 // key. We can skip this if we already know that the caller is the owner.
1964 // But we cannot know this if domain is anything but App. E.g. in the case
1965 // of Domain::SELINUX we have to speculatively check for grants because we have to
1966 // consult the SEPolicy before we know if the caller is the owner.
1967 let access_vector: Option<KeyPermSet> =
1968 if domain != Domain::APP || namespace != caller_uid as i64 {
1969 let access_vector: Option<i32> = tx
1970 .query_row(
1971 "SELECT access_vector FROM persistent.grant
1972 WHERE grantee = ? AND keyentryid = ?;",
1973 params![caller_uid as i64, key.nspace],
1974 |row| row.get(0),
1975 )
1976 .optional()
1977 .context("Domain::KEY_ID: query grant failed.")?;
1978 access_vector.map(|p| p.into())
1979 } else {
1980 None
1981 };
1982
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001983 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001984 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001985 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001986 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001987
Janis Danisevskis45760022021-01-19 16:34:10 -08001988 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001989 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00001990 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001991 }
1992 }
1993
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001994 fn load_blob_components(
1995 key_id: i64,
1996 load_bits: KeyEntryLoadBits,
1997 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001998 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001999 let mut stmt = tx
2000 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002001 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002002 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2003 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002004 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002005
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002006 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002007
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002008 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002009 let mut cert_blob: Option<Vec<u8>> = None;
2010 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002011 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002012 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002013 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002014 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002015 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002016 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2017 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002018 key_blob = Some((
2019 row.get(0).context("Failed to extract key blob id.")?,
2020 row.get(2).context("Failed to extract key blob.")?,
2021 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002022 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002023 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002024 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002025 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002026 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002027 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002028 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002029 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002030 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002031 (SubComponentType::CERT, _, _)
2032 | (SubComponentType::CERT_CHAIN, _, _)
2033 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002034 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2035 }
2036 Ok(())
2037 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002038 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002039
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002040 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2041 Ok(Some((
2042 blob,
2043 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002044 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002045 )))
2046 })?;
2047
2048 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002049 }
2050
2051 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2052 let mut stmt = tx
2053 .prepare(
2054 "SELECT tag, data, security_level from persistent.keyparameter
2055 WHERE keyentryid = ?;",
2056 )
2057 .context("In load_key_parameters: prepare statement failed.")?;
2058
2059 let mut parameters: Vec<KeyParameter> = Vec::new();
2060
2061 let mut rows =
2062 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002063 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002064 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2065 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002066 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002067 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002068 .context("Failed to read KeyParameter.")?,
2069 );
2070 Ok(())
2071 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002072 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002073
2074 Ok(parameters)
2075 }
2076
Qi Wub9433b52020-12-01 14:52:46 +08002077 /// Decrements the usage count of a limited use key. This function first checks whether the
2078 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2079 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2080 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002081 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002082 let _wp = wd::watch("KeystoreDB::check_and_update_key_usage_count");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002083
David Drysdale7b9ca232024-05-23 18:19:46 +01002084 self.with_transaction(Immediate("TX_check_and_update_key_usage_count"), |tx| {
Qi Wub9433b52020-12-01 14:52:46 +08002085 let limit: Option<i32> = tx
2086 .query_row(
2087 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2088 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2089 |row| row.get(0),
2090 )
2091 .optional()
2092 .context("Trying to load usage count")?;
2093
2094 let limit = limit
2095 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2096 .context("The Key no longer exists. Key is exhausted.")?;
2097
2098 tx.execute(
2099 "UPDATE persistent.keyparameter
2100 SET data = data - 1
2101 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2102 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2103 )
2104 .context("Failed to update key usage count.")?;
2105
2106 match limit {
2107 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002108 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002109 .context("Trying to mark limited use key for deletion."),
2110 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002111 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002112 }
2113 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002114 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002115 }
2116
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002117 /// Load a key entry by the given key descriptor.
2118 /// It uses the `check_permission` callback to verify if the access is allowed
2119 /// given the key access tuple read from the database using `load_access_tuple`.
2120 /// With `load_bits` the caller may specify which blobs shall be loaded from
2121 /// the blob database.
2122 pub fn load_key_entry(
2123 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002124 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002125 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002126 load_bits: KeyEntryLoadBits,
2127 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002128 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2129 ) -> Result<(KeyIdGuard, KeyEntry)> {
David Drysdale541846b2024-05-23 13:16:07 +01002130 let _wp = wd::watch("KeystoreDB::load_key_entry");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002131
Janis Danisevskis66784c42021-01-27 08:40:25 -08002132 loop {
2133 match self.load_key_entry_internal(
2134 key,
2135 key_type,
2136 load_bits,
2137 caller_uid,
2138 &check_permission,
2139 ) {
2140 Ok(result) => break Ok(result),
2141 Err(e) => {
2142 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01002143 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08002144 continue;
2145 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002146 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002147 }
2148 }
2149 }
2150 }
2151 }
2152
2153 fn load_key_entry_internal(
2154 &mut self,
2155 key: &KeyDescriptor,
2156 key_type: KeyType,
2157 load_bits: KeyEntryLoadBits,
2158 caller_uid: u32,
2159 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002160 ) -> Result<(KeyIdGuard, KeyEntry)> {
2161 // KEY ID LOCK 1/2
2162 // If we got a key descriptor with a key id we can get the lock right away.
2163 // Otherwise we have to defer it until we know the key id.
2164 let key_id_guard = match key.domain {
2165 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2166 _ => None,
2167 };
2168
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002169 let tx = self
2170 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002171 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002172 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002173
2174 // Load the key_id and complete the access control tuple.
2175 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002176 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002177
2178 // Perform access control. It is vital that we return here if the permission is denied.
2179 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002180 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002181
Janis Danisevskisaec14592020-11-12 09:41:49 -08002182 // KEY ID LOCK 2/2
2183 // If we did not get a key id lock by now, it was because we got a key descriptor
2184 // without a key id. At this point we got the key id, so we can try and get a lock.
2185 // However, we cannot block here, because we are in the middle of the transaction.
2186 // So first we try to get the lock non blocking. If that fails, we roll back the
2187 // transaction and block until we get the lock. After we successfully got the lock,
2188 // we start a new transaction and load the access tuple again.
2189 //
2190 // We don't need to perform access control again, because we already established
2191 // that the caller had access to the given key. But we need to make sure that the
2192 // key id still exists. So we have to load the key entry by key id this time.
2193 let (key_id_guard, tx) = match key_id_guard {
2194 None => match KEY_ID_LOCK.try_get(key_id) {
2195 None => {
2196 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002197 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002198
Janis Danisevskisaec14592020-11-12 09:41:49 -08002199 // Block until we have a key id lock.
2200 let key_id_guard = KEY_ID_LOCK.get(key_id);
2201
2202 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002203 let tx = self
2204 .conn
2205 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002206 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002207
2208 Self::load_access_tuple(
2209 &tx,
2210 // This time we have to load the key by the retrieved key id, because the
2211 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002212 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002213 domain: Domain::KEY_ID,
2214 nspace: key_id,
2215 ..Default::default()
2216 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002217 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002218 caller_uid,
2219 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002220 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002221 (key_id_guard, tx)
2222 }
2223 Some(l) => (l, tx),
2224 },
2225 Some(key_id_guard) => (key_id_guard, tx),
2226 };
2227
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002228 let key_entry =
2229 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002230
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002231 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002232
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002233 Ok((key_id_guard, key_entry))
2234 }
2235
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002236 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002237 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002238 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2239 .context("Trying to delete keyentry.")?;
2240 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2241 .context("Trying to delete keymetadata.")?;
2242 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2243 .context("Trying to delete keyparameters.")?;
2244 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2245 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002246 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002247 }
2248
2249 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002250 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002251 pub fn unbind_key(
2252 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002253 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002254 key_type: KeyType,
2255 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002256 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002257 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002258 let _wp = wd::watch("KeystoreDB::unbind_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002259
David Drysdale7b9ca232024-05-23 18:19:46 +01002260 self.with_transaction(Immediate("TX_unbind_key"), |tx| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002261 let (key_id, access_key_descriptor, access_vector) =
2262 Self::load_access_tuple(tx, key, key_type, caller_uid)
2263 .context("Trying to get access tuple.")?;
2264
2265 // Perform access control. It is vital that we return here if the permission is denied.
2266 // So do not touch that '?' at the end.
2267 check_permission(&access_key_descriptor, access_vector)
2268 .context("While checking permission.")?;
2269
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002270 Self::mark_unreferenced(tx, key_id)
2271 .map(|need_gc| (need_gc, ()))
2272 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002274 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002275 }
2276
Max Bires8e93d2b2021-01-14 13:17:59 -08002277 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2278 tx.query_row(
2279 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2280 params![key_id],
2281 |row| row.get(0),
2282 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002283 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002284 }
2285
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002286 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2287 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2288 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002289 let _wp = wd::watch("KeystoreDB::unbind_keys_for_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002290
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002291 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002292 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002293 }
David Drysdale7b9ca232024-05-23 18:19:46 +01002294 self.with_transaction(Immediate("TX_unbind_keys_for_namespace"), |tx| {
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002295 tx.execute(
2296 "DELETE FROM persistent.keymetadata
2297 WHERE keyentryid IN (
2298 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002299 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002300 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002301 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002302 )
2303 .context("Trying to delete keymetadata.")?;
2304 tx.execute(
2305 "DELETE FROM persistent.keyparameter
2306 WHERE keyentryid IN (
2307 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002308 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002309 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002310 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002311 )
2312 .context("Trying to delete keyparameters.")?;
2313 tx.execute(
2314 "DELETE FROM persistent.grant
2315 WHERE keyentryid IN (
2316 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002317 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002318 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002319 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002320 )
2321 .context("Trying to delete grants.")?;
2322 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002323 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002324 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2325 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002326 )
2327 .context("Trying to delete keyentry.")?;
2328 Ok(()).need_gc()
2329 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002330 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002331 }
2332
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002333 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002334 let _wp = wd::watch("KeystoreDB::cleanup_unreferenced");
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002335 {
2336 tx.execute(
2337 "DELETE FROM persistent.keymetadata
2338 WHERE keyentryid IN (
2339 SELECT id FROM persistent.keyentry
2340 WHERE state = ?
2341 );",
2342 params![KeyLifeCycle::Unreferenced],
2343 )
2344 .context("Trying to delete keymetadata.")?;
2345 tx.execute(
2346 "DELETE FROM persistent.keyparameter
2347 WHERE keyentryid IN (
2348 SELECT id FROM persistent.keyentry
2349 WHERE state = ?
2350 );",
2351 params![KeyLifeCycle::Unreferenced],
2352 )
2353 .context("Trying to delete keyparameters.")?;
2354 tx.execute(
2355 "DELETE FROM persistent.grant
2356 WHERE keyentryid IN (
2357 SELECT id FROM persistent.keyentry
2358 WHERE state = ?
2359 );",
2360 params![KeyLifeCycle::Unreferenced],
2361 )
2362 .context("Trying to delete grants.")?;
2363 tx.execute(
2364 "DELETE FROM persistent.keyentry
2365 WHERE state = ?;",
2366 params![KeyLifeCycle::Unreferenced],
2367 )
2368 .context("Trying to delete keyentry.")?;
2369 Result::<()>::Ok(())
2370 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002371 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002372 }
2373
Hasini Gunasingheda895552021-01-27 19:34:37 +00002374 /// Delete the keys created on behalf of the user, denoted by the user id.
2375 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2376 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2377 /// The caller of this function should notify the gc if the returned value is true.
2378 pub fn unbind_keys_for_user(
2379 &mut self,
2380 user_id: u32,
2381 keep_non_super_encrypted_keys: bool,
2382 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002383 let _wp = wd::watch("KeystoreDB::unbind_keys_for_user");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002384
David Drysdale7b9ca232024-05-23 18:19:46 +01002385 self.with_transaction(Immediate("TX_unbind_keys_for_user"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00002386 let mut stmt = tx
2387 .prepare(&format!(
2388 "SELECT id from persistent.keyentry
2389 WHERE (
2390 key_type = ?
2391 AND domain = ?
2392 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2393 AND state = ?
2394 ) OR (
2395 key_type = ?
2396 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002397 AND state = ?
2398 );",
2399 aid_user_offset = AID_USER_OFFSET
2400 ))
2401 .context(concat!(
2402 "In unbind_keys_for_user. ",
2403 "Failed to prepare the query to find the keys created by apps."
2404 ))?;
2405
2406 let mut rows = stmt
2407 .query(params![
2408 // WHERE client key:
2409 KeyType::Client,
2410 Domain::APP.0 as u32,
2411 user_id,
2412 KeyLifeCycle::Live,
2413 // OR super key:
2414 KeyType::Super,
2415 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002416 KeyLifeCycle::Live
2417 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002418 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002419
2420 let mut key_ids: Vec<i64> = Vec::new();
2421 db_utils::with_rows_extract_all(&mut rows, |row| {
2422 key_ids
2423 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2424 Ok(())
2425 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002426 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002427
2428 let mut notify_gc = false;
2429 for key_id in key_ids {
2430 if keep_non_super_encrypted_keys {
2431 // Load metadata and filter out non-super-encrypted keys.
2432 if let (_, Some((_, blob_metadata)), _, _) =
2433 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002434 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002435 {
2436 if blob_metadata.encrypted_by().is_none() {
2437 continue;
2438 }
2439 }
2440 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002441 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002442 .context("In unbind_keys_for_user.")?
2443 || notify_gc;
2444 }
2445 Ok(()).do_gc(notify_gc)
2446 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002447 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002448 }
2449
Eric Biggersb0478cf2023-10-27 03:55:29 +00002450 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2451 /// This runs when the user's lock screen is being changed to Swipe or None.
2452 ///
2453 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2454 /// such keys also require user authentication. Keystore's concept of user authentication is
2455 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2456 /// authentication is no longer possible. In contrast, keys that just require that the device
2457 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2458 /// is always considered "unlocked" in that case.
2459 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002460 let _wp = wd::watch("KeystoreDB::unbind_auth_bound_keys_for_user");
Eric Biggersb0478cf2023-10-27 03:55:29 +00002461
David Drysdale7b9ca232024-05-23 18:19:46 +01002462 self.with_transaction(Immediate("TX_unbind_auth_bound_keys_for_user"), |tx| {
Eric Biggersb0478cf2023-10-27 03:55:29 +00002463 let mut stmt = tx
2464 .prepare(&format!(
2465 "SELECT id from persistent.keyentry
2466 WHERE key_type = ?
2467 AND domain = ?
2468 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2469 AND state = ?;",
2470 aid_user_offset = AID_USER_OFFSET
2471 ))
2472 .context(concat!(
2473 "In unbind_auth_bound_keys_for_user. ",
2474 "Failed to prepare the query to find the keys created by apps."
2475 ))?;
2476
2477 let mut rows = stmt
2478 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2479 .context(ks_err!("Failed to query the keys created by apps."))?;
2480
2481 let mut key_ids: Vec<i64> = Vec::new();
2482 db_utils::with_rows_extract_all(&mut rows, |row| {
2483 key_ids
2484 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2485 Ok(())
2486 })
2487 .context(ks_err!())?;
2488
2489 let mut notify_gc = false;
2490 let mut num_unbound = 0;
2491 for key_id in key_ids {
2492 // Load the key parameters and filter out non-auth-bound keys. To identify
2493 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2494 // could also be used, but UserSecureID is what Keystore treats as authoritative
2495 // when actually enforcing the key parameters (it might not matter, though).
2496 let params = Self::load_key_parameters(key_id, tx)
2497 .context("Failed to load key parameters.")?;
2498 let is_auth_bound_key = params.iter().any(|kp| {
2499 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2500 });
2501 if is_auth_bound_key {
2502 notify_gc = Self::mark_unreferenced(tx, key_id)
2503 .context("In unbind_auth_bound_keys_for_user.")?
2504 || notify_gc;
2505 num_unbound += 1;
2506 }
2507 }
2508 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2509 Ok(()).do_gc(notify_gc)
2510 })
2511 .context(ks_err!())
2512 }
2513
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002514 fn load_key_components(
2515 tx: &Transaction,
2516 load_bits: KeyEntryLoadBits,
2517 key_id: i64,
2518 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002519 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002520
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002521 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002522 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002523
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002524 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002525 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002526
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002527 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002528 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002529
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002530 Ok(KeyEntry {
2531 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002532 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002533 cert: cert_blob,
2534 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002535 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002536 parameters,
2537 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002538 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002539 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002540 }
2541
Eran Messeri24f31972023-01-25 17:00:33 +00002542 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2543 /// aliases are greater than the specified 'start_past_alias'. If no value
2544 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002545 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002546 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002547 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002548 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002549 &mut self,
2550 domain: Domain,
2551 namespace: i64,
2552 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002553 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002554 ) -> Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002555 let _wp = wd::watch("KeystoreDB::list_past_alias");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002556
Eran Messeri24f31972023-01-25 17:00:33 +00002557 let query = format!(
2558 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002559 WHERE domain = ?
2560 AND namespace = ?
2561 AND alias IS NOT NULL
2562 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002563 AND key_type = ?
2564 {}
2565 ORDER BY alias ASC;",
2566 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2567 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002568
Eran Messeri24f31972023-01-25 17:00:33 +00002569 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2570 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2571
2572 let mut rows = match start_past_alias {
2573 Some(past_alias) => stmt
2574 .query(params![
2575 domain.0 as u32,
2576 namespace,
2577 KeyLifeCycle::Live,
2578 key_type,
2579 past_alias
2580 ])
2581 .context(ks_err!("Failed to query."))?,
2582 None => stmt
2583 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2584 .context(ks_err!("Failed to query."))?,
2585 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002586
Janis Danisevskis66784c42021-01-27 08:40:25 -08002587 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2588 db_utils::with_rows_extract_all(&mut rows, |row| {
2589 descriptors.push(KeyDescriptor {
2590 domain,
2591 nspace: namespace,
2592 alias: Some(row.get(0).context("Trying to extract alias.")?),
2593 blob: None,
2594 });
2595 Ok(())
2596 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002597 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002598 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002599 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002600 }
2601
Eran Messeri24f31972023-01-25 17:00:33 +00002602 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2603 /// Domain must be APP or SELINUX, the caller must make sure of that.
2604 pub fn count_keys(
2605 &mut self,
2606 domain: Domain,
2607 namespace: i64,
2608 key_type: KeyType,
2609 ) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01002610 let _wp = wd::watch("KeystoreDB::countKeys");
Eran Messeri24f31972023-01-25 17:00:33 +00002611
2612 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2613 tx.query_row(
2614 "SELECT COUNT(alias) FROM persistent.keyentry
2615 WHERE domain = ?
2616 AND namespace = ?
2617 AND alias IS NOT NULL
2618 AND state = ?
2619 AND key_type = ?;",
2620 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2621 |row| row.get(0),
2622 )
2623 .context(ks_err!("Failed to count number of keys."))
2624 .no_gc()
2625 })?;
2626 Ok(num_keys)
2627 }
2628
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002629 /// Adds a grant to the grant table.
2630 /// Like `load_key_entry` this function loads the access tuple before
2631 /// it uses the callback for a permission check. Upon success,
2632 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2633 /// grant table. The new row will have a randomized id, which is used as
2634 /// grant id in the namespace field of the resulting KeyDescriptor.
2635 pub fn grant(
2636 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002637 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002638 caller_uid: u32,
2639 grantee_uid: u32,
2640 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002641 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002642 ) -> Result<KeyDescriptor> {
David Drysdale541846b2024-05-23 13:16:07 +01002643 let _wp = wd::watch("KeystoreDB::grant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002644
David Drysdale7b9ca232024-05-23 18:19:46 +01002645 self.with_transaction(Immediate("TX_grant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002646 // Load the key_id and complete the access control tuple.
2647 // We ignore the access vector here because grants cannot be granted.
2648 // The access vector returned here expresses the permissions the
2649 // grantee has if key.domain == Domain::GRANT. But this vector
2650 // cannot include the grant permission by design, so there is no way the
2651 // subsequent permission check can pass.
2652 // We could check key.domain == Domain::GRANT and fail early.
2653 // But even if we load the access tuple by grant here, the permission
2654 // check denies the attempt to create a grant by grant descriptor.
2655 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002656 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002657
Janis Danisevskis66784c42021-01-27 08:40:25 -08002658 // Perform access control. It is vital that we return here if the permission
2659 // was denied. So do not touch that '?' at the end of the line.
2660 // This permission check checks if the caller has the grant permission
2661 // for the given key and in addition to all of the permissions
2662 // expressed in `access_vector`.
2663 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002664 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002665
Janis Danisevskis66784c42021-01-27 08:40:25 -08002666 let grant_id = if let Some(grant_id) = tx
2667 .query_row(
2668 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002669 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002670 params![key_id, grantee_uid],
2671 |row| row.get(0),
2672 )
2673 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002674 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002675 {
2676 tx.execute(
2677 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002678 SET access_vector = ?
2679 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002680 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002681 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002682 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002683 grant_id
2684 } else {
2685 Self::insert_with_retry(|id| {
2686 tx.execute(
2687 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2688 VALUES (?, ?, ?, ?);",
2689 params![id, grantee_uid, key_id, i32::from(access_vector)],
2690 )
2691 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002692 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002693 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002694
Janis Danisevskis66784c42021-01-27 08:40:25 -08002695 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002696 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002697 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002698 }
2699
2700 /// This function checks permissions like `grant` and `load_key_entry`
2701 /// before removing a grant from the grant table.
2702 pub fn ungrant(
2703 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002704 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002705 caller_uid: u32,
2706 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002707 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002708 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002709 let _wp = wd::watch("KeystoreDB::ungrant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002710
David Drysdale7b9ca232024-05-23 18:19:46 +01002711 self.with_transaction(Immediate("TX_ungrant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002712 // Load the key_id and complete the access control tuple.
2713 // We ignore the access vector here because grants cannot be granted.
2714 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002715 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002716
Janis Danisevskis66784c42021-01-27 08:40:25 -08002717 // Perform access control. We must return here if the permission
2718 // was denied. So do not touch the '?' at the end of this line.
2719 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002720 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002721
Janis Danisevskis66784c42021-01-27 08:40:25 -08002722 tx.execute(
2723 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002724 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002725 params![key_id, grantee_uid],
2726 )
2727 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002728
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002729 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002730 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002731 }
2732
Joel Galenson845f74b2020-09-09 14:11:55 -07002733 // Generates a random id and passes it to the given function, which will
2734 // try to insert it into a database. If that insertion fails, retry;
2735 // otherwise return the id.
2736 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2737 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002738 let newid: i64 = match random() {
2739 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2740 i => i,
2741 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002742 match inserter(newid) {
2743 // If the id already existed, try again.
2744 Err(rusqlite::Error::SqliteFailure(
2745 libsqlite3_sys::Error {
2746 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2747 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2748 },
2749 _,
2750 )) => (),
2751 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002752 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002753 }
2754 _ => return Ok(newid),
2755 }
2756 }
2757 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002758
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002759 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2760 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002761 self.perboot
2762 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002763 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002764
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002765 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002766 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002767 where
2768 F: Fn(&AuthTokenEntry) -> bool,
2769 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002770 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002771 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002772
2773 /// Load descriptor of a key by key id
2774 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002775 let _wp = wd::watch("KeystoreDB::load_key_descriptor");
Pavel Grafovf45034a2021-05-12 22:35:45 +01002776
2777 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2778 tx.query_row(
2779 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2780 params![key_id],
2781 |row| {
2782 Ok(KeyDescriptor {
2783 domain: Domain(row.get(0)?),
2784 nspace: row.get(1)?,
2785 alias: row.get(2)?,
2786 blob: None,
2787 })
2788 },
2789 )
2790 .optional()
2791 .context("Trying to load key descriptor")
2792 .no_gc()
2793 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002794 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002795 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002796
2797 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2798 /// (for the given user_id).
2799 /// This is helpful for finding out which apps will have their keys invalidated when
2800 /// the user changes biometrics enrollment or removes their LSKF.
2801 pub fn get_app_uids_affected_by_sid(
2802 &mut self,
2803 user_id: i32,
2804 secure_user_id: i64,
2805 ) -> Result<Vec<i64>> {
David Drysdale541846b2024-05-23 13:16:07 +01002806 let _wp = wd::watch("KeystoreDB::get_app_uids_affected_by_sid");
Eran Messeri4dc27b52024-01-09 12:43:31 +00002807
David Drysdale7b9ca232024-05-23 18:19:46 +01002808 let ids = self.with_transaction(Immediate("TX_get_app_uids_affected_by_sid"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002809 let mut stmt = tx
2810 .prepare(&format!(
2811 "SELECT id, namespace from persistent.keyentry
2812 WHERE key_type = ?
2813 AND domain = ?
2814 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2815 AND state = ?;",
2816 ))
2817 .context(concat!(
2818 "In get_app_uids_affected_by_sid, ",
2819 "failed to prepare the query to find the keys created by apps."
2820 ))?;
2821
2822 let mut rows = stmt
2823 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2824 .context(ks_err!("Failed to query the keys created by apps."))?;
2825
2826 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2827 db_utils::with_rows_extract_all(&mut rows, |row| {
2828 key_ids_and_app_uids.insert(
2829 row.get(0).context("Failed to read key id of a key created by an app.")?,
2830 row.get(1).context("Failed to read the app uid")?,
2831 );
2832 Ok(())
2833 })?;
2834 Ok(key_ids_and_app_uids).no_gc()
2835 })?;
2836 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
David Drysdale7b9ca232024-05-23 18:19:46 +01002837 for (key_id, app_uid) in ids {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002838 // Read the key parameters for each key in its own transaction. It is OK to ignore
2839 // an error to get the properties of a particular key since it might have been deleted
2840 // under our feet after the previous transaction concluded. If the key was deleted
2841 // then it is no longer applicable if it was auth-bound or not.
2842 if let Ok(is_key_bound_to_sid) =
David Drysdale7b9ca232024-05-23 18:19:46 +01002843 self.with_transaction(Immediate("TX_get_app_uids_affects_by_sid 2"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002844 let params = Self::load_key_parameters(key_id, tx)
2845 .context("Failed to load key parameters.")?;
2846 // Check if the key is bound to this secure user ID.
2847 let is_key_bound_to_sid = params.iter().any(|kp| {
2848 matches!(
2849 kp.key_parameter_value(),
2850 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2851 )
2852 });
2853 Ok(is_key_bound_to_sid).no_gc()
2854 })
2855 {
2856 if is_key_bound_to_sid {
2857 app_uids_affected_by_sid.insert(app_uid);
2858 }
2859 }
2860 }
2861
2862 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2863 Ok(app_uids_vec)
2864 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002865}
2866
2867#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002868pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002869
2870 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002871 use crate::key_parameter::{
2872 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2873 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2874 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002875 use crate::key_perm_set;
2876 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002877 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002878 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002879 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2880 HardwareAuthToken::HardwareAuthToken,
2881 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002882 };
2883 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002884 Timestamp::Timestamp,
2885 };
Joel Galenson0891bc12020-07-20 10:37:03 -07002886 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002887 use std::collections::BTreeMap;
2888 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002889 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002890 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002891 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002892 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002893 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002894 #[cfg(disabled)]
2895 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002896
Seth Moore7ee79f92021-12-07 11:42:49 -08002897 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002898 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002899
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002900 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
David Drysdale7b9ca232024-05-23 18:19:46 +01002901 db.with_transaction(Immediate("TX_new_test_db"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002902 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002903 })?;
2904 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002905 }
2906
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002907 fn rebind_alias(
2908 db: &mut KeystoreDB,
2909 newid: &KeyIdGuard,
2910 alias: &str,
2911 domain: Domain,
2912 namespace: i64,
2913 ) -> Result<bool> {
David Drysdale7b9ca232024-05-23 18:19:46 +01002914 db.with_transaction(Immediate("TX_rebind_alias"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002915 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002916 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002917 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002918 }
2919
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002920 #[test]
2921 fn datetime() -> Result<()> {
2922 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002923 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002924 let now = SystemTime::now();
2925 let duration = Duration::from_secs(1000);
2926 let then = now.checked_sub(duration).unwrap();
2927 let soon = now.checked_add(duration).unwrap();
2928 conn.execute(
2929 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2930 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2931 )?;
2932 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002933 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002934 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2935 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2936 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2937 assert!(rows.next()?.is_none());
2938 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2939 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2940 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2941 Ok(())
2942 }
2943
Joel Galenson0891bc12020-07-20 10:37:03 -07002944 // Ensure that we're using the "injected" random function, not the real one.
2945 #[test]
2946 fn test_mocked_random() {
2947 let rand1 = random();
2948 let rand2 = random();
2949 let rand3 = random();
2950 if rand1 == rand2 {
2951 assert_eq!(rand2 + 1, rand3);
2952 } else {
2953 assert_eq!(rand1 + 1, rand2);
2954 assert_eq!(rand2, rand3);
2955 }
2956 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002957
Joel Galenson26f4d012020-07-17 14:57:21 -07002958 // Test that we have the correct tables.
2959 #[test]
2960 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002961 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002962 let tables = db
2963 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002964 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002965 .query_map(params![], |row| row.get(0))?
2966 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002967 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002968 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002969 assert_eq!(tables[1], "blobmetadata");
2970 assert_eq!(tables[2], "grant");
2971 assert_eq!(tables[3], "keyentry");
2972 assert_eq!(tables[4], "keymetadata");
2973 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07002974 Ok(())
2975 }
2976
2977 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002978 fn test_auth_token_table_invariant() -> Result<()> {
2979 let mut db = new_test_db()?;
2980 let auth_token1 = HardwareAuthToken {
2981 challenge: i64::MAX,
2982 userId: 200,
2983 authenticatorId: 200,
2984 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2985 timestamp: Timestamp { milliSeconds: 500 },
2986 mac: String::from("mac").into_bytes(),
2987 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002988 db.insert_auth_token(&auth_token1);
2989 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002990 assert_eq!(auth_tokens_returned.len(), 1);
2991
2992 // insert another auth token with the same values for the columns in the UNIQUE constraint
2993 // of the auth token table and different value for timestamp
2994 let auth_token2 = HardwareAuthToken {
2995 challenge: i64::MAX,
2996 userId: 200,
2997 authenticatorId: 200,
2998 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2999 timestamp: Timestamp { milliSeconds: 600 },
3000 mac: String::from("mac").into_bytes(),
3001 };
3002
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003003 db.insert_auth_token(&auth_token2);
3004 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003005 assert_eq!(auth_tokens_returned.len(), 1);
3006
3007 if let Some(auth_token) = auth_tokens_returned.pop() {
3008 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3009 }
3010
3011 // insert another auth token with the different values for the columns in the UNIQUE
3012 // constraint of the auth token table
3013 let auth_token3 = HardwareAuthToken {
3014 challenge: i64::MAX,
3015 userId: 201,
3016 authenticatorId: 200,
3017 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3018 timestamp: Timestamp { milliSeconds: 600 },
3019 mac: String::from("mac").into_bytes(),
3020 };
3021
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003022 db.insert_auth_token(&auth_token3);
3023 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003024 assert_eq!(auth_tokens_returned.len(), 2);
3025
3026 Ok(())
3027 }
3028
3029 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003030 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3031 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003032 }
3033
David Drysdale8c4c4f32023-10-31 12:14:11 +00003034 fn create_key_entry(
3035 db: &mut KeystoreDB,
3036 domain: &Domain,
3037 namespace: &i64,
3038 key_type: KeyType,
3039 km_uuid: &Uuid,
3040 ) -> Result<KeyIdGuard> {
David Drysdale7b9ca232024-05-23 18:19:46 +01003041 db.with_transaction(Immediate("TX_create_key_entry"), |tx| {
David Drysdale8c4c4f32023-10-31 12:14:11 +00003042 KeystoreDB::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
3043 })
3044 }
3045
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003046 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003047 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003048 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003049 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003050
David Drysdale8c4c4f32023-10-31 12:14:11 +00003051 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003052 let entries = get_keyentry(&db)?;
3053 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003054
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003055 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003056
3057 let entries_new = get_keyentry(&db)?;
3058 assert_eq!(entries, entries_new);
3059 Ok(())
3060 }
3061
3062 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003063 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003064 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3065 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003066 }
3067
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003068 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003069
David Drysdale8c4c4f32023-10-31 12:14:11 +00003070 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3071 create_key_entry(&mut db, &Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003072
3073 let entries = get_keyentry(&db)?;
3074 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003075 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3076 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003077
3078 // Test that we must pass in a valid Domain.
3079 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003080 create_key_entry(&mut db, &Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003081 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003082 );
3083 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003084 create_key_entry(&mut db, &Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003085 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003086 );
3087 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003088 create_key_entry(&mut db, &Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003089 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003090 );
3091
3092 Ok(())
3093 }
3094
Joel Galenson33c04ad2020-08-03 11:04:38 -07003095 #[test]
3096 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003097 fn extractor(
3098 ke: &KeyEntryRow,
3099 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3100 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003101 }
3102
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003103 let mut db = new_test_db()?;
David Drysdale8c4c4f32023-10-31 12:14:11 +00003104 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3105 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003106 let entries = get_keyentry(&db)?;
3107 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003108 assert_eq!(
3109 extractor(&entries[0]),
3110 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3111 );
3112 assert_eq!(
3113 extractor(&entries[1]),
3114 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3115 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003116
3117 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003118 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003119 let entries = get_keyentry(&db)?;
3120 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003121 assert_eq!(
3122 extractor(&entries[0]),
3123 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3124 );
3125 assert_eq!(
3126 extractor(&entries[1]),
3127 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3128 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003129
3130 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003131 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003132 let entries = get_keyentry(&db)?;
3133 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003134 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3135 assert_eq!(
3136 extractor(&entries[1]),
3137 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3138 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003139
3140 // Test that we must pass in a valid Domain.
3141 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003142 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003143 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003144 );
3145 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003146 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003147 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003148 );
3149 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003150 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003151 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003152 );
3153
3154 // Test that we correctly handle setting an alias for something that does not exist.
3155 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003156 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003157 "Expected to update a single entry but instead updated 0",
3158 );
3159 // Test that we correctly abort the transaction in this case.
3160 let entries = get_keyentry(&db)?;
3161 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003162 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3163 assert_eq!(
3164 extractor(&entries[1]),
3165 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3166 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003167
3168 Ok(())
3169 }
3170
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003171 #[test]
3172 fn test_grant_ungrant() -> Result<()> {
3173 const CALLER_UID: u32 = 15;
3174 const GRANTEE_UID: u32 = 12;
3175 const SELINUX_NAMESPACE: i64 = 7;
3176
3177 let mut db = new_test_db()?;
3178 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003179 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3180 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3181 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003182 )?;
3183 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003184 domain: super::Domain::APP,
3185 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003186 alias: Some("key".to_string()),
3187 blob: None,
3188 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003189 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3190 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003191
3192 // Reset totally predictable random number generator in case we
3193 // are not the first test running on this thread.
3194 reset_random();
3195 let next_random = 0i64;
3196
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003197 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003198 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003199 assert_eq!(*a, PVEC1);
3200 assert_eq!(
3201 *k,
3202 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003203 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003204 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003205 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003206 alias: Some("key".to_string()),
3207 blob: None,
3208 }
3209 );
3210 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003211 })
3212 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003213
3214 assert_eq!(
3215 app_granted_key,
3216 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003217 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003218 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003219 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003220 alias: None,
3221 blob: None,
3222 }
3223 );
3224
3225 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003226 domain: super::Domain::SELINUX,
3227 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003228 alias: Some("yek".to_string()),
3229 blob: None,
3230 };
3231
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003232 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003233 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003234 assert_eq!(*a, PVEC1);
3235 assert_eq!(
3236 *k,
3237 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003238 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003239 // namespace must be the supplied SELinux
3240 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003241 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003242 alias: Some("yek".to_string()),
3243 blob: None,
3244 }
3245 );
3246 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003247 })
3248 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003249
3250 assert_eq!(
3251 selinux_granted_key,
3252 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003253 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003254 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003255 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003256 alias: None,
3257 blob: None,
3258 }
3259 );
3260
3261 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003262 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003263 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003264 assert_eq!(*a, PVEC2);
3265 assert_eq!(
3266 *k,
3267 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003268 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003269 // namespace must be the supplied SELinux
3270 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003271 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003272 alias: Some("yek".to_string()),
3273 blob: None,
3274 }
3275 );
3276 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003277 })
3278 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003279
3280 assert_eq!(
3281 selinux_granted_key,
3282 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003283 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003284 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003285 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003286 alias: None,
3287 blob: None,
3288 }
3289 );
3290
3291 {
3292 // Limiting scope of stmt, because it borrows db.
3293 let mut stmt = db
3294 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003295 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003296 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3297 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3298 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003299
3300 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003301 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003302 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003303 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003304 assert!(rows.next().is_none());
3305 }
3306
3307 debug_dump_keyentry_table(&mut db)?;
3308 println!("app_key {:?}", app_key);
3309 println!("selinux_key {:?}", selinux_key);
3310
Janis Danisevskis66784c42021-01-27 08:40:25 -08003311 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3312 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003313
3314 Ok(())
3315 }
3316
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003317 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003318 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3319 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3320
3321 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003322 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003323 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003324 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003325 let mut blob_metadata = BlobMetaData::new();
3326 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3327 db.set_blob(
3328 &key_id,
3329 SubComponentType::KEY_BLOB,
3330 Some(TEST_KEY_BLOB),
3331 Some(&blob_metadata),
3332 )?;
3333 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3334 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003335 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003336
3337 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003338 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003339 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003340 )?;
3341 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003342 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003343 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003344 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003345 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003346 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003347 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003348 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003349 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003350 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003351
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003352 drop(rows);
3353 drop(stmt);
3354
3355 assert_eq!(
David Drysdale7b9ca232024-05-23 18:19:46 +01003356 db.with_transaction(Immediate("TX_test"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003357 BlobMetaData::load_from_db(id, tx).no_gc()
3358 })
3359 .expect("Should find blob metadata."),
3360 blob_metadata
3361 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003362 Ok(())
3363 }
3364
3365 static TEST_ALIAS: &str = "my super duper key";
3366
3367 #[test]
3368 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3369 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003370 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003371 .context("test_insert_and_load_full_keyentry_domain_app")?
3372 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003373 let (_key_guard, key_entry) = db
3374 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003375 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003376 domain: Domain::APP,
3377 nspace: 0,
3378 alias: Some(TEST_ALIAS.to_string()),
3379 blob: None,
3380 },
3381 KeyType::Client,
3382 KeyEntryLoadBits::BOTH,
3383 1,
3384 |_k, _av| Ok(()),
3385 )
3386 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003387 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003388
3389 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003390 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003391 domain: Domain::APP,
3392 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003393 alias: Some(TEST_ALIAS.to_string()),
3394 blob: None,
3395 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003396 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003397 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003398 |_, _| Ok(()),
3399 )
3400 .unwrap();
3401
3402 assert_eq!(
3403 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3404 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003405 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003406 domain: Domain::APP,
3407 nspace: 0,
3408 alias: Some(TEST_ALIAS.to_string()),
3409 blob: None,
3410 },
3411 KeyType::Client,
3412 KeyEntryLoadBits::NONE,
3413 1,
3414 |_k, _av| Ok(()),
3415 )
3416 .unwrap_err()
3417 .root_cause()
3418 .downcast_ref::<KsError>()
3419 );
3420
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003421 Ok(())
3422 }
3423
3424 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003425 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3426 let mut db = new_test_db()?;
3427
3428 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003429 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003430 domain: Domain::APP,
3431 nspace: 1,
3432 alias: Some(TEST_ALIAS.to_string()),
3433 blob: None,
3434 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003435 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003436 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003437 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003438 )
3439 .expect("Trying to insert cert.");
3440
3441 let (_key_guard, mut key_entry) = db
3442 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003443 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003444 domain: Domain::APP,
3445 nspace: 1,
3446 alias: Some(TEST_ALIAS.to_string()),
3447 blob: None,
3448 },
3449 KeyType::Client,
3450 KeyEntryLoadBits::PUBLIC,
3451 1,
3452 |_k, _av| Ok(()),
3453 )
3454 .expect("Trying to read certificate entry.");
3455
3456 assert!(key_entry.pure_cert());
3457 assert!(key_entry.cert().is_none());
3458 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3459
3460 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003461 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003462 domain: Domain::APP,
3463 nspace: 1,
3464 alias: Some(TEST_ALIAS.to_string()),
3465 blob: None,
3466 },
3467 KeyType::Client,
3468 1,
3469 |_, _| Ok(()),
3470 )
3471 .unwrap();
3472
3473 assert_eq!(
3474 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3475 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003476 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003477 domain: Domain::APP,
3478 nspace: 1,
3479 alias: Some(TEST_ALIAS.to_string()),
3480 blob: None,
3481 },
3482 KeyType::Client,
3483 KeyEntryLoadBits::NONE,
3484 1,
3485 |_k, _av| Ok(()),
3486 )
3487 .unwrap_err()
3488 .root_cause()
3489 .downcast_ref::<KsError>()
3490 );
3491
3492 Ok(())
3493 }
3494
3495 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003496 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3497 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003498 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003499 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3500 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003501 let (_key_guard, key_entry) = db
3502 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003503 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003504 domain: Domain::SELINUX,
3505 nspace: 1,
3506 alias: Some(TEST_ALIAS.to_string()),
3507 blob: None,
3508 },
3509 KeyType::Client,
3510 KeyEntryLoadBits::BOTH,
3511 1,
3512 |_k, _av| Ok(()),
3513 )
3514 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003515 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003516
3517 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003518 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003519 domain: Domain::SELINUX,
3520 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003521 alias: Some(TEST_ALIAS.to_string()),
3522 blob: None,
3523 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003524 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003525 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003526 |_, _| Ok(()),
3527 )
3528 .unwrap();
3529
3530 assert_eq!(
3531 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3532 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003533 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003534 domain: Domain::SELINUX,
3535 nspace: 1,
3536 alias: Some(TEST_ALIAS.to_string()),
3537 blob: None,
3538 },
3539 KeyType::Client,
3540 KeyEntryLoadBits::NONE,
3541 1,
3542 |_k, _av| Ok(()),
3543 )
3544 .unwrap_err()
3545 .root_cause()
3546 .downcast_ref::<KsError>()
3547 );
3548
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003549 Ok(())
3550 }
3551
3552 #[test]
3553 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3554 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003555 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003556 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3557 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003558 let (_, key_entry) = db
3559 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003560 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003561 KeyType::Client,
3562 KeyEntryLoadBits::BOTH,
3563 1,
3564 |_k, _av| Ok(()),
3565 )
3566 .unwrap();
3567
Qi Wub9433b52020-12-01 14:52:46 +08003568 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003569
3570 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003571 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003572 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003573 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003574 |_, _| Ok(()),
3575 )
3576 .unwrap();
3577
3578 assert_eq!(
3579 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3580 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003581 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003582 KeyType::Client,
3583 KeyEntryLoadBits::NONE,
3584 1,
3585 |_k, _av| Ok(()),
3586 )
3587 .unwrap_err()
3588 .root_cause()
3589 .downcast_ref::<KsError>()
3590 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003591
3592 Ok(())
3593 }
3594
3595 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003596 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3597 let mut db = new_test_db()?;
3598 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3599 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3600 .0;
3601 // Update the usage count of the limited use key.
3602 db.check_and_update_key_usage_count(key_id)?;
3603
3604 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003605 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003606 KeyType::Client,
3607 KeyEntryLoadBits::BOTH,
3608 1,
3609 |_k, _av| Ok(()),
3610 )?;
3611
3612 // The usage count is decremented now.
3613 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3614
3615 Ok(())
3616 }
3617
3618 #[test]
3619 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3620 let mut db = new_test_db()?;
3621 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3622 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3623 .0;
3624 // Update the usage count of the limited use key.
3625 db.check_and_update_key_usage_count(key_id).expect(concat!(
3626 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3627 "This should succeed."
3628 ));
3629
3630 // Try to update the exhausted limited use key.
3631 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3632 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3633 "This should fail."
3634 ));
3635 assert_eq!(
3636 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3637 e.root_cause().downcast_ref::<KsError>().unwrap()
3638 );
3639
3640 Ok(())
3641 }
3642
3643 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003644 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3645 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003646 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003647 .context("test_insert_and_load_full_keyentry_from_grant")?
3648 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003649
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003650 let granted_key = db
3651 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003652 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003653 domain: Domain::APP,
3654 nspace: 0,
3655 alias: Some(TEST_ALIAS.to_string()),
3656 blob: None,
3657 },
3658 1,
3659 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003660 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003661 |_k, _av| Ok(()),
3662 )
3663 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003664
3665 debug_dump_grant_table(&mut db)?;
3666
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003667 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003668 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3669 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003670 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003671 Ok(())
3672 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003673 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003674
Qi Wub9433b52020-12-01 14:52:46 +08003675 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003676
Janis Danisevskis66784c42021-01-27 08:40:25 -08003677 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003678
3679 assert_eq!(
3680 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3681 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003682 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003683 KeyType::Client,
3684 KeyEntryLoadBits::NONE,
3685 2,
3686 |_k, _av| Ok(()),
3687 )
3688 .unwrap_err()
3689 .root_cause()
3690 .downcast_ref::<KsError>()
3691 );
3692
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003693 Ok(())
3694 }
3695
Janis Danisevskis45760022021-01-19 16:34:10 -08003696 // This test attempts to load a key by key id while the caller is not the owner
3697 // but a grant exists for the given key and the caller.
3698 #[test]
3699 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3700 let mut db = new_test_db()?;
3701 const OWNER_UID: u32 = 1u32;
3702 const GRANTEE_UID: u32 = 2u32;
3703 const SOMEONE_ELSE_UID: u32 = 3u32;
3704 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3705 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3706 .0;
3707
3708 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003709 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003710 domain: Domain::APP,
3711 nspace: 0,
3712 alias: Some(TEST_ALIAS.to_string()),
3713 blob: None,
3714 },
3715 OWNER_UID,
3716 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003717 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003718 |_k, _av| Ok(()),
3719 )
3720 .unwrap();
3721
3722 debug_dump_grant_table(&mut db)?;
3723
3724 let id_descriptor =
3725 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3726
3727 let (_, key_entry) = db
3728 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003729 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003730 KeyType::Client,
3731 KeyEntryLoadBits::BOTH,
3732 GRANTEE_UID,
3733 |k, av| {
3734 assert_eq!(Domain::APP, k.domain);
3735 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003736 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003737 Ok(())
3738 },
3739 )
3740 .unwrap();
3741
3742 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3743
3744 let (_, key_entry) = db
3745 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003746 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003747 KeyType::Client,
3748 KeyEntryLoadBits::BOTH,
3749 SOMEONE_ELSE_UID,
3750 |k, av| {
3751 assert_eq!(Domain::APP, k.domain);
3752 assert_eq!(OWNER_UID as i64, k.nspace);
3753 assert!(av.is_none());
3754 Ok(())
3755 },
3756 )
3757 .unwrap();
3758
3759 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3760
Janis Danisevskis66784c42021-01-27 08:40:25 -08003761 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003762
3763 assert_eq!(
3764 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3765 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003766 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003767 KeyType::Client,
3768 KeyEntryLoadBits::NONE,
3769 GRANTEE_UID,
3770 |_k, _av| Ok(()),
3771 )
3772 .unwrap_err()
3773 .root_cause()
3774 .downcast_ref::<KsError>()
3775 );
3776
3777 Ok(())
3778 }
3779
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003780 // Creates a key migrates it to a different location and then tries to access it by the old
3781 // and new location.
3782 #[test]
3783 fn test_migrate_key_app_to_app() -> Result<()> {
3784 let mut db = new_test_db()?;
3785 const SOURCE_UID: u32 = 1u32;
3786 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003787 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3788 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003789 let key_id_guard =
3790 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3791 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3792
3793 let source_descriptor: KeyDescriptor = KeyDescriptor {
3794 domain: Domain::APP,
3795 nspace: -1,
3796 alias: Some(SOURCE_ALIAS.to_string()),
3797 blob: None,
3798 };
3799
3800 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3801 domain: Domain::APP,
3802 nspace: -1,
3803 alias: Some(DESTINATION_ALIAS.to_string()),
3804 blob: None,
3805 };
3806
3807 let key_id = key_id_guard.id();
3808
3809 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3810 Ok(())
3811 })
3812 .unwrap();
3813
3814 let (_, key_entry) = db
3815 .load_key_entry(
3816 &destination_descriptor,
3817 KeyType::Client,
3818 KeyEntryLoadBits::BOTH,
3819 DESTINATION_UID,
3820 |k, av| {
3821 assert_eq!(Domain::APP, k.domain);
3822 assert_eq!(DESTINATION_UID as i64, k.nspace);
3823 assert!(av.is_none());
3824 Ok(())
3825 },
3826 )
3827 .unwrap();
3828
3829 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3830
3831 assert_eq!(
3832 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3833 db.load_key_entry(
3834 &source_descriptor,
3835 KeyType::Client,
3836 KeyEntryLoadBits::NONE,
3837 SOURCE_UID,
3838 |_k, _av| Ok(()),
3839 )
3840 .unwrap_err()
3841 .root_cause()
3842 .downcast_ref::<KsError>()
3843 );
3844
3845 Ok(())
3846 }
3847
3848 // Creates a key migrates it to a different location and then tries to access it by the old
3849 // and new location.
3850 #[test]
3851 fn test_migrate_key_app_to_selinux() -> Result<()> {
3852 let mut db = new_test_db()?;
3853 const SOURCE_UID: u32 = 1u32;
3854 const DESTINATION_UID: u32 = 2u32;
3855 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003856 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3857 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003858 let key_id_guard =
3859 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3860 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3861
3862 let source_descriptor: KeyDescriptor = KeyDescriptor {
3863 domain: Domain::APP,
3864 nspace: -1,
3865 alias: Some(SOURCE_ALIAS.to_string()),
3866 blob: None,
3867 };
3868
3869 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3870 domain: Domain::SELINUX,
3871 nspace: DESTINATION_NAMESPACE,
3872 alias: Some(DESTINATION_ALIAS.to_string()),
3873 blob: None,
3874 };
3875
3876 let key_id = key_id_guard.id();
3877
3878 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3879 Ok(())
3880 })
3881 .unwrap();
3882
3883 let (_, key_entry) = db
3884 .load_key_entry(
3885 &destination_descriptor,
3886 KeyType::Client,
3887 KeyEntryLoadBits::BOTH,
3888 DESTINATION_UID,
3889 |k, av| {
3890 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003891 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003892 assert!(av.is_none());
3893 Ok(())
3894 },
3895 )
3896 .unwrap();
3897
3898 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3899
3900 assert_eq!(
3901 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3902 db.load_key_entry(
3903 &source_descriptor,
3904 KeyType::Client,
3905 KeyEntryLoadBits::NONE,
3906 SOURCE_UID,
3907 |_k, _av| Ok(()),
3908 )
3909 .unwrap_err()
3910 .root_cause()
3911 .downcast_ref::<KsError>()
3912 );
3913
3914 Ok(())
3915 }
3916
3917 // Creates two keys and tries to migrate the first to the location of the second which
3918 // is expected to fail.
3919 #[test]
3920 fn test_migrate_key_destination_occupied() -> Result<()> {
3921 let mut db = new_test_db()?;
3922 const SOURCE_UID: u32 = 1u32;
3923 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003924 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3925 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003926 let key_id_guard =
3927 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3928 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3929 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3930 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3931
3932 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3933 domain: Domain::APP,
3934 nspace: -1,
3935 alias: Some(DESTINATION_ALIAS.to_string()),
3936 blob: None,
3937 };
3938
3939 assert_eq!(
3940 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3941 db.migrate_key_namespace(
3942 key_id_guard,
3943 &destination_descriptor,
3944 DESTINATION_UID,
3945 |_k| Ok(())
3946 )
3947 .unwrap_err()
3948 .root_cause()
3949 .downcast_ref::<KsError>()
3950 );
3951
3952 Ok(())
3953 }
3954
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003955 #[test]
3956 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003957 const ALIAS1: &str = "test_upgrade_0_to_1_1";
3958 const ALIAS2: &str = "test_upgrade_0_to_1_2";
3959 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003960 const UID: u32 = 33;
3961 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3962 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3963 let key_id_untouched1 =
3964 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3965 let key_id_untouched2 =
3966 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
3967 let key_id_deleted =
3968 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
3969
3970 let (_, key_entry) = db
3971 .load_key_entry(
3972 &KeyDescriptor {
3973 domain: Domain::APP,
3974 nspace: -1,
3975 alias: Some(ALIAS1.to_string()),
3976 blob: None,
3977 },
3978 KeyType::Client,
3979 KeyEntryLoadBits::BOTH,
3980 UID,
3981 |k, av| {
3982 assert_eq!(Domain::APP, k.domain);
3983 assert_eq!(UID as i64, k.nspace);
3984 assert!(av.is_none());
3985 Ok(())
3986 },
3987 )
3988 .unwrap();
3989 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
3990 let (_, key_entry) = db
3991 .load_key_entry(
3992 &KeyDescriptor {
3993 domain: Domain::APP,
3994 nspace: -1,
3995 alias: Some(ALIAS2.to_string()),
3996 blob: None,
3997 },
3998 KeyType::Client,
3999 KeyEntryLoadBits::BOTH,
4000 UID,
4001 |k, av| {
4002 assert_eq!(Domain::APP, k.domain);
4003 assert_eq!(UID as i64, k.nspace);
4004 assert!(av.is_none());
4005 Ok(())
4006 },
4007 )
4008 .unwrap();
4009 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4010 let (_, key_entry) = db
4011 .load_key_entry(
4012 &KeyDescriptor {
4013 domain: Domain::APP,
4014 nspace: -1,
4015 alias: Some(ALIAS3.to_string()),
4016 blob: None,
4017 },
4018 KeyType::Client,
4019 KeyEntryLoadBits::BOTH,
4020 UID,
4021 |k, av| {
4022 assert_eq!(Domain::APP, k.domain);
4023 assert_eq!(UID as i64, k.nspace);
4024 assert!(av.is_none());
4025 Ok(())
4026 },
4027 )
4028 .unwrap();
4029 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4030
David Drysdale7b9ca232024-05-23 18:19:46 +01004031 db.with_transaction(Immediate("TX_test"), |tx| KeystoreDB::from_0_to_1(tx).no_gc())
4032 .unwrap();
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004033
4034 let (_, key_entry) = db
4035 .load_key_entry(
4036 &KeyDescriptor {
4037 domain: Domain::APP,
4038 nspace: -1,
4039 alias: Some(ALIAS1.to_string()),
4040 blob: None,
4041 },
4042 KeyType::Client,
4043 KeyEntryLoadBits::BOTH,
4044 UID,
4045 |k, av| {
4046 assert_eq!(Domain::APP, k.domain);
4047 assert_eq!(UID as i64, k.nspace);
4048 assert!(av.is_none());
4049 Ok(())
4050 },
4051 )
4052 .unwrap();
4053 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4054 let (_, key_entry) = db
4055 .load_key_entry(
4056 &KeyDescriptor {
4057 domain: Domain::APP,
4058 nspace: -1,
4059 alias: Some(ALIAS2.to_string()),
4060 blob: None,
4061 },
4062 KeyType::Client,
4063 KeyEntryLoadBits::BOTH,
4064 UID,
4065 |k, av| {
4066 assert_eq!(Domain::APP, k.domain);
4067 assert_eq!(UID as i64, k.nspace);
4068 assert!(av.is_none());
4069 Ok(())
4070 },
4071 )
4072 .unwrap();
4073 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4074 assert_eq!(
4075 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4076 db.load_key_entry(
4077 &KeyDescriptor {
4078 domain: Domain::APP,
4079 nspace: -1,
4080 alias: Some(ALIAS3.to_string()),
4081 blob: None,
4082 },
4083 KeyType::Client,
4084 KeyEntryLoadBits::BOTH,
4085 UID,
4086 |k, av| {
4087 assert_eq!(Domain::APP, k.domain);
4088 assert_eq!(UID as i64, k.nspace);
4089 assert!(av.is_none());
4090 Ok(())
4091 },
4092 )
4093 .unwrap_err()
4094 .root_cause()
4095 .downcast_ref::<KsError>()
4096 );
4097 }
4098
Janis Danisevskisaec14592020-11-12 09:41:49 -08004099 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4100
Janis Danisevskisaec14592020-11-12 09:41:49 -08004101 #[test]
4102 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4103 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004104 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4105 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004106 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004107 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004108 .context("test_insert_and_load_full_keyentry_domain_app")?
4109 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004110 let (_key_guard, key_entry) = db
4111 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004112 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004113 domain: Domain::APP,
4114 nspace: 0,
4115 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4116 blob: None,
4117 },
4118 KeyType::Client,
4119 KeyEntryLoadBits::BOTH,
4120 33,
4121 |_k, _av| Ok(()),
4122 )
4123 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004124 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004125 let state = Arc::new(AtomicU8::new(1));
4126 let state2 = state.clone();
4127
4128 // Spawning a second thread that attempts to acquire the key id lock
4129 // for the same key as the primary thread. The primary thread then
4130 // waits, thereby forcing the secondary thread into the second stage
4131 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4132 // The test succeeds if the secondary thread observes the transition
4133 // of `state` from 1 to 2, despite having a whole second to overtake
4134 // the primary thread.
4135 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004136 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004137 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004138 assert!(db
4139 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004140 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004141 domain: Domain::APP,
4142 nspace: 0,
4143 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4144 blob: None,
4145 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004146 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004147 KeyEntryLoadBits::BOTH,
4148 33,
4149 |_k, _av| Ok(()),
4150 )
4151 .is_ok());
4152 // We should only see a 2 here because we can only return
4153 // from load_key_entry when the `_key_guard` expires,
4154 // which happens at the end of the scope.
4155 assert_eq!(2, state2.load(Ordering::Relaxed));
4156 });
4157
4158 thread::sleep(std::time::Duration::from_millis(1000));
4159
4160 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4161
4162 // Return the handle from this scope so we can join with the
4163 // secondary thread after the key id lock has expired.
4164 handle
4165 // This is where the `_key_guard` goes out of scope,
4166 // which is the reason for concurrent load_key_entry on the same key
4167 // to unblock.
4168 };
4169 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4170 // main test thread. We will not see failing asserts in secondary threads otherwise.
4171 handle.join().unwrap();
4172 Ok(())
4173 }
4174
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004175 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004176 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004177 let temp_dir =
4178 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4179
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004180 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4181 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004182
4183 let _tx1 = db1
4184 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004185 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004186 .expect("Failed to create first transaction.");
4187
4188 let error = db2
4189 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004190 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004191 .context("Transaction begin failed.")
4192 .expect_err("This should fail.");
4193 let root_cause = error.root_cause();
4194 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4195 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4196 {
4197 return;
4198 }
4199 panic!(
4200 "Unexpected error {:?} \n{:?} \n{:?}",
4201 error,
4202 root_cause,
4203 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4204 )
4205 }
4206
4207 #[cfg(disabled)]
4208 #[test]
4209 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4210 let temp_dir = Arc::new(
4211 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4212 .expect("Failed to create temp dir."),
4213 );
4214
4215 let test_begin = Instant::now();
4216
Janis Danisevskis66784c42021-01-27 08:40:25 -08004217 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004218 let mut db =
4219 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004220 const OPEN_DB_COUNT: u32 = 50u32;
4221
4222 let mut actual_key_count = KEY_COUNT;
4223 // First insert KEY_COUNT keys.
4224 for count in 0..KEY_COUNT {
4225 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4226 actual_key_count = count;
4227 break;
4228 }
4229 let alias = format!("test_alias_{}", count);
4230 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4231 .expect("Failed to make key entry.");
4232 }
4233
4234 // Insert more keys from a different thread and into a different namespace.
4235 let temp_dir1 = temp_dir.clone();
4236 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004237 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4238 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004239
4240 for count in 0..actual_key_count {
4241 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4242 return;
4243 }
4244 let alias = format!("test_alias_{}", count);
4245 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4246 .expect("Failed to make key entry.");
4247 }
4248
4249 // then unbind them again.
4250 for count in 0..actual_key_count {
4251 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4252 return;
4253 }
4254 let key = KeyDescriptor {
4255 domain: Domain::APP,
4256 nspace: -1,
4257 alias: Some(format!("test_alias_{}", count)),
4258 blob: None,
4259 };
4260 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4261 }
4262 });
4263
4264 // And start unbinding the first set of keys.
4265 let temp_dir2 = temp_dir.clone();
4266 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004267 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4268 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004269
4270 for count in 0..actual_key_count {
4271 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4272 return;
4273 }
4274 let key = KeyDescriptor {
4275 domain: Domain::APP,
4276 nspace: -1,
4277 alias: Some(format!("test_alias_{}", count)),
4278 blob: None,
4279 };
4280 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4281 }
4282 });
4283
Janis Danisevskis66784c42021-01-27 08:40:25 -08004284 // While a lot of inserting and deleting is going on we have to open database connections
4285 // successfully and use them.
4286 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4287 // out of scope.
4288 #[allow(clippy::redundant_clone)]
4289 let temp_dir4 = temp_dir.clone();
4290 let handle4 = thread::spawn(move || {
4291 for count in 0..OPEN_DB_COUNT {
4292 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4293 return;
4294 }
Seth Moore444b51a2021-06-11 09:49:49 -07004295 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4296 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004297
4298 let alias = format!("test_alias_{}", count);
4299 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4300 .expect("Failed to make key entry.");
4301 let key = KeyDescriptor {
4302 domain: Domain::APP,
4303 nspace: -1,
4304 alias: Some(alias),
4305 blob: None,
4306 };
4307 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4308 }
4309 });
4310
4311 handle1.join().expect("Thread 1 panicked.");
4312 handle2.join().expect("Thread 2 panicked.");
4313 handle4.join().expect("Thread 4 panicked.");
4314
Janis Danisevskis66784c42021-01-27 08:40:25 -08004315 Ok(())
4316 }
4317
4318 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004319 fn list() -> Result<()> {
4320 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004321 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004322 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4323 (Domain::APP, 1, "test1"),
4324 (Domain::APP, 1, "test2"),
4325 (Domain::APP, 1, "test3"),
4326 (Domain::APP, 1, "test4"),
4327 (Domain::APP, 1, "test5"),
4328 (Domain::APP, 1, "test6"),
4329 (Domain::APP, 1, "test7"),
4330 (Domain::APP, 2, "test1"),
4331 (Domain::APP, 2, "test2"),
4332 (Domain::APP, 2, "test3"),
4333 (Domain::APP, 2, "test4"),
4334 (Domain::APP, 2, "test5"),
4335 (Domain::APP, 2, "test6"),
4336 (Domain::APP, 2, "test8"),
4337 (Domain::SELINUX, 100, "test1"),
4338 (Domain::SELINUX, 100, "test2"),
4339 (Domain::SELINUX, 100, "test3"),
4340 (Domain::SELINUX, 100, "test4"),
4341 (Domain::SELINUX, 100, "test5"),
4342 (Domain::SELINUX, 100, "test6"),
4343 (Domain::SELINUX, 100, "test9"),
4344 ];
4345
4346 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4347 .iter()
4348 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004349 let entry =
4350 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004351 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4352 });
4353 (entry.id(), *ns)
4354 })
4355 .collect();
4356
4357 for (domain, namespace) in
4358 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4359 {
4360 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4361 .iter()
4362 .filter_map(|(domain, ns, alias)| match ns {
4363 ns if *ns == *namespace => Some(KeyDescriptor {
4364 domain: *domain,
4365 nspace: *ns,
4366 alias: Some(alias.to_string()),
4367 blob: None,
4368 }),
4369 _ => None,
4370 })
4371 .collect();
4372 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004373 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004374 list_result.sort();
4375 assert_eq!(list_o_descriptors, list_result);
4376
4377 let mut list_o_ids: Vec<i64> = list_o_descriptors
4378 .into_iter()
4379 .map(|d| {
4380 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004381 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004382 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004383 KeyType::Client,
4384 KeyEntryLoadBits::NONE,
4385 *namespace as u32,
4386 |_, _| Ok(()),
4387 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004388 .unwrap();
4389 entry.id()
4390 })
4391 .collect();
4392 list_o_ids.sort_unstable();
4393 let mut loaded_entries: Vec<i64> = list_o_keys
4394 .iter()
4395 .filter_map(|(id, ns)| match ns {
4396 ns if *ns == *namespace => Some(*id),
4397 _ => None,
4398 })
4399 .collect();
4400 loaded_entries.sort_unstable();
4401 assert_eq!(list_o_ids, loaded_entries);
4402 }
Eran Messeri24f31972023-01-25 17:00:33 +00004403 assert_eq!(
4404 Vec::<KeyDescriptor>::new(),
4405 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4406 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004407
4408 Ok(())
4409 }
4410
Joel Galenson0891bc12020-07-20 10:37:03 -07004411 // Helpers
4412
4413 // Checks that the given result is an error containing the given string.
4414 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4415 let error_str = format!(
4416 "{:#?}",
4417 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4418 );
4419 assert!(
4420 error_str.contains(target),
4421 "The string \"{}\" should contain \"{}\"",
4422 error_str,
4423 target
4424 );
4425 }
4426
Joel Galenson2aab4432020-07-22 15:27:57 -07004427 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004428 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004429 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004430 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004431 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004432 namespace: Option<i64>,
4433 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004434 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004435 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004436 }
4437
4438 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4439 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004440 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004441 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004442 Ok(KeyEntryRow {
4443 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004444 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004445 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004446 namespace: row.get(3)?,
4447 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004448 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004449 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004450 })
4451 })?
4452 .map(|r| r.context("Could not read keyentry row."))
4453 .collect::<Result<Vec<_>>>()
4454 }
4455
Eran Messeri4dc27b52024-01-09 12:43:31 +00004456 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4457 make_test_params_with_sids(max_usage_count, &[42])
4458 }
4459
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004460 // Note: The parameters and SecurityLevel associations are nonsensical. This
4461 // collection is only used to check if the parameters are preserved as expected by the
4462 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004463 fn make_test_params_with_sids(
4464 max_usage_count: Option<i32>,
4465 user_secure_ids: &[i64],
4466 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004467 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004468 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4469 KeyParameter::new(
4470 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4471 SecurityLevel::TRUSTED_ENVIRONMENT,
4472 ),
4473 KeyParameter::new(
4474 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4475 SecurityLevel::TRUSTED_ENVIRONMENT,
4476 ),
4477 KeyParameter::new(
4478 KeyParameterValue::Algorithm(Algorithm::RSA),
4479 SecurityLevel::TRUSTED_ENVIRONMENT,
4480 ),
4481 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4482 KeyParameter::new(
4483 KeyParameterValue::BlockMode(BlockMode::ECB),
4484 SecurityLevel::TRUSTED_ENVIRONMENT,
4485 ),
4486 KeyParameter::new(
4487 KeyParameterValue::BlockMode(BlockMode::GCM),
4488 SecurityLevel::TRUSTED_ENVIRONMENT,
4489 ),
4490 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4491 KeyParameter::new(
4492 KeyParameterValue::Digest(Digest::MD5),
4493 SecurityLevel::TRUSTED_ENVIRONMENT,
4494 ),
4495 KeyParameter::new(
4496 KeyParameterValue::Digest(Digest::SHA_2_224),
4497 SecurityLevel::TRUSTED_ENVIRONMENT,
4498 ),
4499 KeyParameter::new(
4500 KeyParameterValue::Digest(Digest::SHA_2_256),
4501 SecurityLevel::STRONGBOX,
4502 ),
4503 KeyParameter::new(
4504 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4505 SecurityLevel::TRUSTED_ENVIRONMENT,
4506 ),
4507 KeyParameter::new(
4508 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4509 SecurityLevel::TRUSTED_ENVIRONMENT,
4510 ),
4511 KeyParameter::new(
4512 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4513 SecurityLevel::STRONGBOX,
4514 ),
4515 KeyParameter::new(
4516 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4517 SecurityLevel::TRUSTED_ENVIRONMENT,
4518 ),
4519 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4520 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4521 KeyParameter::new(
4522 KeyParameterValue::EcCurve(EcCurve::P_224),
4523 SecurityLevel::TRUSTED_ENVIRONMENT,
4524 ),
4525 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4526 KeyParameter::new(
4527 KeyParameterValue::EcCurve(EcCurve::P_384),
4528 SecurityLevel::TRUSTED_ENVIRONMENT,
4529 ),
4530 KeyParameter::new(
4531 KeyParameterValue::EcCurve(EcCurve::P_521),
4532 SecurityLevel::TRUSTED_ENVIRONMENT,
4533 ),
4534 KeyParameter::new(
4535 KeyParameterValue::RSAPublicExponent(3),
4536 SecurityLevel::TRUSTED_ENVIRONMENT,
4537 ),
4538 KeyParameter::new(
4539 KeyParameterValue::IncludeUniqueID,
4540 SecurityLevel::TRUSTED_ENVIRONMENT,
4541 ),
4542 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4543 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4544 KeyParameter::new(
4545 KeyParameterValue::ActiveDateTime(1234567890),
4546 SecurityLevel::STRONGBOX,
4547 ),
4548 KeyParameter::new(
4549 KeyParameterValue::OriginationExpireDateTime(1234567890),
4550 SecurityLevel::TRUSTED_ENVIRONMENT,
4551 ),
4552 KeyParameter::new(
4553 KeyParameterValue::UsageExpireDateTime(1234567890),
4554 SecurityLevel::TRUSTED_ENVIRONMENT,
4555 ),
4556 KeyParameter::new(
4557 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4558 SecurityLevel::TRUSTED_ENVIRONMENT,
4559 ),
4560 KeyParameter::new(
4561 KeyParameterValue::MaxUsesPerBoot(1234567890),
4562 SecurityLevel::TRUSTED_ENVIRONMENT,
4563 ),
4564 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004565 KeyParameter::new(
4566 KeyParameterValue::NoAuthRequired,
4567 SecurityLevel::TRUSTED_ENVIRONMENT,
4568 ),
4569 KeyParameter::new(
4570 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4571 SecurityLevel::TRUSTED_ENVIRONMENT,
4572 ),
4573 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4574 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4575 KeyParameter::new(
4576 KeyParameterValue::TrustedUserPresenceRequired,
4577 SecurityLevel::TRUSTED_ENVIRONMENT,
4578 ),
4579 KeyParameter::new(
4580 KeyParameterValue::TrustedConfirmationRequired,
4581 SecurityLevel::TRUSTED_ENVIRONMENT,
4582 ),
4583 KeyParameter::new(
4584 KeyParameterValue::UnlockedDeviceRequired,
4585 SecurityLevel::TRUSTED_ENVIRONMENT,
4586 ),
4587 KeyParameter::new(
4588 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4589 SecurityLevel::SOFTWARE,
4590 ),
4591 KeyParameter::new(
4592 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4593 SecurityLevel::SOFTWARE,
4594 ),
4595 KeyParameter::new(
4596 KeyParameterValue::CreationDateTime(12345677890),
4597 SecurityLevel::SOFTWARE,
4598 ),
4599 KeyParameter::new(
4600 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4601 SecurityLevel::TRUSTED_ENVIRONMENT,
4602 ),
4603 KeyParameter::new(
4604 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4605 SecurityLevel::TRUSTED_ENVIRONMENT,
4606 ),
4607 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4608 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4609 KeyParameter::new(
4610 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4611 SecurityLevel::SOFTWARE,
4612 ),
4613 KeyParameter::new(
4614 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4615 SecurityLevel::TRUSTED_ENVIRONMENT,
4616 ),
4617 KeyParameter::new(
4618 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4619 SecurityLevel::TRUSTED_ENVIRONMENT,
4620 ),
4621 KeyParameter::new(
4622 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4623 SecurityLevel::TRUSTED_ENVIRONMENT,
4624 ),
4625 KeyParameter::new(
4626 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4627 SecurityLevel::TRUSTED_ENVIRONMENT,
4628 ),
4629 KeyParameter::new(
4630 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4631 SecurityLevel::TRUSTED_ENVIRONMENT,
4632 ),
4633 KeyParameter::new(
4634 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4635 SecurityLevel::TRUSTED_ENVIRONMENT,
4636 ),
4637 KeyParameter::new(
4638 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4639 SecurityLevel::TRUSTED_ENVIRONMENT,
4640 ),
4641 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004642 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4643 SecurityLevel::TRUSTED_ENVIRONMENT,
4644 ),
4645 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004646 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4647 SecurityLevel::TRUSTED_ENVIRONMENT,
4648 ),
4649 KeyParameter::new(
4650 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4651 SecurityLevel::TRUSTED_ENVIRONMENT,
4652 ),
4653 KeyParameter::new(
4654 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4655 SecurityLevel::TRUSTED_ENVIRONMENT,
4656 ),
4657 KeyParameter::new(
4658 KeyParameterValue::VendorPatchLevel(3),
4659 SecurityLevel::TRUSTED_ENVIRONMENT,
4660 ),
4661 KeyParameter::new(
4662 KeyParameterValue::BootPatchLevel(4),
4663 SecurityLevel::TRUSTED_ENVIRONMENT,
4664 ),
4665 KeyParameter::new(
4666 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4667 SecurityLevel::TRUSTED_ENVIRONMENT,
4668 ),
4669 KeyParameter::new(
4670 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4671 SecurityLevel::TRUSTED_ENVIRONMENT,
4672 ),
4673 KeyParameter::new(
4674 KeyParameterValue::MacLength(256),
4675 SecurityLevel::TRUSTED_ENVIRONMENT,
4676 ),
4677 KeyParameter::new(
4678 KeyParameterValue::ResetSinceIdRotation,
4679 SecurityLevel::TRUSTED_ENVIRONMENT,
4680 ),
4681 KeyParameter::new(
4682 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4683 SecurityLevel::TRUSTED_ENVIRONMENT,
4684 ),
Qi Wub9433b52020-12-01 14:52:46 +08004685 ];
4686 if let Some(value) = max_usage_count {
4687 params.push(KeyParameter::new(
4688 KeyParameterValue::UsageCountLimit(value),
4689 SecurityLevel::SOFTWARE,
4690 ));
4691 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004692
4693 for sid in user_secure_ids.iter() {
4694 params.push(KeyParameter::new(
4695 KeyParameterValue::UserSecureID(*sid),
4696 SecurityLevel::STRONGBOX,
4697 ));
4698 }
Qi Wub9433b52020-12-01 14:52:46 +08004699 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004700 }
4701
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004702 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004703 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004704 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004705 namespace: i64,
4706 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004707 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004708 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004709 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4710 }
4711
4712 pub fn make_test_key_entry_with_sids(
4713 db: &mut KeystoreDB,
4714 domain: Domain,
4715 namespace: i64,
4716 alias: &str,
4717 max_usage_count: Option<i32>,
4718 sids: &[i64],
4719 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004720 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004721 let mut blob_metadata = BlobMetaData::new();
4722 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4723 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4724 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4725 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4726 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4727
4728 db.set_blob(
4729 &key_id,
4730 SubComponentType::KEY_BLOB,
4731 Some(TEST_KEY_BLOB),
4732 Some(&blob_metadata),
4733 )?;
4734 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4735 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004736
Eran Messeri4dc27b52024-01-09 12:43:31 +00004737 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004738 db.insert_keyparameter(&key_id, &params)?;
4739
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004740 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004741 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004742 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004743 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004744 Ok(key_id)
4745 }
4746
Qi Wub9433b52020-12-01 14:52:46 +08004747 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4748 let params = make_test_params(max_usage_count);
4749
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004750 let mut blob_metadata = BlobMetaData::new();
4751 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4752 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4753 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4754 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4755 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4756
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004757 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004758 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004759
4760 KeyEntry {
4761 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004762 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004763 cert: Some(TEST_CERT_BLOB.to_vec()),
4764 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004765 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004766 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004767 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004768 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004769 }
4770 }
4771
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004772 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004773 db: &mut KeystoreDB,
4774 domain: Domain,
4775 namespace: i64,
4776 alias: &str,
4777 logical_only: bool,
4778 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004779 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004780 let mut blob_metadata = BlobMetaData::new();
4781 if !logical_only {
4782 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4783 }
4784 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4785
4786 db.set_blob(
4787 &key_id,
4788 SubComponentType::KEY_BLOB,
4789 Some(TEST_KEY_BLOB),
4790 Some(&blob_metadata),
4791 )?;
4792 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4793 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4794
4795 let mut params = make_test_params(None);
4796 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4797
4798 db.insert_keyparameter(&key_id, &params)?;
4799
4800 let mut metadata = KeyMetaData::new();
4801 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4802 db.insert_key_metadata(&key_id, &metadata)?;
4803 rebind_alias(db, &key_id, alias, domain, namespace)?;
4804 Ok(key_id)
4805 }
4806
Eric Biggersb0478cf2023-10-27 03:55:29 +00004807 // Creates an app key that is marked as being superencrypted by the given
4808 // super key ID and that has the given authentication and unlocked device
4809 // parameters. This does not actually superencrypt the key blob.
4810 fn make_superencrypted_key_entry(
4811 db: &mut KeystoreDB,
4812 namespace: i64,
4813 alias: &str,
4814 requires_authentication: bool,
4815 requires_unlocked_device: bool,
4816 super_key_id: i64,
4817 ) -> Result<KeyIdGuard> {
4818 let domain = Domain::APP;
David Drysdale8c4c4f32023-10-31 12:14:11 +00004819 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Eric Biggersb0478cf2023-10-27 03:55:29 +00004820
4821 let mut blob_metadata = BlobMetaData::new();
4822 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4823 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4824 db.set_blob(
4825 &key_id,
4826 SubComponentType::KEY_BLOB,
4827 Some(TEST_KEY_BLOB),
4828 Some(&blob_metadata),
4829 )?;
4830
4831 let mut params = vec![];
4832 if requires_unlocked_device {
4833 params.push(KeyParameter::new(
4834 KeyParameterValue::UnlockedDeviceRequired,
4835 SecurityLevel::TRUSTED_ENVIRONMENT,
4836 ));
4837 }
4838 if requires_authentication {
4839 params.push(KeyParameter::new(
4840 KeyParameterValue::UserSecureID(42),
4841 SecurityLevel::TRUSTED_ENVIRONMENT,
4842 ));
4843 }
4844 db.insert_keyparameter(&key_id, &params)?;
4845
4846 let mut metadata = KeyMetaData::new();
4847 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4848 db.insert_key_metadata(&key_id, &metadata)?;
4849
4850 rebind_alias(db, &key_id, alias, domain, namespace)?;
4851 Ok(key_id)
4852 }
4853
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004854 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4855 let mut params = make_test_params(None);
4856 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4857
4858 let mut blob_metadata = BlobMetaData::new();
4859 if !logical_only {
4860 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4861 }
4862 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4863
4864 let mut metadata = KeyMetaData::new();
4865 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4866
4867 KeyEntry {
4868 id: key_id,
4869 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4870 cert: Some(TEST_CERT_BLOB.to_vec()),
4871 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4872 km_uuid: KEYSTORE_UUID,
4873 parameters: params,
4874 metadata,
4875 pure_cert: false,
4876 }
4877 }
4878
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004879 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004880 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004881 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004882 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004883 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004884 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004885 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004886 Ok((
4887 row.get(0)?,
4888 row.get(1)?,
4889 row.get(2)?,
4890 row.get(3)?,
4891 row.get(4)?,
4892 row.get(5)?,
4893 row.get(6)?,
4894 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004895 },
4896 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004897
4898 println!("Key entry table rows:");
4899 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004900 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004901 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004902 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4903 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004904 );
4905 }
4906 Ok(())
4907 }
4908
4909 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004910 let mut stmt = db
4911 .conn
4912 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004913 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004914 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4915 })?;
4916
4917 println!("Grant table rows:");
4918 for r in rows {
4919 let (id, gt, ki, av) = r.unwrap();
4920 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4921 }
4922 Ok(())
4923 }
4924
Joel Galenson0891bc12020-07-20 10:37:03 -07004925 // Use a custom random number generator that repeats each number once.
4926 // This allows us to test repeated elements.
4927
4928 thread_local! {
Charisee43391152024-04-02 16:16:30 +00004929 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07004930 }
4931
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004932 fn reset_random() {
4933 RANDOM_COUNTER.with(|counter| {
4934 *counter.borrow_mut() = 0;
4935 })
4936 }
4937
Joel Galenson0891bc12020-07-20 10:37:03 -07004938 pub fn random() -> i64 {
4939 RANDOM_COUNTER.with(|counter| {
4940 let result = *counter.borrow() / 2;
4941 *counter.borrow_mut() += 1;
4942 result
4943 })
4944 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004945
4946 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00004947 fn test_unbind_keys_for_user() -> Result<()> {
4948 let mut db = new_test_db()?;
4949 db.unbind_keys_for_user(1, false)?;
4950
4951 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4952 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4953 db.unbind_keys_for_user(2, false)?;
4954
Eran Messeri24f31972023-01-25 17:00:33 +00004955 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4956 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004957
4958 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004959 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004960
4961 Ok(())
4962 }
4963
4964 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004965 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4966 let mut db = new_test_db()?;
4967 let super_key = keystore2_crypto::generate_aes256_key()?;
4968 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4969 let (encrypted_super_key, metadata) =
4970 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4971
4972 let key_name_enc = SuperKeyType {
4973 alias: "test_super_key_1",
4974 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004975 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004976 };
4977
4978 let key_name_nonenc = SuperKeyType {
4979 alias: "test_super_key_2",
4980 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004981 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004982 };
4983
4984 // Install two super keys.
4985 db.store_super_key(
4986 1,
4987 &key_name_nonenc,
4988 &super_key,
4989 &BlobMetaData::new(),
4990 &KeyMetaData::new(),
4991 )?;
4992 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4993
4994 // Check that both can be found in the database.
4995 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
4996 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
4997
4998 // Install the same keys for a different user.
4999 db.store_super_key(
5000 2,
5001 &key_name_nonenc,
5002 &super_key,
5003 &BlobMetaData::new(),
5004 &KeyMetaData::new(),
5005 )?;
5006 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5007
5008 // Check that the second pair of keys can be found in the database.
5009 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5010 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5011
5012 // Delete only encrypted keys.
5013 db.unbind_keys_for_user(1, true)?;
5014
5015 // The encrypted superkey should be gone now.
5016 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5017 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5018
5019 // Reinsert the encrypted key.
5020 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5021
5022 // Check that both can be found in the database, again..
5023 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5024 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5025
5026 // Delete all even unencrypted keys.
5027 db.unbind_keys_for_user(1, false)?;
5028
5029 // Both should be gone now.
5030 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5031 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5032
5033 // Check that the second pair of keys was untouched.
5034 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5035 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5036
5037 Ok(())
5038 }
5039
Eric Biggersb0478cf2023-10-27 03:55:29 +00005040 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5041 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5042 }
5043
5044 // Tests the unbind_auth_bound_keys_for_user() function.
5045 #[test]
5046 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5047 let mut db = new_test_db()?;
5048 let user_id = 1;
5049 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5050 let other_user_id = 2;
5051 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5052 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5053
5054 // Create a superencryption key.
5055 let super_key = keystore2_crypto::generate_aes256_key()?;
5056 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5057 let (encrypted_super_key, blob_metadata) =
5058 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5059 db.store_super_key(
5060 user_id,
5061 super_key_type,
5062 &encrypted_super_key,
5063 &blob_metadata,
5064 &KeyMetaData::new(),
5065 )?;
5066 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5067
5068 // Store 4 superencrypted app keys, one for each possible combination of
5069 // (authentication required, unlocked device required).
5070 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5071 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5072 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5073 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5074 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5075 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5076 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5077 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5078
5079 // Also store a key for a different user that requires authentication.
5080 make_superencrypted_key_entry(
5081 &mut db,
5082 other_user_nspace,
5083 "auth_ud",
5084 true,
5085 true,
5086 super_key_id,
5087 )?;
5088
5089 db.unbind_auth_bound_keys_for_user(user_id)?;
5090
5091 // Verify that only the user's app keys that require authentication were
5092 // deleted. Keys that require an unlocked device but not authentication
5093 // should *not* have been deleted, nor should the super key have been
5094 // deleted, nor should other users' keys have been deleted.
5095 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5096 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5097 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5098 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5099 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5100 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5101
5102 Ok(())
5103 }
5104
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005105 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005106 fn test_store_super_key() -> Result<()> {
5107 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005108 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005109 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005110 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005111 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005112 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005113
5114 let (encrypted_super_key, metadata) =
5115 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005116 db.store_super_key(
5117 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005118 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005119 &encrypted_super_key,
5120 &metadata,
5121 &KeyMetaData::new(),
5122 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005123
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005124 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005125 assert!(db.key_exists(
5126 Domain::APP,
5127 1,
5128 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5129 KeyType::Super
5130 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005131
Eric Biggers673d34a2023-10-18 01:54:18 +00005132 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005133 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005134 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005135 key_entry,
5136 &pw,
5137 None,
5138 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005139
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005140 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005141 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005142
Hasini Gunasingheda895552021-01-27 19:34:37 +00005143 Ok(())
5144 }
Seth Moore78c091f2021-04-09 21:38:30 +00005145
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005146 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005147 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005148 MetricsStorage::KEY_ENTRY,
5149 MetricsStorage::KEY_ENTRY_ID_INDEX,
5150 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5151 MetricsStorage::BLOB_ENTRY,
5152 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5153 MetricsStorage::KEY_PARAMETER,
5154 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5155 MetricsStorage::KEY_METADATA,
5156 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5157 MetricsStorage::GRANT,
5158 MetricsStorage::AUTH_TOKEN,
5159 MetricsStorage::BLOB_METADATA,
5160 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005161 ]
5162 }
5163
5164 /// Perform a simple check to ensure that we can query all the storage types
5165 /// that are supported by the DB. Check for reasonable values.
5166 #[test]
5167 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005168 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005169
5170 let mut db = new_test_db()?;
5171
5172 for t in get_valid_statsd_storage_types() {
5173 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005174 // AuthToken can be less than a page since it's in a btree, not sqlite
5175 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005176 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005177 } else {
5178 assert!(stat.size >= PAGE_SIZE);
5179 }
Seth Moore78c091f2021-04-09 21:38:30 +00005180 assert!(stat.size >= stat.unused_size);
5181 }
5182
5183 Ok(())
5184 }
5185
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005186 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005187 get_valid_statsd_storage_types()
5188 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005189 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005190 .collect()
5191 }
5192
5193 fn assert_storage_increased(
5194 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005195 increased_storage_types: Vec<MetricsStorage>,
5196 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005197 ) {
5198 for storage in increased_storage_types {
5199 // Verify the expected storage increased.
5200 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005201 let old = &baseline[&storage.0];
5202 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005203 assert!(
5204 new.unused_size <= old.unused_size,
5205 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005206 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005207 new.unused_size,
5208 old.unused_size
5209 );
5210
5211 // Update the baseline with the new value so that it succeeds in the
5212 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005213 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005214 }
5215
5216 // Get an updated map of the storage and verify there were no unexpected changes.
5217 let updated_stats = get_storage_stats_map(db);
5218 assert_eq!(updated_stats.len(), baseline.len());
5219
5220 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005221 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005222 let mut s = String::new();
5223 for &k in map.keys() {
5224 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5225 .expect("string concat failed");
5226 }
5227 s
5228 };
5229
5230 assert!(
5231 updated_stats[&k].size == baseline[&k].size
5232 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5233 "updated_stats:\n{}\nbaseline:\n{}",
5234 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005235 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005236 );
5237 }
5238 }
5239
5240 #[test]
5241 fn test_verify_key_table_size_reporting() -> Result<()> {
5242 let mut db = new_test_db()?;
5243 let mut working_stats = get_storage_stats_map(&mut db);
5244
David Drysdale8c4c4f32023-10-31 12:14:11 +00005245 let key_id = create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005246 assert_storage_increased(
5247 &mut db,
5248 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005249 MetricsStorage::KEY_ENTRY,
5250 MetricsStorage::KEY_ENTRY_ID_INDEX,
5251 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005252 ],
5253 &mut working_stats,
5254 );
5255
5256 let mut blob_metadata = BlobMetaData::new();
5257 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5258 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5259 assert_storage_increased(
5260 &mut db,
5261 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005262 MetricsStorage::BLOB_ENTRY,
5263 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5264 MetricsStorage::BLOB_METADATA,
5265 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005266 ],
5267 &mut working_stats,
5268 );
5269
5270 let params = make_test_params(None);
5271 db.insert_keyparameter(&key_id, &params)?;
5272 assert_storage_increased(
5273 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005274 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005275 &mut working_stats,
5276 );
5277
5278 let mut metadata = KeyMetaData::new();
5279 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5280 db.insert_key_metadata(&key_id, &metadata)?;
5281 assert_storage_increased(
5282 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005283 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005284 &mut working_stats,
5285 );
5286
5287 let mut sum = 0;
5288 for stat in working_stats.values() {
5289 sum += stat.size;
5290 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005291 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005292 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5293
5294 Ok(())
5295 }
5296
5297 #[test]
5298 fn test_verify_auth_table_size_reporting() -> Result<()> {
5299 let mut db = new_test_db()?;
5300 let mut working_stats = get_storage_stats_map(&mut db);
5301 db.insert_auth_token(&HardwareAuthToken {
5302 challenge: 123,
5303 userId: 456,
5304 authenticatorId: 789,
5305 authenticatorType: kmhw_authenticator_type::ANY,
5306 timestamp: Timestamp { milliSeconds: 10 },
5307 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005308 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005309 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005310 Ok(())
5311 }
5312
5313 #[test]
5314 fn test_verify_grant_table_size_reporting() -> Result<()> {
5315 const OWNER: i64 = 1;
5316 let mut db = new_test_db()?;
5317 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5318
5319 let mut working_stats = get_storage_stats_map(&mut db);
5320 db.grant(
5321 &KeyDescriptor {
5322 domain: Domain::APP,
5323 nspace: 0,
5324 alias: Some(TEST_ALIAS.to_string()),
5325 blob: None,
5326 },
5327 OWNER as u32,
5328 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005329 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005330 |_, _| Ok(()),
5331 )?;
5332
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005333 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005334
5335 Ok(())
5336 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005337
5338 #[test]
5339 fn find_auth_token_entry_returns_latest() -> Result<()> {
5340 let mut db = new_test_db()?;
5341 db.insert_auth_token(&HardwareAuthToken {
5342 challenge: 123,
5343 userId: 456,
5344 authenticatorId: 789,
5345 authenticatorType: kmhw_authenticator_type::ANY,
5346 timestamp: Timestamp { milliSeconds: 10 },
5347 mac: b"mac0".to_vec(),
5348 });
5349 std::thread::sleep(std::time::Duration::from_millis(1));
5350 db.insert_auth_token(&HardwareAuthToken {
5351 challenge: 123,
5352 userId: 457,
5353 authenticatorId: 789,
5354 authenticatorType: kmhw_authenticator_type::ANY,
5355 timestamp: Timestamp { milliSeconds: 12 },
5356 mac: b"mac1".to_vec(),
5357 });
5358 std::thread::sleep(std::time::Duration::from_millis(1));
5359 db.insert_auth_token(&HardwareAuthToken {
5360 challenge: 123,
5361 userId: 458,
5362 authenticatorId: 789,
5363 authenticatorType: kmhw_authenticator_type::ANY,
5364 timestamp: Timestamp { milliSeconds: 3 },
5365 mac: b"mac2".to_vec(),
5366 });
5367 // All three entries are in the database
5368 assert_eq!(db.perboot.auth_tokens_len(), 3);
5369 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005370 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005371 Ok(())
5372 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005373
5374 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005375 fn test_load_key_descriptor() -> Result<()> {
5376 let mut db = new_test_db()?;
5377 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5378
5379 let key = db.load_key_descriptor(key_id)?.unwrap();
5380
5381 assert_eq!(key.domain, Domain::APP);
5382 assert_eq!(key.nspace, 1);
5383 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5384
5385 // No such id
5386 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5387 Ok(())
5388 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005389
5390 #[test]
5391 fn test_get_list_app_uids_for_sid() -> Result<()> {
5392 let uid: i32 = 1;
5393 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5394 let first_sid = 667;
5395 let second_sid = 669;
5396 let first_app_id: i64 = 123 + uid_offset;
5397 let second_app_id: i64 = 456 + uid_offset;
5398 let third_app_id: i64 = 789 + uid_offset;
5399 let unrelated_app_id: i64 = 1011 + uid_offset;
5400 let mut db = new_test_db()?;
5401 make_test_key_entry_with_sids(
5402 &mut db,
5403 Domain::APP,
5404 first_app_id,
5405 TEST_ALIAS,
5406 None,
5407 &[first_sid],
5408 )
5409 .context("test_get_list_app_uids_for_sid")?;
5410 make_test_key_entry_with_sids(
5411 &mut db,
5412 Domain::APP,
5413 second_app_id,
5414 "alias2",
5415 None,
5416 &[first_sid],
5417 )
5418 .context("test_get_list_app_uids_for_sid")?;
5419 make_test_key_entry_with_sids(
5420 &mut db,
5421 Domain::APP,
5422 second_app_id,
5423 TEST_ALIAS,
5424 None,
5425 &[second_sid],
5426 )
5427 .context("test_get_list_app_uids_for_sid")?;
5428 make_test_key_entry_with_sids(
5429 &mut db,
5430 Domain::APP,
5431 third_app_id,
5432 "alias3",
5433 None,
5434 &[second_sid],
5435 )
5436 .context("test_get_list_app_uids_for_sid")?;
5437 make_test_key_entry_with_sids(
5438 &mut db,
5439 Domain::APP,
5440 unrelated_app_id,
5441 TEST_ALIAS,
5442 None,
5443 &[],
5444 )
5445 .context("test_get_list_app_uids_for_sid")?;
5446
5447 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5448 first_sid_apps.sort();
5449 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5450 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5451 second_sid_apps.sort();
5452 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5453 Ok(())
5454 }
5455
5456 #[test]
5457 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5458 let uid: i32 = 1;
5459 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5460 let first_sid = 667;
5461 let second_sid = 669;
5462 let third_sid = 772;
5463 let first_app_id: i64 = 123 + uid_offset;
5464 let second_app_id: i64 = 456 + uid_offset;
5465 let mut db = new_test_db()?;
5466 make_test_key_entry_with_sids(
5467 &mut db,
5468 Domain::APP,
5469 first_app_id,
5470 TEST_ALIAS,
5471 None,
5472 &[first_sid, second_sid],
5473 )
5474 .context("test_get_list_app_uids_for_sid")?;
5475 make_test_key_entry_with_sids(
5476 &mut db,
5477 Domain::APP,
5478 second_app_id,
5479 "alias2",
5480 None,
5481 &[second_sid, third_sid],
5482 )
5483 .context("test_get_list_app_uids_for_sid")?;
5484
5485 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5486 assert_eq!(first_sid_apps, vec![first_app_id]);
5487
5488 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5489 second_sid_apps.sort();
5490 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5491
5492 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5493 assert_eq!(third_sid_apps, vec![second_app_id]);
5494 Ok(())
5495 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005496}