blob: a9a1c4bf3f17d7288ff10a292d6e095ceff90e1b [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;
David Drysdalef1ba3812024-05-08 17:50:13 +010049use crate::impl_metadata; // This is in database/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
David Drysdalef1ba3812024-05-08 17:50:13 +0100859/// Information about a superseded blob (a blob that is no longer the
860/// most recent blob of that type for a given key, due to upgrade or
861/// replacement).
862pub struct SupersededBlob {
863 /// ID
864 pub blob_id: i64,
865 /// Contents.
866 pub blob: Vec<u8>,
867 /// Metadata.
868 pub metadata: BlobMetaData,
869}
870
Joel Galenson26f4d012020-07-17 14:57:21 -0700871impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800872 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700873 const CURRENT_DB_VERSION: u32 = 1;
874 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800875
Seth Moore78c091f2021-04-09 21:38:30 +0000876 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700877 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000878
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700879 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800880 /// files persistent.sqlite and perboot.sqlite in the given directory.
881 /// It also attempts to initialize all of the tables.
882 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700883 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700884 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
David Drysdale541846b2024-05-23 13:16:07 +0100885 let _wp = wd::watch("KeystoreDB::new");
Janis Danisevskis850d4862021-05-05 08:41:14 -0700886
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700887 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700888 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800889
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700890 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
David Drysdale7b9ca232024-05-23 18:19:46 +0100891 db.with_transaction(Immediate("TX_new"), |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700892 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000893 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800894 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800895 })?;
896 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700897 }
898
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700899 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
900 // cryptographic binding to the boot level keys was implemented.
901 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
902 tx.execute(
903 "UPDATE persistent.keyentry SET state = ?
904 WHERE
905 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
906 AND
907 id NOT IN (
908 SELECT keyentryid FROM persistent.blobentry
909 WHERE id IN (
910 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
911 )
912 );",
913 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
914 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000915 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700916 Ok(1)
917 }
918
Janis Danisevskis66784c42021-01-27 08:40:25 -0800919 fn init_tables(tx: &Transaction) -> Result<()> {
920 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700921 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700922 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800923 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700924 domain INTEGER,
925 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800926 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800927 state INTEGER,
928 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000929 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700930 )
931 .context("Failed to initialize \"keyentry\" table.")?;
932
Janis Danisevskis66784c42021-01-27 08:40:25 -0800933 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800934 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
935 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000936 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800937 )
938 .context("Failed to create index keyentry_id_index.")?;
939
940 tx.execute(
941 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
942 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000943 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800944 )
945 .context("Failed to create index keyentry_domain_namespace_index.")?;
946
947 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700948 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
949 id INTEGER PRIMARY KEY,
950 subcomponent_type INTEGER,
951 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800952 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000953 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700954 )
955 .context("Failed to initialize \"blobentry\" table.")?;
956
Janis Danisevskis66784c42021-01-27 08:40:25 -0800957 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800958 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
959 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000960 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800961 )
962 .context("Failed to create index blobentry_keyentryid_index.")?;
963
964 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800965 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
966 id INTEGER PRIMARY KEY,
967 blobentryid INTEGER,
968 tag INTEGER,
969 data ANY,
970 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000971 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800972 )
973 .context("Failed to initialize \"blobmetadata\" table.")?;
974
975 tx.execute(
976 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
977 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000978 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800979 )
980 .context("Failed to create index blobmetadata_blobentryid_index.")?;
981
982 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700983 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000984 keyentryid INTEGER,
985 tag INTEGER,
986 data ANY,
987 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000988 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700989 )
990 .context("Failed to initialize \"keyparameter\" table.")?;
991
Janis Danisevskis66784c42021-01-27 08:40:25 -0800992 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800993 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
994 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000995 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800996 )
997 .context("Failed to create index keyparameter_keyentryid_index.")?;
998
999 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001000 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
1001 keyentryid INTEGER,
1002 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001003 data ANY,
1004 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001005 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001006 )
1007 .context("Failed to initialize \"keymetadata\" table.")?;
1008
Janis Danisevskis66784c42021-01-27 08:40:25 -08001009 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -08001010 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
1011 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001012 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -08001013 )
1014 .context("Failed to create index keymetadata_keyentryid_index.")?;
1015
1016 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001017 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001018 id INTEGER UNIQUE,
1019 grantee INTEGER,
1020 keyentryid INTEGER,
1021 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001022 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001023 )
1024 .context("Failed to initialize \"grant\" table.")?;
1025
Joel Galenson0891bc12020-07-20 10:37:03 -07001026 Ok(())
1027 }
1028
Seth Moore472fcbb2021-05-12 10:07:51 -07001029 fn make_persistent_path(db_root: &Path) -> Result<String> {
1030 // Build the path to the sqlite file.
1031 let mut persistent_path = db_root.to_path_buf();
1032 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1033
1034 // Now convert them to strings prefixed with "file:"
1035 let mut persistent_path_str = "file:".to_owned();
1036 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1037
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001038 // Connect to database in specific mode
1039 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1040 "?journal_mode=WAL".to_owned()
1041 } else {
1042 "?journal_mode=DELETE".to_owned()
1043 };
1044 persistent_path_str.push_str(&persistent_path_mode);
1045
Seth Moore472fcbb2021-05-12 10:07:51 -07001046 Ok(persistent_path_str)
1047 }
1048
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001049 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001050 let conn =
1051 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1052
Janis Danisevskis66784c42021-01-27 08:40:25 -08001053 loop {
1054 if let Err(e) = conn
1055 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1056 .context("Failed to attach database persistent.")
1057 {
1058 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001059 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001060 continue;
1061 } else {
1062 return Err(e);
1063 }
1064 }
1065 break;
1066 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001067
Matthew Maurer4fb19112021-05-06 15:40:44 -07001068 // Drop the cache size from default (2M) to 0.5M
1069 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1070 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001071
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001072 Ok(conn)
1073 }
1074
Seth Moore78c091f2021-04-09 21:38:30 +00001075 fn do_table_size_query(
1076 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001077 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001078 query: &str,
1079 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001080 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001081 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001082 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001083 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001084 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001085 })
1086 .no_gc()
1087 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001088 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001089 }
1090
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001091 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001092 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001093 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001094 "SELECT page_count * page_size, freelist_count * page_size
1095 FROM pragma_page_count('persistent'),
1096 pragma_page_size('persistent'),
1097 persistent.pragma_freelist_count();",
1098 &[],
1099 )
1100 }
1101
1102 fn get_table_size(
1103 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001104 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001105 schema: &str,
1106 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001108 self.do_table_size_query(
1109 storage_type,
1110 "SELECT pgsize,unused FROM dbstat(?1)
1111 WHERE name=?2 AND aggregate=TRUE;",
1112 &[schema, table],
1113 )
1114 }
1115
1116 /// Fetches a storage statisitics atom for a given storage type. For storage
1117 /// types that map to a table, information about the table's storage is
1118 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
David Drysdale541846b2024-05-23 13:16:07 +01001120 let _wp = wd::watch("KeystoreDB::get_storage_stat");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001121
Seth Moore78c091f2021-04-09 21:38:30 +00001122 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001123 MetricsStorage::DATABASE => self.get_total_size(),
1124 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001125 self.get_table_size(storage_type, "persistent", "keyentry")
1126 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001128 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1129 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001131 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1132 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001133 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001134 self.get_table_size(storage_type, "persistent", "blobentry")
1135 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001137 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1138 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001140 self.get_table_size(storage_type, "persistent", "keyparameter")
1141 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001142 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001143 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1144 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001145 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001146 self.get_table_size(storage_type, "persistent", "keymetadata")
1147 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001148 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001149 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1150 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001151 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1152 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001153 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1154 // reportable
1155 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001156 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001157 storage_type,
1158 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001159 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001160 unused_size: 0,
1161 })
Seth Moore78c091f2021-04-09 21:38:30 +00001162 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001163 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001164 self.get_table_size(storage_type, "persistent", "blobmetadata")
1165 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001166 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001167 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1168 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001169 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001170 }
1171 }
1172
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001173 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001174 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1175 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001176 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1177 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001178 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001179 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001180 blob_ids_to_delete: &[i64],
1181 max_blobs: usize,
David Drysdalef1ba3812024-05-08 17:50:13 +01001182 ) -> Result<Vec<SupersededBlob>> {
David Drysdale541846b2024-05-23 13:16:07 +01001183 let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob");
David Drysdale7b9ca232024-05-23 18:19:46 +01001184 self.with_transaction(Immediate("TX_handle_next_superseded_blob"), |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001185 // Delete the given blobs.
1186 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001187 tx.execute(
1188 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001189 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001190 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001191 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001192 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001193 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001194 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001195
1196 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1197
David Drysdalef1ba3812024-05-08 17:50:13 +01001198 // Find up to `max_blobs` more superseded key blobs, load their metadata and return it.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001199 let result: Vec<(i64, Vec<u8>)> = {
David Drysdalef1ba3812024-05-08 17:50:13 +01001200 let _wp = wd::watch("handle_next_superseded_blob find_next");
Janis Danisevskis3395f862021-05-06 10:54:17 -07001201 let mut stmt = tx
1202 .prepare(
1203 "SELECT id, blob FROM persistent.blobentry
1204 WHERE subcomponent_type = ?
1205 AND (
1206 id NOT IN (
1207 SELECT MAX(id) FROM persistent.blobentry
1208 WHERE subcomponent_type = ?
1209 GROUP BY keyentryid, subcomponent_type
1210 )
1211 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1212 ) LIMIT ?;",
1213 )
1214 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001215
Janis Danisevskis3395f862021-05-06 10:54:17 -07001216 let rows = stmt
1217 .query_map(
1218 params![
1219 SubComponentType::KEY_BLOB,
1220 SubComponentType::KEY_BLOB,
1221 max_blobs as i64,
1222 ],
1223 |row| Ok((row.get(0)?, row.get(1)?)),
1224 )
1225 .context("Trying to query superseded blob.")?;
1226
1227 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1228 .context("Trying to extract superseded blobs.")?
1229 };
1230
David Drysdalef1ba3812024-05-08 17:50:13 +01001231 let _wp = wd::watch("handle_next_superseded_blob load_metadata");
Janis Danisevskis3395f862021-05-06 10:54:17 -07001232 let result = result
1233 .into_iter()
1234 .map(|(blob_id, blob)| {
David Drysdalef1ba3812024-05-08 17:50:13 +01001235 Ok(SupersededBlob {
1236 blob_id,
1237 blob,
1238 metadata: BlobMetaData::load_from_db(blob_id, tx)?,
1239 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001240 })
David Drysdalef1ba3812024-05-08 17:50:13 +01001241 .collect::<Result<Vec<_>>>()
Janis Danisevskis3395f862021-05-06 10:54:17 -07001242 .context("Trying to load blob metadata.")?;
1243 if !result.is_empty() {
1244 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001245 }
1246
1247 // We did not find any superseded key blob, so let's remove other superseded blob in
1248 // one transaction.
David Drysdalef1ba3812024-05-08 17:50:13 +01001249 let _wp = wd::watch("handle_next_superseded_blob delete");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001250 tx.execute(
1251 "DELETE FROM persistent.blobentry
1252 WHERE NOT subcomponent_type = ?
1253 AND (
1254 id NOT IN (
1255 SELECT MAX(id) FROM persistent.blobentry
1256 WHERE NOT subcomponent_type = ?
1257 GROUP BY keyentryid, subcomponent_type
1258 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1259 );",
1260 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1261 )
1262 .context("Trying to purge superseded blobs.")?;
1263
Janis Danisevskis3395f862021-05-06 10:54:17 -07001264 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001265 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001266 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001267 }
1268
1269 /// This maintenance function should be called only once before the database is used for the
1270 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1271 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1272 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1273 /// Keystore crashed at some point during key generation. Callers may want to log such
1274 /// occurrences.
1275 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1276 /// it to `KeyLifeCycle::Live` may have grants.
1277 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01001278 let _wp = wd::watch("KeystoreDB::cleanup_leftovers");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001279
David Drysdale7b9ca232024-05-23 18:19:46 +01001280 self.with_transaction(Immediate("TX_cleanup_leftovers"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001281 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001282 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1283 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1284 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001285 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001286 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001287 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001288 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001289 }
1290
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001291 /// Checks if a key exists with given key type and key descriptor properties.
1292 pub fn key_exists(
1293 &mut self,
1294 domain: Domain,
1295 nspace: i64,
1296 alias: &str,
1297 key_type: KeyType,
1298 ) -> Result<bool> {
David Drysdale541846b2024-05-23 13:16:07 +01001299 let _wp = wd::watch("KeystoreDB::key_exists");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001300
David Drysdale7b9ca232024-05-23 18:19:46 +01001301 self.with_transaction(Immediate("TX_key_exists"), |tx| {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001302 let key_descriptor =
1303 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001304 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001305 match result {
1306 Ok(_) => Ok(true),
1307 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1308 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001309 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001310 },
1311 }
1312 .no_gc()
1313 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001314 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001315 }
1316
Hasini Gunasingheda895552021-01-27 19:34:37 +00001317 /// Stores a super key in the database.
1318 pub fn store_super_key(
1319 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001320 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001321 key_type: &SuperKeyType,
1322 blob: &[u8],
1323 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001324 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001325 ) -> Result<KeyEntry> {
David Drysdale541846b2024-05-23 13:16:07 +01001326 let _wp = wd::watch("KeystoreDB::store_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001327
David Drysdale7b9ca232024-05-23 18:19:46 +01001328 self.with_transaction(Immediate("TX_store_super_key"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00001329 let key_id = Self::insert_with_retry(|id| {
1330 tx.execute(
1331 "INSERT into persistent.keyentry
1332 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001333 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001334 params![
1335 id,
1336 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001337 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001338 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001339 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001340 KeyLifeCycle::Live,
1341 &KEYSTORE_UUID,
1342 ],
1343 )
1344 })
1345 .context("Failed to insert into keyentry table.")?;
1346
Paul Crowley8d5b2532021-03-19 10:53:07 -07001347 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1348
Hasini Gunasingheda895552021-01-27 19:34:37 +00001349 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001350 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001351 key_id,
1352 SubComponentType::KEY_BLOB,
1353 Some(blob),
1354 Some(blob_metadata),
1355 )
1356 .context("Failed to store key blob.")?;
1357
1358 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1359 .context("Trying to load key components.")
1360 .no_gc()
1361 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001362 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001363 }
1364
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001365 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001366 pub fn load_super_key(
1367 &mut self,
1368 key_type: &SuperKeyType,
1369 user_id: u32,
1370 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
David Drysdale541846b2024-05-23 13:16:07 +01001371 let _wp = wd::watch("KeystoreDB::load_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001372
David Drysdale7b9ca232024-05-23 18:19:46 +01001373 self.with_transaction(Immediate("TX_load_super_key"), |tx| {
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001374 let key_descriptor = KeyDescriptor {
1375 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001376 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001377 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001378 blob: None,
1379 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001380 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001381 match id {
1382 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001383 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001384 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001385 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1386 }
1387 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1388 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001389 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001390 },
1391 }
1392 .no_gc()
1393 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001394 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001395 }
1396
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001397 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1399 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001400 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1401 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001402 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001403 {
David Drysdale7b9ca232024-05-23 18:19:46 +01001404 let name = behavior.name();
Janis Danisevskis66784c42021-01-27 08:40:25 -08001405 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001406 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01001408 .transaction_with_behavior(behavior.into())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001409 .context(ks_err!())
David Drysdale7b9ca232024-05-23 18:19:46 +01001410 .and_then(|tx| {
1411 let _wp = name.map(wd::watch);
1412 f(&tx).map(|result| (result, tx))
1413 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001414 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001415 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001417 });
1418 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 Ok(result) => break Ok(result),
1420 Err(e) => {
1421 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001422 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001423 continue;
1424 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001425 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 }
1427 }
1428 }
1429 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001430 .map(|(need_gc, result)| {
1431 if need_gc {
1432 if let Some(ref gc) = self.gc {
1433 gc.notify_gc();
1434 }
1435 }
1436 result
1437 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001438 }
1439
1440 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001441 matches!(
1442 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1443 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1444 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1445 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001446 }
1447
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001448 fn create_key_entry_internal(
1449 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001450 domain: &Domain,
1451 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001452 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001453 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001454 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001455 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001456 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001457 _ => {
1458 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001459 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001460 }
1461 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001462 Ok(KEY_ID_LOCK.get(
1463 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001464 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001465 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001466 (id, key_type, domain, namespace, alias, state, km_uuid)
1467 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001468 params![
1469 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001470 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001471 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001472 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001473 KeyLifeCycle::Existing,
1474 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001475 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001476 )
1477 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001478 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001479 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001480 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001481
Janis Danisevskis377d1002021-01-27 19:07:48 -08001482 /// Set a new blob and associates it with the given key id. Each blob
1483 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001484 /// Each key can have one of each sub component type associated. If more
1485 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001486 /// will get garbage collected.
1487 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1488 /// removed by setting blob to None.
1489 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001490 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001491 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001492 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001493 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001494 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001495 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001496 let _wp = wd::watch("KeystoreDB::set_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001497
David Drysdale7b9ca232024-05-23 18:19:46 +01001498 self.with_transaction(Immediate("TX_set_blob"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001499 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001500 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001501 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001502 }
1503
Janis Danisevskiseed69842021-02-18 20:04:10 -08001504 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1505 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1506 /// We use this to insert key blobs into the database which can then be garbage collected
1507 /// lazily by the key garbage collector.
1508 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001509 let _wp = wd::watch("KeystoreDB::set_deleted_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001510
David Drysdale7b9ca232024-05-23 18:19:46 +01001511 self.with_transaction(Immediate("TX_set_deleted_blob"), |tx| {
Janis Danisevskiseed69842021-02-18 20:04:10 -08001512 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001513 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001514 Self::UNASSIGNED_KEY_ID,
1515 SubComponentType::KEY_BLOB,
1516 Some(blob),
1517 Some(blob_metadata),
1518 )
1519 .need_gc()
1520 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001521 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001522 }
1523
Janis Danisevskis377d1002021-01-27 19:07:48 -08001524 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001525 tx: &Transaction,
1526 key_id: i64,
1527 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001528 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001529 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001530 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001531 match (blob, sc_type) {
1532 (Some(blob), _) => {
1533 tx.execute(
1534 "INSERT INTO persistent.blobentry
1535 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1536 params![sc_type, key_id, blob],
1537 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001538 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001539 if let Some(blob_metadata) = blob_metadata {
1540 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001541 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001542 row.get(0)
1543 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001544 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001545 blob_metadata
1546 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001547 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001548 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001549 }
1550 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1551 tx.execute(
1552 "DELETE FROM persistent.blobentry
1553 WHERE subcomponent_type = ? AND keyentryid = ?;",
1554 params![sc_type, key_id],
1555 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001556 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001557 }
1558 (None, _) => {
1559 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001560 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001561 }
1562 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001563 Ok(())
1564 }
1565
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001566 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1567 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001568 #[cfg(test)]
1569 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001570 self.with_transaction(Immediate("TX_insert_keyparameter"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001571 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001572 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001573 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001574 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001575
Janis Danisevskis66784c42021-01-27 08:40:25 -08001576 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001577 tx: &Transaction,
1578 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001579 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001580 ) -> Result<()> {
1581 let mut stmt = tx
1582 .prepare(
1583 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1584 VALUES (?, ?, ?, ?);",
1585 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001586 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001587
Janis Danisevskis66784c42021-01-27 08:40:25 -08001588 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001589 stmt.insert(params![
1590 key_id.0,
1591 p.get_tag().0,
1592 p.key_parameter_value(),
1593 p.security_level().0
1594 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001595 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001596 }
1597 Ok(())
1598 }
1599
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001600 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001601 #[cfg(test)]
1602 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001603 self.with_transaction(Immediate("TX_insert_key_metadata"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001604 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001605 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001606 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001607 }
1608
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001609 /// Updates the alias column of the given key id `newid` with the given alias,
1610 /// and atomically, removes the alias, domain, and namespace from another row
1611 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001612 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1613 /// collector.
1614 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001615 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001616 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001617 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001618 domain: &Domain,
1619 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001620 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001621 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001622 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001623 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001624 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001625 return Err(KsError::sys())
1626 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001627 }
1628 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001629 let updated = tx
1630 .execute(
1631 "UPDATE persistent.keyentry
1632 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001633 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1634 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001635 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001636 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001637 let result = tx
1638 .execute(
1639 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001640 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001641 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001642 params![
1643 alias,
1644 KeyLifeCycle::Live,
1645 newid.0,
1646 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001647 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001648 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001649 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001650 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001651 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001652 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001653 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001654 return Err(KsError::sys()).context(ks_err!(
1655 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001656 result
1657 ));
1658 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001659 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001660 }
1661
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001662 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1663 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1664 pub fn migrate_key_namespace(
1665 &mut self,
1666 key_id_guard: KeyIdGuard,
1667 destination: &KeyDescriptor,
1668 caller_uid: u32,
1669 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1670 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001671 let _wp = wd::watch("KeystoreDB::migrate_key_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001672
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001673 let destination = match destination.domain {
1674 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1675 Domain::SELINUX => (*destination).clone(),
1676 domain => {
1677 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1678 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1679 }
1680 };
1681
1682 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001683 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001684
1685 let alias = destination
1686 .alias
1687 .as_ref()
1688 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001689 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001690
David Drysdale7b9ca232024-05-23 18:19:46 +01001691 self.with_transaction(Immediate("TX_migrate_key_namespace"), |tx| {
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001692 // Query the destination location. If there is a key, the migration request fails.
1693 if tx
1694 .query_row(
1695 "SELECT id FROM persistent.keyentry
1696 WHERE alias = ? AND domain = ? AND namespace = ?;",
1697 params![alias, destination.domain.0, destination.nspace],
1698 |_| Ok(()),
1699 )
1700 .optional()
1701 .context("Failed to query destination.")?
1702 .is_some()
1703 {
1704 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1705 .context("Target already exists.");
1706 }
1707
1708 let updated = tx
1709 .execute(
1710 "UPDATE persistent.keyentry
1711 SET alias = ?, domain = ?, namespace = ?
1712 WHERE id = ?;",
1713 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1714 )
1715 .context("Failed to update key entry.")?;
1716
1717 if updated != 1 {
1718 return Err(KsError::sys())
1719 .context(format!("Update succeeded, but {} rows were updated.", updated));
1720 }
1721 Ok(()).no_gc()
1722 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001723 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001724 }
1725
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001726 /// Store a new key in a single transaction.
1727 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1728 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001729 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1730 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001731 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001732 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001734 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001735 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001736 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001737 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001738 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001739 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001740 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001741 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001742 let _wp = wd::watch("KeystoreDB::store_new_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001743
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001744 let (alias, domain, namespace) = match key {
1745 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1746 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1747 (alias, key.domain, nspace)
1748 }
1749 _ => {
1750 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001751 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001752 }
1753 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001754 self.with_transaction(Immediate("TX_store_new_key"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001755 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001756 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001757 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1758
1759 // In some occasions the key blob is already upgraded during the import.
1760 // In order to make sure it gets properly deleted it is inserted into the
1761 // database here and then immediately replaced by the superseding blob.
1762 // The garbage collector will then subject the blob to deleteKey of the
1763 // KM back end to permanently invalidate the key.
1764 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1765 Self::set_blob_internal(
1766 tx,
1767 key_id.id(),
1768 SubComponentType::KEY_BLOB,
1769 Some(blob),
1770 Some(blob_metadata),
1771 )
1772 .context("Trying to insert superseded key blob.")?;
1773 true
1774 } else {
1775 false
1776 };
1777
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001778 Self::set_blob_internal(
1779 tx,
1780 key_id.id(),
1781 SubComponentType::KEY_BLOB,
1782 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001783 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001784 )
1785 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001786 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001787 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001788 .context("Trying to insert the certificate.")?;
1789 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001790 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001791 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001792 tx,
1793 key_id.id(),
1794 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001795 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001796 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001797 )
1798 .context("Trying to insert the certificate chain.")?;
1799 }
1800 Self::insert_keyparameter_internal(tx, &key_id, params)
1801 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001802 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001803 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001804 .context("Trying to rebind alias.")?
1805 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001806 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001807 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001808 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001809 }
1810
Janis Danisevskis377d1002021-01-27 19:07:48 -08001811 /// Store a new certificate
1812 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1813 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001814 pub fn store_new_certificate(
1815 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001816 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001817 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001818 cert: &[u8],
1819 km_uuid: &Uuid,
1820 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001821 let _wp = wd::watch("KeystoreDB::store_new_certificate");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001822
Janis Danisevskis377d1002021-01-27 19:07:48 -08001823 let (alias, domain, namespace) = match key {
1824 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1825 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1826 (alias, key.domain, nspace)
1827 }
1828 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001829 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1830 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001831 }
1832 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001833 self.with_transaction(Immediate("TX_store_new_certificate"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001834 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001835 .context("Trying to create new key entry.")?;
1836
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001837 Self::set_blob_internal(
1838 tx,
1839 key_id.id(),
1840 SubComponentType::CERT_CHAIN,
1841 Some(cert),
1842 None,
1843 )
1844 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001845
1846 let mut metadata = KeyMetaData::new();
1847 metadata.add(KeyMetaEntry::CreationDate(
1848 DateTime::now().context("Trying to make creation time.")?,
1849 ));
1850
1851 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1852
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001853 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001854 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001855 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001856 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001857 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001858 }
1859
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001860 // Helper function loading the key_id given the key descriptor
1861 // tuple comprising domain, namespace, and alias.
1862 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001863 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001864 let alias = key
1865 .alias
1866 .as_ref()
1867 .map_or_else(|| Err(KsError::sys()), Ok)
1868 .context("In load_key_entry_id: Alias must be specified.")?;
1869 let mut stmt = tx
1870 .prepare(
1871 "SELECT id FROM persistent.keyentry
1872 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001873 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001874 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001875 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001876 AND alias = ?
1877 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001878 )
1879 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1880 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001881 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001882 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001883 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001884 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001885 .get(0)
1886 .context("Failed to unpack id.")
1887 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001888 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001889 }
1890
1891 /// This helper function completes the access tuple of a key, which is required
1892 /// to perform access control. The strategy depends on the `domain` field in the
1893 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001894 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001895 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001896 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001897 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001898 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001899 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001900 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001901 /// `namespace`.
1902 /// In each case the information returned is sufficient to perform the access
1903 /// check and the key id can be used to load further key artifacts.
1904 fn load_access_tuple(
1905 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001906 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001907 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001908 caller_uid: u32,
1909 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1910 match key.domain {
1911 // Domain App or SELinux. In this case we load the key_id from
1912 // the keyentry database for further loading of key components.
1913 // We already have the full access tuple to perform access control.
1914 // The only distinction is that we use the caller_uid instead
1915 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001916 // Domain::APP.
1917 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001918 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001919 if access_key.domain == Domain::APP {
1920 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001921 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001922 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001923 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001924
1925 Ok((key_id, access_key, None))
1926 }
1927
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001928 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001929 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001930 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001931 let mut stmt = tx
1932 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001933 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001934 WHERE grantee = ? AND id = ? AND
1935 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001936 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001937 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001938 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001939 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001940 .context("Domain:Grant: query failed.")?;
1941 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001942 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001943 let r =
1944 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001945 Ok((
1946 r.get(0).context("Failed to unpack key_id.")?,
1947 r.get(1).context("Failed to unpack access_vector.")?,
1948 ))
1949 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001950 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001951 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001952 }
1953
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001954 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001955 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001956 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08001957 let (domain, namespace): (Domain, i64) = {
1958 let mut stmt = tx
1959 .prepare(
1960 "SELECT domain, namespace FROM persistent.keyentry
1961 WHERE
1962 id = ?
1963 AND state = ?;",
1964 )
1965 .context("Domain::KEY_ID: prepare statement failed")?;
1966 let mut rows = stmt
1967 .query(params![key.nspace, KeyLifeCycle::Live])
1968 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001969 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001970 let r =
1971 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001972 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001973 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001974 r.get(1).context("Failed to unpack namespace.")?,
1975 ))
1976 })
Janis Danisevskis45760022021-01-19 16:34:10 -08001977 .context("Domain::KEY_ID.")?
1978 };
1979
1980 // We may use a key by id after loading it by grant.
1981 // In this case we have to check if the caller has a grant for this particular
1982 // key. We can skip this if we already know that the caller is the owner.
1983 // But we cannot know this if domain is anything but App. E.g. in the case
1984 // of Domain::SELINUX we have to speculatively check for grants because we have to
1985 // consult the SEPolicy before we know if the caller is the owner.
1986 let access_vector: Option<KeyPermSet> =
1987 if domain != Domain::APP || namespace != caller_uid as i64 {
1988 let access_vector: Option<i32> = tx
1989 .query_row(
1990 "SELECT access_vector FROM persistent.grant
1991 WHERE grantee = ? AND keyentryid = ?;",
1992 params![caller_uid as i64, key.nspace],
1993 |row| row.get(0),
1994 )
1995 .optional()
1996 .context("Domain::KEY_ID: query grant failed.")?;
1997 access_vector.map(|p| p.into())
1998 } else {
1999 None
2000 };
2001
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002002 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002003 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002004 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002005 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002006
Janis Danisevskis45760022021-01-19 16:34:10 -08002007 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002008 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002009 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002010 }
2011 }
2012
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002013 fn load_blob_components(
2014 key_id: i64,
2015 load_bits: KeyEntryLoadBits,
2016 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002017 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002018 let mut stmt = tx
2019 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002020 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002021 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2022 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002023 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002024
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002025 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002026
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002027 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002028 let mut cert_blob: Option<Vec<u8>> = None;
2029 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002030 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002031 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002032 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002033 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002034 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002035 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2036 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002037 key_blob = Some((
2038 row.get(0).context("Failed to extract key blob id.")?,
2039 row.get(2).context("Failed to extract key blob.")?,
2040 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002041 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002042 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002043 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002044 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002045 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002046 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002047 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002048 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002049 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002050 (SubComponentType::CERT, _, _)
2051 | (SubComponentType::CERT_CHAIN, _, _)
2052 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002053 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2054 }
2055 Ok(())
2056 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002057 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002058
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002059 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2060 Ok(Some((
2061 blob,
2062 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002063 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002064 )))
2065 })?;
2066
2067 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002068 }
2069
2070 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2071 let mut stmt = tx
2072 .prepare(
2073 "SELECT tag, data, security_level from persistent.keyparameter
2074 WHERE keyentryid = ?;",
2075 )
2076 .context("In load_key_parameters: prepare statement failed.")?;
2077
2078 let mut parameters: Vec<KeyParameter> = Vec::new();
2079
2080 let mut rows =
2081 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002082 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002083 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2084 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002085 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002086 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002087 .context("Failed to read KeyParameter.")?,
2088 );
2089 Ok(())
2090 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002091 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002092
2093 Ok(parameters)
2094 }
2095
Qi Wub9433b52020-12-01 14:52:46 +08002096 /// Decrements the usage count of a limited use key. This function first checks whether the
2097 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2098 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2099 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002100 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002101 let _wp = wd::watch("KeystoreDB::check_and_update_key_usage_count");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002102
David Drysdale7b9ca232024-05-23 18:19:46 +01002103 self.with_transaction(Immediate("TX_check_and_update_key_usage_count"), |tx| {
Qi Wub9433b52020-12-01 14:52:46 +08002104 let limit: Option<i32> = tx
2105 .query_row(
2106 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2107 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2108 |row| row.get(0),
2109 )
2110 .optional()
2111 .context("Trying to load usage count")?;
2112
2113 let limit = limit
2114 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2115 .context("The Key no longer exists. Key is exhausted.")?;
2116
2117 tx.execute(
2118 "UPDATE persistent.keyparameter
2119 SET data = data - 1
2120 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2121 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2122 )
2123 .context("Failed to update key usage count.")?;
2124
2125 match limit {
2126 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002127 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002128 .context("Trying to mark limited use key for deletion."),
2129 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002130 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002131 }
2132 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002133 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002134 }
2135
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002136 /// Load a key entry by the given key descriptor.
2137 /// It uses the `check_permission` callback to verify if the access is allowed
2138 /// given the key access tuple read from the database using `load_access_tuple`.
2139 /// With `load_bits` the caller may specify which blobs shall be loaded from
2140 /// the blob database.
2141 pub fn load_key_entry(
2142 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002143 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002144 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002145 load_bits: KeyEntryLoadBits,
2146 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002147 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2148 ) -> Result<(KeyIdGuard, KeyEntry)> {
David Drysdale541846b2024-05-23 13:16:07 +01002149 let _wp = wd::watch("KeystoreDB::load_key_entry");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002150
Janis Danisevskis66784c42021-01-27 08:40:25 -08002151 loop {
2152 match self.load_key_entry_internal(
2153 key,
2154 key_type,
2155 load_bits,
2156 caller_uid,
2157 &check_permission,
2158 ) {
2159 Ok(result) => break Ok(result),
2160 Err(e) => {
2161 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01002162 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08002163 continue;
2164 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002165 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002166 }
2167 }
2168 }
2169 }
2170 }
2171
2172 fn load_key_entry_internal(
2173 &mut self,
2174 key: &KeyDescriptor,
2175 key_type: KeyType,
2176 load_bits: KeyEntryLoadBits,
2177 caller_uid: u32,
2178 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002179 ) -> Result<(KeyIdGuard, KeyEntry)> {
2180 // KEY ID LOCK 1/2
2181 // If we got a key descriptor with a key id we can get the lock right away.
2182 // Otherwise we have to defer it until we know the key id.
2183 let key_id_guard = match key.domain {
2184 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2185 _ => None,
2186 };
2187
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002188 let tx = self
2189 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002190 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002191 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002192
2193 // Load the key_id and complete the access control tuple.
2194 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002195 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002196
2197 // Perform access control. It is vital that we return here if the permission is denied.
2198 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002199 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002200
Janis Danisevskisaec14592020-11-12 09:41:49 -08002201 // KEY ID LOCK 2/2
2202 // If we did not get a key id lock by now, it was because we got a key descriptor
2203 // without a key id. At this point we got the key id, so we can try and get a lock.
2204 // However, we cannot block here, because we are in the middle of the transaction.
2205 // So first we try to get the lock non blocking. If that fails, we roll back the
2206 // transaction and block until we get the lock. After we successfully got the lock,
2207 // we start a new transaction and load the access tuple again.
2208 //
2209 // We don't need to perform access control again, because we already established
2210 // that the caller had access to the given key. But we need to make sure that the
2211 // key id still exists. So we have to load the key entry by key id this time.
2212 let (key_id_guard, tx) = match key_id_guard {
2213 None => match KEY_ID_LOCK.try_get(key_id) {
2214 None => {
2215 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002216 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002217
Janis Danisevskisaec14592020-11-12 09:41:49 -08002218 // Block until we have a key id lock.
2219 let key_id_guard = KEY_ID_LOCK.get(key_id);
2220
2221 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002222 let tx = self
2223 .conn
2224 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002225 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002226
2227 Self::load_access_tuple(
2228 &tx,
2229 // This time we have to load the key by the retrieved key id, because the
2230 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002231 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002232 domain: Domain::KEY_ID,
2233 nspace: key_id,
2234 ..Default::default()
2235 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002236 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002237 caller_uid,
2238 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002239 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002240 (key_id_guard, tx)
2241 }
2242 Some(l) => (l, tx),
2243 },
2244 Some(key_id_guard) => (key_id_guard, tx),
2245 };
2246
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002247 let key_entry =
2248 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002249
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002250 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002251
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002252 Ok((key_id_guard, key_entry))
2253 }
2254
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002255 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002256 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002257 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2258 .context("Trying to delete keyentry.")?;
2259 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2260 .context("Trying to delete keymetadata.")?;
2261 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2262 .context("Trying to delete keyparameters.")?;
2263 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2264 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002265 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002266 }
2267
2268 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002269 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002270 pub fn unbind_key(
2271 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002272 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 key_type: KeyType,
2274 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002275 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002276 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002277 let _wp = wd::watch("KeystoreDB::unbind_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002278
David Drysdale7b9ca232024-05-23 18:19:46 +01002279 self.with_transaction(Immediate("TX_unbind_key"), |tx| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002280 let (key_id, access_key_descriptor, access_vector) =
2281 Self::load_access_tuple(tx, key, key_type, caller_uid)
2282 .context("Trying to get access tuple.")?;
2283
2284 // Perform access control. It is vital that we return here if the permission is denied.
2285 // So do not touch that '?' at the end.
2286 check_permission(&access_key_descriptor, access_vector)
2287 .context("While checking permission.")?;
2288
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002289 Self::mark_unreferenced(tx, key_id)
2290 .map(|need_gc| (need_gc, ()))
2291 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002292 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002293 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002294 }
2295
Max Bires8e93d2b2021-01-14 13:17:59 -08002296 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2297 tx.query_row(
2298 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2299 params![key_id],
2300 |row| row.get(0),
2301 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002302 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002303 }
2304
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002305 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2306 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2307 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002308 let _wp = wd::watch("KeystoreDB::unbind_keys_for_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002309
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002310 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002311 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002312 }
David Drysdale7b9ca232024-05-23 18:19:46 +01002313 self.with_transaction(Immediate("TX_unbind_keys_for_namespace"), |tx| {
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002314 tx.execute(
2315 "DELETE FROM persistent.keymetadata
2316 WHERE keyentryid IN (
2317 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002318 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002319 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002320 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002321 )
2322 .context("Trying to delete keymetadata.")?;
2323 tx.execute(
2324 "DELETE FROM persistent.keyparameter
2325 WHERE keyentryid IN (
2326 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002327 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002328 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002329 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002330 )
2331 .context("Trying to delete keyparameters.")?;
2332 tx.execute(
2333 "DELETE FROM persistent.grant
2334 WHERE keyentryid IN (
2335 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002336 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002337 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002338 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002339 )
2340 .context("Trying to delete grants.")?;
2341 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002342 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002343 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2344 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002345 )
2346 .context("Trying to delete keyentry.")?;
2347 Ok(()).need_gc()
2348 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002349 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002350 }
2351
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002352 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002353 let _wp = wd::watch("KeystoreDB::cleanup_unreferenced");
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002354 {
2355 tx.execute(
2356 "DELETE FROM persistent.keymetadata
2357 WHERE keyentryid IN (
2358 SELECT id FROM persistent.keyentry
2359 WHERE state = ?
2360 );",
2361 params![KeyLifeCycle::Unreferenced],
2362 )
2363 .context("Trying to delete keymetadata.")?;
2364 tx.execute(
2365 "DELETE FROM persistent.keyparameter
2366 WHERE keyentryid IN (
2367 SELECT id FROM persistent.keyentry
2368 WHERE state = ?
2369 );",
2370 params![KeyLifeCycle::Unreferenced],
2371 )
2372 .context("Trying to delete keyparameters.")?;
2373 tx.execute(
2374 "DELETE FROM persistent.grant
2375 WHERE keyentryid IN (
2376 SELECT id FROM persistent.keyentry
2377 WHERE state = ?
2378 );",
2379 params![KeyLifeCycle::Unreferenced],
2380 )
2381 .context("Trying to delete grants.")?;
2382 tx.execute(
2383 "DELETE FROM persistent.keyentry
2384 WHERE state = ?;",
2385 params![KeyLifeCycle::Unreferenced],
2386 )
2387 .context("Trying to delete keyentry.")?;
2388 Result::<()>::Ok(())
2389 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002390 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002391 }
2392
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00002393 /// Deletes all keys for the given user, including both client keys and super keys.
2394 pub fn unbind_keys_for_user(&mut self, user_id: u32) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002395 let _wp = wd::watch("KeystoreDB::unbind_keys_for_user");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002396
David Drysdale7b9ca232024-05-23 18:19:46 +01002397 self.with_transaction(Immediate("TX_unbind_keys_for_user"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00002398 let mut stmt = tx
2399 .prepare(&format!(
2400 "SELECT id from persistent.keyentry
2401 WHERE (
2402 key_type = ?
2403 AND domain = ?
2404 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2405 AND state = ?
2406 ) OR (
2407 key_type = ?
2408 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002409 AND state = ?
2410 );",
2411 aid_user_offset = AID_USER_OFFSET
2412 ))
2413 .context(concat!(
2414 "In unbind_keys_for_user. ",
2415 "Failed to prepare the query to find the keys created by apps."
2416 ))?;
2417
2418 let mut rows = stmt
2419 .query(params![
2420 // WHERE client key:
2421 KeyType::Client,
2422 Domain::APP.0 as u32,
2423 user_id,
2424 KeyLifeCycle::Live,
2425 // OR super key:
2426 KeyType::Super,
2427 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002428 KeyLifeCycle::Live
2429 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002430 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002431
2432 let mut key_ids: Vec<i64> = Vec::new();
2433 db_utils::with_rows_extract_all(&mut rows, |row| {
2434 key_ids
2435 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2436 Ok(())
2437 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002438 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002439
2440 let mut notify_gc = false;
2441 for key_id in key_ids {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002442 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002443 .context("In unbind_keys_for_user.")?
2444 || notify_gc;
2445 }
2446 Ok(()).do_gc(notify_gc)
2447 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002448 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002449 }
2450
Eric Biggersb0478cf2023-10-27 03:55:29 +00002451 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2452 /// This runs when the user's lock screen is being changed to Swipe or None.
2453 ///
2454 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2455 /// such keys also require user authentication. Keystore's concept of user authentication is
2456 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2457 /// authentication is no longer possible. In contrast, keys that just require that the device
2458 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2459 /// is always considered "unlocked" in that case.
2460 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002461 let _wp = wd::watch("KeystoreDB::unbind_auth_bound_keys_for_user");
Eric Biggersb0478cf2023-10-27 03:55:29 +00002462
David Drysdale7b9ca232024-05-23 18:19:46 +01002463 self.with_transaction(Immediate("TX_unbind_auth_bound_keys_for_user"), |tx| {
Eric Biggersb0478cf2023-10-27 03:55:29 +00002464 let mut stmt = tx
2465 .prepare(&format!(
2466 "SELECT id from persistent.keyentry
2467 WHERE key_type = ?
2468 AND domain = ?
2469 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2470 AND state = ?;",
2471 aid_user_offset = AID_USER_OFFSET
2472 ))
2473 .context(concat!(
2474 "In unbind_auth_bound_keys_for_user. ",
2475 "Failed to prepare the query to find the keys created by apps."
2476 ))?;
2477
2478 let mut rows = stmt
2479 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2480 .context(ks_err!("Failed to query the keys created by apps."))?;
2481
2482 let mut key_ids: Vec<i64> = Vec::new();
2483 db_utils::with_rows_extract_all(&mut rows, |row| {
2484 key_ids
2485 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2486 Ok(())
2487 })
2488 .context(ks_err!())?;
2489
2490 let mut notify_gc = false;
2491 let mut num_unbound = 0;
2492 for key_id in key_ids {
2493 // Load the key parameters and filter out non-auth-bound keys. To identify
2494 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2495 // could also be used, but UserSecureID is what Keystore treats as authoritative
2496 // when actually enforcing the key parameters (it might not matter, though).
2497 let params = Self::load_key_parameters(key_id, tx)
2498 .context("Failed to load key parameters.")?;
2499 let is_auth_bound_key = params.iter().any(|kp| {
2500 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2501 });
2502 if is_auth_bound_key {
2503 notify_gc = Self::mark_unreferenced(tx, key_id)
2504 .context("In unbind_auth_bound_keys_for_user.")?
2505 || notify_gc;
2506 num_unbound += 1;
2507 }
2508 }
2509 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2510 Ok(()).do_gc(notify_gc)
2511 })
2512 .context(ks_err!())
2513 }
2514
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002515 fn load_key_components(
2516 tx: &Transaction,
2517 load_bits: KeyEntryLoadBits,
2518 key_id: i64,
2519 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002520 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002521
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002522 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002523 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002524
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002525 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002526 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002527
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002528 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002529 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002530
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002531 Ok(KeyEntry {
2532 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002533 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002534 cert: cert_blob,
2535 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002536 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002537 parameters,
2538 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002539 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002540 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002541 }
2542
Eran Messeri24f31972023-01-25 17:00:33 +00002543 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2544 /// aliases are greater than the specified 'start_past_alias'. If no value
2545 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002546 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002547 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002548 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002549 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002550 &mut self,
2551 domain: Domain,
2552 namespace: i64,
2553 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002554 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002555 ) -> Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002556 let _wp = wd::watch("KeystoreDB::list_past_alias");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002557
Eran Messeri24f31972023-01-25 17:00:33 +00002558 let query = format!(
2559 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002560 WHERE domain = ?
2561 AND namespace = ?
2562 AND alias IS NOT NULL
2563 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002564 AND key_type = ?
2565 {}
2566 ORDER BY alias ASC;",
2567 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2568 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002569
Eran Messeri24f31972023-01-25 17:00:33 +00002570 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2571 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2572
2573 let mut rows = match start_past_alias {
2574 Some(past_alias) => stmt
2575 .query(params![
2576 domain.0 as u32,
2577 namespace,
2578 KeyLifeCycle::Live,
2579 key_type,
2580 past_alias
2581 ])
2582 .context(ks_err!("Failed to query."))?,
2583 None => stmt
2584 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2585 .context(ks_err!("Failed to query."))?,
2586 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002587
Janis Danisevskis66784c42021-01-27 08:40:25 -08002588 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2589 db_utils::with_rows_extract_all(&mut rows, |row| {
2590 descriptors.push(KeyDescriptor {
2591 domain,
2592 nspace: namespace,
2593 alias: Some(row.get(0).context("Trying to extract alias.")?),
2594 blob: None,
2595 });
2596 Ok(())
2597 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002598 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002599 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002600 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002601 }
2602
Eran Messeri24f31972023-01-25 17:00:33 +00002603 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2604 /// Domain must be APP or SELINUX, the caller must make sure of that.
2605 pub fn count_keys(
2606 &mut self,
2607 domain: Domain,
2608 namespace: i64,
2609 key_type: KeyType,
2610 ) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01002611 let _wp = wd::watch("KeystoreDB::countKeys");
Eran Messeri24f31972023-01-25 17:00:33 +00002612
2613 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2614 tx.query_row(
2615 "SELECT COUNT(alias) FROM persistent.keyentry
2616 WHERE domain = ?
2617 AND namespace = ?
2618 AND alias IS NOT NULL
2619 AND state = ?
2620 AND key_type = ?;",
2621 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2622 |row| row.get(0),
2623 )
2624 .context(ks_err!("Failed to count number of keys."))
2625 .no_gc()
2626 })?;
2627 Ok(num_keys)
2628 }
2629
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002630 /// Adds a grant to the grant table.
2631 /// Like `load_key_entry` this function loads the access tuple before
2632 /// it uses the callback for a permission check. Upon success,
2633 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2634 /// grant table. The new row will have a randomized id, which is used as
2635 /// grant id in the namespace field of the resulting KeyDescriptor.
2636 pub fn grant(
2637 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002638 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002639 caller_uid: u32,
2640 grantee_uid: u32,
2641 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002642 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002643 ) -> Result<KeyDescriptor> {
David Drysdale541846b2024-05-23 13:16:07 +01002644 let _wp = wd::watch("KeystoreDB::grant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002645
David Drysdale7b9ca232024-05-23 18:19:46 +01002646 self.with_transaction(Immediate("TX_grant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002647 // Load the key_id and complete the access control tuple.
2648 // We ignore the access vector here because grants cannot be granted.
2649 // The access vector returned here expresses the permissions the
2650 // grantee has if key.domain == Domain::GRANT. But this vector
2651 // cannot include the grant permission by design, so there is no way the
2652 // subsequent permission check can pass.
2653 // We could check key.domain == Domain::GRANT and fail early.
2654 // But even if we load the access tuple by grant here, the permission
2655 // check denies the attempt to create a grant by grant descriptor.
2656 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002657 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002658
Janis Danisevskis66784c42021-01-27 08:40:25 -08002659 // Perform access control. It is vital that we return here if the permission
2660 // was denied. So do not touch that '?' at the end of the line.
2661 // This permission check checks if the caller has the grant permission
2662 // for the given key and in addition to all of the permissions
2663 // expressed in `access_vector`.
2664 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002665 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666
Janis Danisevskis66784c42021-01-27 08:40:25 -08002667 let grant_id = if let Some(grant_id) = tx
2668 .query_row(
2669 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002670 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002671 params![key_id, grantee_uid],
2672 |row| row.get(0),
2673 )
2674 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002675 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002676 {
2677 tx.execute(
2678 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002679 SET access_vector = ?
2680 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002681 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002682 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002683 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002684 grant_id
2685 } else {
2686 Self::insert_with_retry(|id| {
2687 tx.execute(
2688 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2689 VALUES (?, ?, ?, ?);",
2690 params![id, grantee_uid, key_id, i32::from(access_vector)],
2691 )
2692 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002693 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002694 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002695
Janis Danisevskis66784c42021-01-27 08:40:25 -08002696 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002697 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002698 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002699 }
2700
2701 /// This function checks permissions like `grant` and `load_key_entry`
2702 /// before removing a grant from the grant table.
2703 pub fn ungrant(
2704 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002705 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002706 caller_uid: u32,
2707 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002708 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002709 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002710 let _wp = wd::watch("KeystoreDB::ungrant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002711
David Drysdale7b9ca232024-05-23 18:19:46 +01002712 self.with_transaction(Immediate("TX_ungrant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002713 // Load the key_id and complete the access control tuple.
2714 // We ignore the access vector here because grants cannot be granted.
2715 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002716 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002717
Janis Danisevskis66784c42021-01-27 08:40:25 -08002718 // Perform access control. We must return here if the permission
2719 // was denied. So do not touch the '?' at the end of this line.
2720 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002721 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002722
Janis Danisevskis66784c42021-01-27 08:40:25 -08002723 tx.execute(
2724 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002725 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002726 params![key_id, grantee_uid],
2727 )
2728 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002729
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002730 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002731 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002732 }
2733
Joel Galenson845f74b2020-09-09 14:11:55 -07002734 // Generates a random id and passes it to the given function, which will
2735 // try to insert it into a database. If that insertion fails, retry;
2736 // otherwise return the id.
2737 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2738 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002739 let newid: i64 = match random() {
2740 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2741 i => i,
2742 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002743 match inserter(newid) {
2744 // If the id already existed, try again.
2745 Err(rusqlite::Error::SqliteFailure(
2746 libsqlite3_sys::Error {
2747 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2748 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2749 },
2750 _,
2751 )) => (),
2752 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002753 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002754 }
2755 _ => return Ok(newid),
2756 }
2757 }
2758 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002759
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002760 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2761 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002762 self.perboot
2763 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002764 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002765
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002766 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002767 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002768 where
2769 F: Fn(&AuthTokenEntry) -> bool,
2770 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002771 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002772 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002773
2774 /// Load descriptor of a key by key id
2775 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002776 let _wp = wd::watch("KeystoreDB::load_key_descriptor");
Pavel Grafovf45034a2021-05-12 22:35:45 +01002777
2778 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2779 tx.query_row(
2780 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2781 params![key_id],
2782 |row| {
2783 Ok(KeyDescriptor {
2784 domain: Domain(row.get(0)?),
2785 nspace: row.get(1)?,
2786 alias: row.get(2)?,
2787 blob: None,
2788 })
2789 },
2790 )
2791 .optional()
2792 .context("Trying to load key descriptor")
2793 .no_gc()
2794 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002795 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002796 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002797
2798 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2799 /// (for the given user_id).
2800 /// This is helpful for finding out which apps will have their keys invalidated when
2801 /// the user changes biometrics enrollment or removes their LSKF.
2802 pub fn get_app_uids_affected_by_sid(
2803 &mut self,
2804 user_id: i32,
2805 secure_user_id: i64,
2806 ) -> Result<Vec<i64>> {
David Drysdale541846b2024-05-23 13:16:07 +01002807 let _wp = wd::watch("KeystoreDB::get_app_uids_affected_by_sid");
Eran Messeri4dc27b52024-01-09 12:43:31 +00002808
David Drysdale7b9ca232024-05-23 18:19:46 +01002809 let ids = self.with_transaction(Immediate("TX_get_app_uids_affected_by_sid"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002810 let mut stmt = tx
2811 .prepare(&format!(
2812 "SELECT id, namespace from persistent.keyentry
2813 WHERE key_type = ?
2814 AND domain = ?
2815 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2816 AND state = ?;",
2817 ))
2818 .context(concat!(
2819 "In get_app_uids_affected_by_sid, ",
2820 "failed to prepare the query to find the keys created by apps."
2821 ))?;
2822
2823 let mut rows = stmt
2824 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2825 .context(ks_err!("Failed to query the keys created by apps."))?;
2826
2827 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2828 db_utils::with_rows_extract_all(&mut rows, |row| {
2829 key_ids_and_app_uids.insert(
2830 row.get(0).context("Failed to read key id of a key created by an app.")?,
2831 row.get(1).context("Failed to read the app uid")?,
2832 );
2833 Ok(())
2834 })?;
2835 Ok(key_ids_and_app_uids).no_gc()
2836 })?;
2837 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
David Drysdale7b9ca232024-05-23 18:19:46 +01002838 for (key_id, app_uid) in ids {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002839 // Read the key parameters for each key in its own transaction. It is OK to ignore
2840 // an error to get the properties of a particular key since it might have been deleted
2841 // under our feet after the previous transaction concluded. If the key was deleted
2842 // then it is no longer applicable if it was auth-bound or not.
2843 if let Ok(is_key_bound_to_sid) =
David Drysdale7b9ca232024-05-23 18:19:46 +01002844 self.with_transaction(Immediate("TX_get_app_uids_affects_by_sid 2"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002845 let params = Self::load_key_parameters(key_id, tx)
2846 .context("Failed to load key parameters.")?;
2847 // Check if the key is bound to this secure user ID.
2848 let is_key_bound_to_sid = params.iter().any(|kp| {
2849 matches!(
2850 kp.key_parameter_value(),
2851 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2852 )
2853 });
2854 Ok(is_key_bound_to_sid).no_gc()
2855 })
2856 {
2857 if is_key_bound_to_sid {
2858 app_uids_affected_by_sid.insert(app_uid);
2859 }
2860 }
2861 }
2862
2863 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2864 Ok(app_uids_vec)
2865 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002866}
2867
2868#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002869pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002870
2871 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002872 use crate::key_parameter::{
2873 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2874 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2875 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002876 use crate::key_perm_set;
2877 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002878 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002879 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002880 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2881 HardwareAuthToken::HardwareAuthToken,
2882 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002883 };
2884 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002885 Timestamp::Timestamp,
2886 };
Joel Galenson0891bc12020-07-20 10:37:03 -07002887 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002888 use std::collections::BTreeMap;
2889 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002890 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002891 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002892 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002893 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002894 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002895 #[cfg(disabled)]
2896 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002897
Seth Moore7ee79f92021-12-07 11:42:49 -08002898 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002899 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002900
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002901 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
David Drysdale7b9ca232024-05-23 18:19:46 +01002902 db.with_transaction(Immediate("TX_new_test_db"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002903 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002904 })?;
2905 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002906 }
2907
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002908 fn rebind_alias(
2909 db: &mut KeystoreDB,
2910 newid: &KeyIdGuard,
2911 alias: &str,
2912 domain: Domain,
2913 namespace: i64,
2914 ) -> Result<bool> {
David Drysdale7b9ca232024-05-23 18:19:46 +01002915 db.with_transaction(Immediate("TX_rebind_alias"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002916 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002917 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002918 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002919 }
2920
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002921 #[test]
2922 fn datetime() -> Result<()> {
2923 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002924 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002925 let now = SystemTime::now();
2926 let duration = Duration::from_secs(1000);
2927 let then = now.checked_sub(duration).unwrap();
2928 let soon = now.checked_add(duration).unwrap();
2929 conn.execute(
2930 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2931 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2932 )?;
2933 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002934 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002935 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2936 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2937 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2938 assert!(rows.next()?.is_none());
2939 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2940 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2941 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2942 Ok(())
2943 }
2944
Joel Galenson0891bc12020-07-20 10:37:03 -07002945 // Ensure that we're using the "injected" random function, not the real one.
2946 #[test]
2947 fn test_mocked_random() {
2948 let rand1 = random();
2949 let rand2 = random();
2950 let rand3 = random();
2951 if rand1 == rand2 {
2952 assert_eq!(rand2 + 1, rand3);
2953 } else {
2954 assert_eq!(rand1 + 1, rand2);
2955 assert_eq!(rand2, rand3);
2956 }
2957 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002958
Joel Galenson26f4d012020-07-17 14:57:21 -07002959 // Test that we have the correct tables.
2960 #[test]
2961 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002962 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002963 let tables = db
2964 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002965 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002966 .query_map(params![], |row| row.get(0))?
2967 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002968 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002969 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002970 assert_eq!(tables[1], "blobmetadata");
2971 assert_eq!(tables[2], "grant");
2972 assert_eq!(tables[3], "keyentry");
2973 assert_eq!(tables[4], "keymetadata");
2974 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07002975 Ok(())
2976 }
2977
2978 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002979 fn test_auth_token_table_invariant() -> Result<()> {
2980 let mut db = new_test_db()?;
2981 let auth_token1 = HardwareAuthToken {
2982 challenge: i64::MAX,
2983 userId: 200,
2984 authenticatorId: 200,
2985 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2986 timestamp: Timestamp { milliSeconds: 500 },
2987 mac: String::from("mac").into_bytes(),
2988 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002989 db.insert_auth_token(&auth_token1);
2990 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002991 assert_eq!(auth_tokens_returned.len(), 1);
2992
2993 // insert another auth token with the same values for the columns in the UNIQUE constraint
2994 // of the auth token table and different value for timestamp
2995 let auth_token2 = HardwareAuthToken {
2996 challenge: i64::MAX,
2997 userId: 200,
2998 authenticatorId: 200,
2999 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3000 timestamp: Timestamp { milliSeconds: 600 },
3001 mac: String::from("mac").into_bytes(),
3002 };
3003
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003004 db.insert_auth_token(&auth_token2);
3005 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003006 assert_eq!(auth_tokens_returned.len(), 1);
3007
3008 if let Some(auth_token) = auth_tokens_returned.pop() {
3009 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3010 }
3011
3012 // insert another auth token with the different values for the columns in the UNIQUE
3013 // constraint of the auth token table
3014 let auth_token3 = HardwareAuthToken {
3015 challenge: i64::MAX,
3016 userId: 201,
3017 authenticatorId: 200,
3018 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3019 timestamp: Timestamp { milliSeconds: 600 },
3020 mac: String::from("mac").into_bytes(),
3021 };
3022
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003023 db.insert_auth_token(&auth_token3);
3024 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003025 assert_eq!(auth_tokens_returned.len(), 2);
3026
3027 Ok(())
3028 }
3029
3030 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003031 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3032 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003033 }
3034
David Drysdale8c4c4f32023-10-31 12:14:11 +00003035 fn create_key_entry(
3036 db: &mut KeystoreDB,
3037 domain: &Domain,
3038 namespace: &i64,
3039 key_type: KeyType,
3040 km_uuid: &Uuid,
3041 ) -> Result<KeyIdGuard> {
David Drysdale7b9ca232024-05-23 18:19:46 +01003042 db.with_transaction(Immediate("TX_create_key_entry"), |tx| {
David Drysdale8c4c4f32023-10-31 12:14:11 +00003043 KeystoreDB::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
3044 })
3045 }
3046
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003047 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003048 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003049 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003050 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003051
David Drysdale8c4c4f32023-10-31 12:14:11 +00003052 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003053 let entries = get_keyentry(&db)?;
3054 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003055
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003056 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003057
3058 let entries_new = get_keyentry(&db)?;
3059 assert_eq!(entries, entries_new);
3060 Ok(())
3061 }
3062
3063 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003064 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003065 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3066 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003067 }
3068
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003069 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003070
David Drysdale8c4c4f32023-10-31 12:14:11 +00003071 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3072 create_key_entry(&mut db, &Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003073
3074 let entries = get_keyentry(&db)?;
3075 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003076 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3077 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003078
3079 // Test that we must pass in a valid Domain.
3080 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003081 create_key_entry(&mut db, &Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003082 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003083 );
3084 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003085 create_key_entry(&mut db, &Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003086 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003087 );
3088 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003089 create_key_entry(&mut db, &Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003090 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003091 );
3092
3093 Ok(())
3094 }
3095
Joel Galenson33c04ad2020-08-03 11:04:38 -07003096 #[test]
3097 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003098 fn extractor(
3099 ke: &KeyEntryRow,
3100 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3101 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003102 }
3103
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003104 let mut db = new_test_db()?;
David Drysdale8c4c4f32023-10-31 12:14:11 +00003105 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3106 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003107 let entries = get_keyentry(&db)?;
3108 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003109 assert_eq!(
3110 extractor(&entries[0]),
3111 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3112 );
3113 assert_eq!(
3114 extractor(&entries[1]),
3115 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3116 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003117
3118 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003119 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003120 let entries = get_keyentry(&db)?;
3121 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003122 assert_eq!(
3123 extractor(&entries[0]),
3124 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3125 );
3126 assert_eq!(
3127 extractor(&entries[1]),
3128 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3129 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003130
3131 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003132 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003133 let entries = get_keyentry(&db)?;
3134 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003135 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3136 assert_eq!(
3137 extractor(&entries[1]),
3138 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3139 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003140
3141 // Test that we must pass in a valid Domain.
3142 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003143 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003144 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003145 );
3146 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003147 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003148 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003149 );
3150 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003151 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003152 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003153 );
3154
3155 // Test that we correctly handle setting an alias for something that does not exist.
3156 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003157 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003158 "Expected to update a single entry but instead updated 0",
3159 );
3160 // Test that we correctly abort the transaction in this case.
3161 let entries = get_keyentry(&db)?;
3162 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003163 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3164 assert_eq!(
3165 extractor(&entries[1]),
3166 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3167 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003168
3169 Ok(())
3170 }
3171
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003172 #[test]
3173 fn test_grant_ungrant() -> Result<()> {
3174 const CALLER_UID: u32 = 15;
3175 const GRANTEE_UID: u32 = 12;
3176 const SELINUX_NAMESPACE: i64 = 7;
3177
3178 let mut db = new_test_db()?;
3179 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003180 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3181 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3182 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003183 )?;
3184 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003185 domain: super::Domain::APP,
3186 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003187 alias: Some("key".to_string()),
3188 blob: None,
3189 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003190 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3191 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003192
3193 // Reset totally predictable random number generator in case we
3194 // are not the first test running on this thread.
3195 reset_random();
3196 let next_random = 0i64;
3197
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003198 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003199 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003200 assert_eq!(*a, PVEC1);
3201 assert_eq!(
3202 *k,
3203 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003204 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003205 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003206 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003207 alias: Some("key".to_string()),
3208 blob: None,
3209 }
3210 );
3211 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003212 })
3213 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003214
3215 assert_eq!(
3216 app_granted_key,
3217 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003218 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003219 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003220 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003221 alias: None,
3222 blob: None,
3223 }
3224 );
3225
3226 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003227 domain: super::Domain::SELINUX,
3228 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003229 alias: Some("yek".to_string()),
3230 blob: None,
3231 };
3232
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003233 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003234 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003235 assert_eq!(*a, PVEC1);
3236 assert_eq!(
3237 *k,
3238 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003239 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003240 // namespace must be the supplied SELinux
3241 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003242 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003243 alias: Some("yek".to_string()),
3244 blob: None,
3245 }
3246 );
3247 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003248 })
3249 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003250
3251 assert_eq!(
3252 selinux_granted_key,
3253 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003254 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003255 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003256 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003257 alias: None,
3258 blob: None,
3259 }
3260 );
3261
3262 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003263 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003264 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003265 assert_eq!(*a, PVEC2);
3266 assert_eq!(
3267 *k,
3268 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003269 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003270 // namespace must be the supplied SELinux
3271 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003272 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003273 alias: Some("yek".to_string()),
3274 blob: None,
3275 }
3276 );
3277 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003278 })
3279 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003280
3281 assert_eq!(
3282 selinux_granted_key,
3283 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003284 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003285 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003286 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003287 alias: None,
3288 blob: None,
3289 }
3290 );
3291
3292 {
3293 // Limiting scope of stmt, because it borrows db.
3294 let mut stmt = db
3295 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003296 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003297 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3298 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3299 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003300
3301 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003302 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003304 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003305 assert!(rows.next().is_none());
3306 }
3307
3308 debug_dump_keyentry_table(&mut db)?;
3309 println!("app_key {:?}", app_key);
3310 println!("selinux_key {:?}", selinux_key);
3311
Janis Danisevskis66784c42021-01-27 08:40:25 -08003312 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3313 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003314
3315 Ok(())
3316 }
3317
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003318 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003319 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3320 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3321
3322 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003323 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003324 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003325 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003326 let mut blob_metadata = BlobMetaData::new();
3327 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3328 db.set_blob(
3329 &key_id,
3330 SubComponentType::KEY_BLOB,
3331 Some(TEST_KEY_BLOB),
3332 Some(&blob_metadata),
3333 )?;
3334 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3335 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003336 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003337
3338 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003339 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003340 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003341 )?;
3342 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003343 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003344 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003345 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003346 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003347 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003348 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003349 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003350 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003351 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003352
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003353 drop(rows);
3354 drop(stmt);
3355
3356 assert_eq!(
David Drysdale7b9ca232024-05-23 18:19:46 +01003357 db.with_transaction(Immediate("TX_test"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003358 BlobMetaData::load_from_db(id, tx).no_gc()
3359 })
3360 .expect("Should find blob metadata."),
3361 blob_metadata
3362 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003363 Ok(())
3364 }
3365
3366 static TEST_ALIAS: &str = "my super duper key";
3367
3368 #[test]
3369 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3370 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003371 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003372 .context("test_insert_and_load_full_keyentry_domain_app")?
3373 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003374 let (_key_guard, key_entry) = db
3375 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003376 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003377 domain: Domain::APP,
3378 nspace: 0,
3379 alias: Some(TEST_ALIAS.to_string()),
3380 blob: None,
3381 },
3382 KeyType::Client,
3383 KeyEntryLoadBits::BOTH,
3384 1,
3385 |_k, _av| Ok(()),
3386 )
3387 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003388 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003389
3390 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003391 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003392 domain: Domain::APP,
3393 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003394 alias: Some(TEST_ALIAS.to_string()),
3395 blob: None,
3396 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003397 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003398 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003399 |_, _| Ok(()),
3400 )
3401 .unwrap();
3402
3403 assert_eq!(
3404 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3405 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003406 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003407 domain: Domain::APP,
3408 nspace: 0,
3409 alias: Some(TEST_ALIAS.to_string()),
3410 blob: None,
3411 },
3412 KeyType::Client,
3413 KeyEntryLoadBits::NONE,
3414 1,
3415 |_k, _av| Ok(()),
3416 )
3417 .unwrap_err()
3418 .root_cause()
3419 .downcast_ref::<KsError>()
3420 );
3421
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003422 Ok(())
3423 }
3424
3425 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003426 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3427 let mut db = new_test_db()?;
3428
3429 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003430 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003431 domain: Domain::APP,
3432 nspace: 1,
3433 alias: Some(TEST_ALIAS.to_string()),
3434 blob: None,
3435 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003436 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003437 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003438 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003439 )
3440 .expect("Trying to insert cert.");
3441
3442 let (_key_guard, mut key_entry) = db
3443 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003444 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003445 domain: Domain::APP,
3446 nspace: 1,
3447 alias: Some(TEST_ALIAS.to_string()),
3448 blob: None,
3449 },
3450 KeyType::Client,
3451 KeyEntryLoadBits::PUBLIC,
3452 1,
3453 |_k, _av| Ok(()),
3454 )
3455 .expect("Trying to read certificate entry.");
3456
3457 assert!(key_entry.pure_cert());
3458 assert!(key_entry.cert().is_none());
3459 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3460
3461 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003462 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003463 domain: Domain::APP,
3464 nspace: 1,
3465 alias: Some(TEST_ALIAS.to_string()),
3466 blob: None,
3467 },
3468 KeyType::Client,
3469 1,
3470 |_, _| Ok(()),
3471 )
3472 .unwrap();
3473
3474 assert_eq!(
3475 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3476 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003477 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003478 domain: Domain::APP,
3479 nspace: 1,
3480 alias: Some(TEST_ALIAS.to_string()),
3481 blob: None,
3482 },
3483 KeyType::Client,
3484 KeyEntryLoadBits::NONE,
3485 1,
3486 |_k, _av| Ok(()),
3487 )
3488 .unwrap_err()
3489 .root_cause()
3490 .downcast_ref::<KsError>()
3491 );
3492
3493 Ok(())
3494 }
3495
3496 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003497 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3498 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003499 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003500 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3501 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003502 let (_key_guard, key_entry) = db
3503 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003504 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003505 domain: Domain::SELINUX,
3506 nspace: 1,
3507 alias: Some(TEST_ALIAS.to_string()),
3508 blob: None,
3509 },
3510 KeyType::Client,
3511 KeyEntryLoadBits::BOTH,
3512 1,
3513 |_k, _av| Ok(()),
3514 )
3515 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003516 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003517
3518 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003519 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003520 domain: Domain::SELINUX,
3521 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003522 alias: Some(TEST_ALIAS.to_string()),
3523 blob: None,
3524 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003525 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003526 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003527 |_, _| Ok(()),
3528 )
3529 .unwrap();
3530
3531 assert_eq!(
3532 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3533 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003534 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003535 domain: Domain::SELINUX,
3536 nspace: 1,
3537 alias: Some(TEST_ALIAS.to_string()),
3538 blob: None,
3539 },
3540 KeyType::Client,
3541 KeyEntryLoadBits::NONE,
3542 1,
3543 |_k, _av| Ok(()),
3544 )
3545 .unwrap_err()
3546 .root_cause()
3547 .downcast_ref::<KsError>()
3548 );
3549
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003550 Ok(())
3551 }
3552
3553 #[test]
3554 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3555 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003556 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003557 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3558 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003559 let (_, key_entry) = db
3560 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003561 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003562 KeyType::Client,
3563 KeyEntryLoadBits::BOTH,
3564 1,
3565 |_k, _av| Ok(()),
3566 )
3567 .unwrap();
3568
Qi Wub9433b52020-12-01 14:52:46 +08003569 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003570
3571 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003572 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003573 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003574 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003575 |_, _| Ok(()),
3576 )
3577 .unwrap();
3578
3579 assert_eq!(
3580 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3581 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003582 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003583 KeyType::Client,
3584 KeyEntryLoadBits::NONE,
3585 1,
3586 |_k, _av| Ok(()),
3587 )
3588 .unwrap_err()
3589 .root_cause()
3590 .downcast_ref::<KsError>()
3591 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003592
3593 Ok(())
3594 }
3595
3596 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003597 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3598 let mut db = new_test_db()?;
3599 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3600 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3601 .0;
3602 // Update the usage count of the limited use key.
3603 db.check_and_update_key_usage_count(key_id)?;
3604
3605 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003606 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003607 KeyType::Client,
3608 KeyEntryLoadBits::BOTH,
3609 1,
3610 |_k, _av| Ok(()),
3611 )?;
3612
3613 // The usage count is decremented now.
3614 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3615
3616 Ok(())
3617 }
3618
3619 #[test]
3620 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3621 let mut db = new_test_db()?;
3622 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3623 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3624 .0;
3625 // Update the usage count of the limited use key.
3626 db.check_and_update_key_usage_count(key_id).expect(concat!(
3627 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3628 "This should succeed."
3629 ));
3630
3631 // Try to update the exhausted limited use key.
3632 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3633 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3634 "This should fail."
3635 ));
3636 assert_eq!(
3637 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3638 e.root_cause().downcast_ref::<KsError>().unwrap()
3639 );
3640
3641 Ok(())
3642 }
3643
3644 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003645 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3646 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003647 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003648 .context("test_insert_and_load_full_keyentry_from_grant")?
3649 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003650
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003651 let granted_key = db
3652 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003653 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003654 domain: Domain::APP,
3655 nspace: 0,
3656 alias: Some(TEST_ALIAS.to_string()),
3657 blob: None,
3658 },
3659 1,
3660 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003661 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003662 |_k, _av| Ok(()),
3663 )
3664 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003665
3666 debug_dump_grant_table(&mut db)?;
3667
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003668 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003669 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3670 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003671 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003672 Ok(())
3673 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003674 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003675
Qi Wub9433b52020-12-01 14:52:46 +08003676 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003677
Janis Danisevskis66784c42021-01-27 08:40:25 -08003678 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003679
3680 assert_eq!(
3681 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3682 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003683 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003684 KeyType::Client,
3685 KeyEntryLoadBits::NONE,
3686 2,
3687 |_k, _av| Ok(()),
3688 )
3689 .unwrap_err()
3690 .root_cause()
3691 .downcast_ref::<KsError>()
3692 );
3693
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003694 Ok(())
3695 }
3696
Janis Danisevskis45760022021-01-19 16:34:10 -08003697 // This test attempts to load a key by key id while the caller is not the owner
3698 // but a grant exists for the given key and the caller.
3699 #[test]
3700 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3701 let mut db = new_test_db()?;
3702 const OWNER_UID: u32 = 1u32;
3703 const GRANTEE_UID: u32 = 2u32;
3704 const SOMEONE_ELSE_UID: u32 = 3u32;
3705 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3706 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3707 .0;
3708
3709 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003710 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003711 domain: Domain::APP,
3712 nspace: 0,
3713 alias: Some(TEST_ALIAS.to_string()),
3714 blob: None,
3715 },
3716 OWNER_UID,
3717 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003718 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003719 |_k, _av| Ok(()),
3720 )
3721 .unwrap();
3722
3723 debug_dump_grant_table(&mut db)?;
3724
3725 let id_descriptor =
3726 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3727
3728 let (_, key_entry) = db
3729 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003730 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003731 KeyType::Client,
3732 KeyEntryLoadBits::BOTH,
3733 GRANTEE_UID,
3734 |k, av| {
3735 assert_eq!(Domain::APP, k.domain);
3736 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003737 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003738 Ok(())
3739 },
3740 )
3741 .unwrap();
3742
3743 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3744
3745 let (_, key_entry) = db
3746 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003747 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003748 KeyType::Client,
3749 KeyEntryLoadBits::BOTH,
3750 SOMEONE_ELSE_UID,
3751 |k, av| {
3752 assert_eq!(Domain::APP, k.domain);
3753 assert_eq!(OWNER_UID as i64, k.nspace);
3754 assert!(av.is_none());
3755 Ok(())
3756 },
3757 )
3758 .unwrap();
3759
3760 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3761
Janis Danisevskis66784c42021-01-27 08:40:25 -08003762 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003763
3764 assert_eq!(
3765 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3766 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003767 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003768 KeyType::Client,
3769 KeyEntryLoadBits::NONE,
3770 GRANTEE_UID,
3771 |_k, _av| Ok(()),
3772 )
3773 .unwrap_err()
3774 .root_cause()
3775 .downcast_ref::<KsError>()
3776 );
3777
3778 Ok(())
3779 }
3780
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003781 // Creates a key migrates it to a different location and then tries to access it by the old
3782 // and new location.
3783 #[test]
3784 fn test_migrate_key_app_to_app() -> Result<()> {
3785 let mut db = new_test_db()?;
3786 const SOURCE_UID: u32 = 1u32;
3787 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003788 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3789 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003790 let key_id_guard =
3791 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3792 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3793
3794 let source_descriptor: KeyDescriptor = KeyDescriptor {
3795 domain: Domain::APP,
3796 nspace: -1,
3797 alias: Some(SOURCE_ALIAS.to_string()),
3798 blob: None,
3799 };
3800
3801 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3802 domain: Domain::APP,
3803 nspace: -1,
3804 alias: Some(DESTINATION_ALIAS.to_string()),
3805 blob: None,
3806 };
3807
3808 let key_id = key_id_guard.id();
3809
3810 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3811 Ok(())
3812 })
3813 .unwrap();
3814
3815 let (_, key_entry) = db
3816 .load_key_entry(
3817 &destination_descriptor,
3818 KeyType::Client,
3819 KeyEntryLoadBits::BOTH,
3820 DESTINATION_UID,
3821 |k, av| {
3822 assert_eq!(Domain::APP, k.domain);
3823 assert_eq!(DESTINATION_UID as i64, k.nspace);
3824 assert!(av.is_none());
3825 Ok(())
3826 },
3827 )
3828 .unwrap();
3829
3830 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3831
3832 assert_eq!(
3833 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3834 db.load_key_entry(
3835 &source_descriptor,
3836 KeyType::Client,
3837 KeyEntryLoadBits::NONE,
3838 SOURCE_UID,
3839 |_k, _av| Ok(()),
3840 )
3841 .unwrap_err()
3842 .root_cause()
3843 .downcast_ref::<KsError>()
3844 );
3845
3846 Ok(())
3847 }
3848
3849 // Creates a key migrates it to a different location and then tries to access it by the old
3850 // and new location.
3851 #[test]
3852 fn test_migrate_key_app_to_selinux() -> Result<()> {
3853 let mut db = new_test_db()?;
3854 const SOURCE_UID: u32 = 1u32;
3855 const DESTINATION_UID: u32 = 2u32;
3856 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003857 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3858 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003859 let key_id_guard =
3860 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3861 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3862
3863 let source_descriptor: KeyDescriptor = KeyDescriptor {
3864 domain: Domain::APP,
3865 nspace: -1,
3866 alias: Some(SOURCE_ALIAS.to_string()),
3867 blob: None,
3868 };
3869
3870 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3871 domain: Domain::SELINUX,
3872 nspace: DESTINATION_NAMESPACE,
3873 alias: Some(DESTINATION_ALIAS.to_string()),
3874 blob: None,
3875 };
3876
3877 let key_id = key_id_guard.id();
3878
3879 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3880 Ok(())
3881 })
3882 .unwrap();
3883
3884 let (_, key_entry) = db
3885 .load_key_entry(
3886 &destination_descriptor,
3887 KeyType::Client,
3888 KeyEntryLoadBits::BOTH,
3889 DESTINATION_UID,
3890 |k, av| {
3891 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003892 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003893 assert!(av.is_none());
3894 Ok(())
3895 },
3896 )
3897 .unwrap();
3898
3899 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3900
3901 assert_eq!(
3902 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3903 db.load_key_entry(
3904 &source_descriptor,
3905 KeyType::Client,
3906 KeyEntryLoadBits::NONE,
3907 SOURCE_UID,
3908 |_k, _av| Ok(()),
3909 )
3910 .unwrap_err()
3911 .root_cause()
3912 .downcast_ref::<KsError>()
3913 );
3914
3915 Ok(())
3916 }
3917
3918 // Creates two keys and tries to migrate the first to the location of the second which
3919 // is expected to fail.
3920 #[test]
3921 fn test_migrate_key_destination_occupied() -> Result<()> {
3922 let mut db = new_test_db()?;
3923 const SOURCE_UID: u32 = 1u32;
3924 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003925 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3926 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003927 let key_id_guard =
3928 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3929 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3930 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3931 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3932
3933 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3934 domain: Domain::APP,
3935 nspace: -1,
3936 alias: Some(DESTINATION_ALIAS.to_string()),
3937 blob: None,
3938 };
3939
3940 assert_eq!(
3941 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3942 db.migrate_key_namespace(
3943 key_id_guard,
3944 &destination_descriptor,
3945 DESTINATION_UID,
3946 |_k| Ok(())
3947 )
3948 .unwrap_err()
3949 .root_cause()
3950 .downcast_ref::<KsError>()
3951 );
3952
3953 Ok(())
3954 }
3955
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003956 #[test]
3957 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003958 const ALIAS1: &str = "test_upgrade_0_to_1_1";
3959 const ALIAS2: &str = "test_upgrade_0_to_1_2";
3960 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003961 const UID: u32 = 33;
3962 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3963 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3964 let key_id_untouched1 =
3965 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3966 let key_id_untouched2 =
3967 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
3968 let key_id_deleted =
3969 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
3970
3971 let (_, key_entry) = db
3972 .load_key_entry(
3973 &KeyDescriptor {
3974 domain: Domain::APP,
3975 nspace: -1,
3976 alias: Some(ALIAS1.to_string()),
3977 blob: None,
3978 },
3979 KeyType::Client,
3980 KeyEntryLoadBits::BOTH,
3981 UID,
3982 |k, av| {
3983 assert_eq!(Domain::APP, k.domain);
3984 assert_eq!(UID as i64, k.nspace);
3985 assert!(av.is_none());
3986 Ok(())
3987 },
3988 )
3989 .unwrap();
3990 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
3991 let (_, key_entry) = db
3992 .load_key_entry(
3993 &KeyDescriptor {
3994 domain: Domain::APP,
3995 nspace: -1,
3996 alias: Some(ALIAS2.to_string()),
3997 blob: None,
3998 },
3999 KeyType::Client,
4000 KeyEntryLoadBits::BOTH,
4001 UID,
4002 |k, av| {
4003 assert_eq!(Domain::APP, k.domain);
4004 assert_eq!(UID as i64, k.nspace);
4005 assert!(av.is_none());
4006 Ok(())
4007 },
4008 )
4009 .unwrap();
4010 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4011 let (_, key_entry) = db
4012 .load_key_entry(
4013 &KeyDescriptor {
4014 domain: Domain::APP,
4015 nspace: -1,
4016 alias: Some(ALIAS3.to_string()),
4017 blob: None,
4018 },
4019 KeyType::Client,
4020 KeyEntryLoadBits::BOTH,
4021 UID,
4022 |k, av| {
4023 assert_eq!(Domain::APP, k.domain);
4024 assert_eq!(UID as i64, k.nspace);
4025 assert!(av.is_none());
4026 Ok(())
4027 },
4028 )
4029 .unwrap();
4030 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4031
David Drysdale7b9ca232024-05-23 18:19:46 +01004032 db.with_transaction(Immediate("TX_test"), |tx| KeystoreDB::from_0_to_1(tx).no_gc())
4033 .unwrap();
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004034
4035 let (_, key_entry) = db
4036 .load_key_entry(
4037 &KeyDescriptor {
4038 domain: Domain::APP,
4039 nspace: -1,
4040 alias: Some(ALIAS1.to_string()),
4041 blob: None,
4042 },
4043 KeyType::Client,
4044 KeyEntryLoadBits::BOTH,
4045 UID,
4046 |k, av| {
4047 assert_eq!(Domain::APP, k.domain);
4048 assert_eq!(UID as i64, k.nspace);
4049 assert!(av.is_none());
4050 Ok(())
4051 },
4052 )
4053 .unwrap();
4054 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4055 let (_, key_entry) = db
4056 .load_key_entry(
4057 &KeyDescriptor {
4058 domain: Domain::APP,
4059 nspace: -1,
4060 alias: Some(ALIAS2.to_string()),
4061 blob: None,
4062 },
4063 KeyType::Client,
4064 KeyEntryLoadBits::BOTH,
4065 UID,
4066 |k, av| {
4067 assert_eq!(Domain::APP, k.domain);
4068 assert_eq!(UID as i64, k.nspace);
4069 assert!(av.is_none());
4070 Ok(())
4071 },
4072 )
4073 .unwrap();
4074 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4075 assert_eq!(
4076 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4077 db.load_key_entry(
4078 &KeyDescriptor {
4079 domain: Domain::APP,
4080 nspace: -1,
4081 alias: Some(ALIAS3.to_string()),
4082 blob: None,
4083 },
4084 KeyType::Client,
4085 KeyEntryLoadBits::BOTH,
4086 UID,
4087 |k, av| {
4088 assert_eq!(Domain::APP, k.domain);
4089 assert_eq!(UID as i64, k.nspace);
4090 assert!(av.is_none());
4091 Ok(())
4092 },
4093 )
4094 .unwrap_err()
4095 .root_cause()
4096 .downcast_ref::<KsError>()
4097 );
4098 }
4099
Janis Danisevskisaec14592020-11-12 09:41:49 -08004100 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4101
Janis Danisevskisaec14592020-11-12 09:41:49 -08004102 #[test]
4103 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4104 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004105 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4106 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004107 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004108 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004109 .context("test_insert_and_load_full_keyentry_domain_app")?
4110 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004111 let (_key_guard, key_entry) = db
4112 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004113 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004114 domain: Domain::APP,
4115 nspace: 0,
4116 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4117 blob: None,
4118 },
4119 KeyType::Client,
4120 KeyEntryLoadBits::BOTH,
4121 33,
4122 |_k, _av| Ok(()),
4123 )
4124 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004125 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004126 let state = Arc::new(AtomicU8::new(1));
4127 let state2 = state.clone();
4128
4129 // Spawning a second thread that attempts to acquire the key id lock
4130 // for the same key as the primary thread. The primary thread then
4131 // waits, thereby forcing the secondary thread into the second stage
4132 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4133 // The test succeeds if the secondary thread observes the transition
4134 // of `state` from 1 to 2, despite having a whole second to overtake
4135 // the primary thread.
4136 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004137 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004138 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004139 assert!(db
4140 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004141 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004142 domain: Domain::APP,
4143 nspace: 0,
4144 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4145 blob: None,
4146 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004147 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004148 KeyEntryLoadBits::BOTH,
4149 33,
4150 |_k, _av| Ok(()),
4151 )
4152 .is_ok());
4153 // We should only see a 2 here because we can only return
4154 // from load_key_entry when the `_key_guard` expires,
4155 // which happens at the end of the scope.
4156 assert_eq!(2, state2.load(Ordering::Relaxed));
4157 });
4158
4159 thread::sleep(std::time::Duration::from_millis(1000));
4160
4161 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4162
4163 // Return the handle from this scope so we can join with the
4164 // secondary thread after the key id lock has expired.
4165 handle
4166 // This is where the `_key_guard` goes out of scope,
4167 // which is the reason for concurrent load_key_entry on the same key
4168 // to unblock.
4169 };
4170 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4171 // main test thread. We will not see failing asserts in secondary threads otherwise.
4172 handle.join().unwrap();
4173 Ok(())
4174 }
4175
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004176 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004177 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004178 let temp_dir =
4179 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4180
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004181 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4182 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004183
4184 let _tx1 = db1
4185 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004186 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004187 .expect("Failed to create first transaction.");
4188
4189 let error = db2
4190 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004191 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004192 .context("Transaction begin failed.")
4193 .expect_err("This should fail.");
4194 let root_cause = error.root_cause();
4195 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4196 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4197 {
4198 return;
4199 }
4200 panic!(
4201 "Unexpected error {:?} \n{:?} \n{:?}",
4202 error,
4203 root_cause,
4204 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4205 )
4206 }
4207
4208 #[cfg(disabled)]
4209 #[test]
4210 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4211 let temp_dir = Arc::new(
4212 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4213 .expect("Failed to create temp dir."),
4214 );
4215
4216 let test_begin = Instant::now();
4217
Janis Danisevskis66784c42021-01-27 08:40:25 -08004218 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004219 let mut db =
4220 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004221 const OPEN_DB_COUNT: u32 = 50u32;
4222
4223 let mut actual_key_count = KEY_COUNT;
4224 // First insert KEY_COUNT keys.
4225 for count in 0..KEY_COUNT {
4226 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4227 actual_key_count = count;
4228 break;
4229 }
4230 let alias = format!("test_alias_{}", count);
4231 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4232 .expect("Failed to make key entry.");
4233 }
4234
4235 // Insert more keys from a different thread and into a different namespace.
4236 let temp_dir1 = temp_dir.clone();
4237 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004238 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4239 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004240
4241 for count in 0..actual_key_count {
4242 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4243 return;
4244 }
4245 let alias = format!("test_alias_{}", count);
4246 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4247 .expect("Failed to make key entry.");
4248 }
4249
4250 // then unbind them again.
4251 for count in 0..actual_key_count {
4252 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4253 return;
4254 }
4255 let key = KeyDescriptor {
4256 domain: Domain::APP,
4257 nspace: -1,
4258 alias: Some(format!("test_alias_{}", count)),
4259 blob: None,
4260 };
4261 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4262 }
4263 });
4264
4265 // And start unbinding the first set of keys.
4266 let temp_dir2 = temp_dir.clone();
4267 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004268 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4269 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004270
4271 for count in 0..actual_key_count {
4272 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4273 return;
4274 }
4275 let key = KeyDescriptor {
4276 domain: Domain::APP,
4277 nspace: -1,
4278 alias: Some(format!("test_alias_{}", count)),
4279 blob: None,
4280 };
4281 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4282 }
4283 });
4284
Janis Danisevskis66784c42021-01-27 08:40:25 -08004285 // While a lot of inserting and deleting is going on we have to open database connections
4286 // successfully and use them.
4287 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4288 // out of scope.
4289 #[allow(clippy::redundant_clone)]
4290 let temp_dir4 = temp_dir.clone();
4291 let handle4 = thread::spawn(move || {
4292 for count in 0..OPEN_DB_COUNT {
4293 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4294 return;
4295 }
Seth Moore444b51a2021-06-11 09:49:49 -07004296 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4297 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004298
4299 let alias = format!("test_alias_{}", count);
4300 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4301 .expect("Failed to make key entry.");
4302 let key = KeyDescriptor {
4303 domain: Domain::APP,
4304 nspace: -1,
4305 alias: Some(alias),
4306 blob: None,
4307 };
4308 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4309 }
4310 });
4311
4312 handle1.join().expect("Thread 1 panicked.");
4313 handle2.join().expect("Thread 2 panicked.");
4314 handle4.join().expect("Thread 4 panicked.");
4315
Janis Danisevskis66784c42021-01-27 08:40:25 -08004316 Ok(())
4317 }
4318
4319 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004320 fn list() -> Result<()> {
4321 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004322 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004323 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4324 (Domain::APP, 1, "test1"),
4325 (Domain::APP, 1, "test2"),
4326 (Domain::APP, 1, "test3"),
4327 (Domain::APP, 1, "test4"),
4328 (Domain::APP, 1, "test5"),
4329 (Domain::APP, 1, "test6"),
4330 (Domain::APP, 1, "test7"),
4331 (Domain::APP, 2, "test1"),
4332 (Domain::APP, 2, "test2"),
4333 (Domain::APP, 2, "test3"),
4334 (Domain::APP, 2, "test4"),
4335 (Domain::APP, 2, "test5"),
4336 (Domain::APP, 2, "test6"),
4337 (Domain::APP, 2, "test8"),
4338 (Domain::SELINUX, 100, "test1"),
4339 (Domain::SELINUX, 100, "test2"),
4340 (Domain::SELINUX, 100, "test3"),
4341 (Domain::SELINUX, 100, "test4"),
4342 (Domain::SELINUX, 100, "test5"),
4343 (Domain::SELINUX, 100, "test6"),
4344 (Domain::SELINUX, 100, "test9"),
4345 ];
4346
4347 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4348 .iter()
4349 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004350 let entry =
4351 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004352 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4353 });
4354 (entry.id(), *ns)
4355 })
4356 .collect();
4357
4358 for (domain, namespace) in
4359 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4360 {
4361 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4362 .iter()
4363 .filter_map(|(domain, ns, alias)| match ns {
4364 ns if *ns == *namespace => Some(KeyDescriptor {
4365 domain: *domain,
4366 nspace: *ns,
4367 alias: Some(alias.to_string()),
4368 blob: None,
4369 }),
4370 _ => None,
4371 })
4372 .collect();
4373 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004374 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004375 list_result.sort();
4376 assert_eq!(list_o_descriptors, list_result);
4377
4378 let mut list_o_ids: Vec<i64> = list_o_descriptors
4379 .into_iter()
4380 .map(|d| {
4381 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004382 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004383 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004384 KeyType::Client,
4385 KeyEntryLoadBits::NONE,
4386 *namespace as u32,
4387 |_, _| Ok(()),
4388 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004389 .unwrap();
4390 entry.id()
4391 })
4392 .collect();
4393 list_o_ids.sort_unstable();
4394 let mut loaded_entries: Vec<i64> = list_o_keys
4395 .iter()
4396 .filter_map(|(id, ns)| match ns {
4397 ns if *ns == *namespace => Some(*id),
4398 _ => None,
4399 })
4400 .collect();
4401 loaded_entries.sort_unstable();
4402 assert_eq!(list_o_ids, loaded_entries);
4403 }
Eran Messeri24f31972023-01-25 17:00:33 +00004404 assert_eq!(
4405 Vec::<KeyDescriptor>::new(),
4406 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4407 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004408
4409 Ok(())
4410 }
4411
Joel Galenson0891bc12020-07-20 10:37:03 -07004412 // Helpers
4413
4414 // Checks that the given result is an error containing the given string.
4415 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4416 let error_str = format!(
4417 "{:#?}",
4418 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4419 );
4420 assert!(
4421 error_str.contains(target),
4422 "The string \"{}\" should contain \"{}\"",
4423 error_str,
4424 target
4425 );
4426 }
4427
Joel Galenson2aab4432020-07-22 15:27:57 -07004428 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004429 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004430 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004431 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004432 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004433 namespace: Option<i64>,
4434 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004435 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004436 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004437 }
4438
4439 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4440 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004441 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004442 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004443 Ok(KeyEntryRow {
4444 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004445 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004446 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004447 namespace: row.get(3)?,
4448 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004449 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004450 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004451 })
4452 })?
4453 .map(|r| r.context("Could not read keyentry row."))
4454 .collect::<Result<Vec<_>>>()
4455 }
4456
Eran Messeri4dc27b52024-01-09 12:43:31 +00004457 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4458 make_test_params_with_sids(max_usage_count, &[42])
4459 }
4460
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004461 // Note: The parameters and SecurityLevel associations are nonsensical. This
4462 // collection is only used to check if the parameters are preserved as expected by the
4463 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004464 fn make_test_params_with_sids(
4465 max_usage_count: Option<i32>,
4466 user_secure_ids: &[i64],
4467 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004468 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004469 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4470 KeyParameter::new(
4471 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4472 SecurityLevel::TRUSTED_ENVIRONMENT,
4473 ),
4474 KeyParameter::new(
4475 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4476 SecurityLevel::TRUSTED_ENVIRONMENT,
4477 ),
4478 KeyParameter::new(
4479 KeyParameterValue::Algorithm(Algorithm::RSA),
4480 SecurityLevel::TRUSTED_ENVIRONMENT,
4481 ),
4482 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4483 KeyParameter::new(
4484 KeyParameterValue::BlockMode(BlockMode::ECB),
4485 SecurityLevel::TRUSTED_ENVIRONMENT,
4486 ),
4487 KeyParameter::new(
4488 KeyParameterValue::BlockMode(BlockMode::GCM),
4489 SecurityLevel::TRUSTED_ENVIRONMENT,
4490 ),
4491 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4492 KeyParameter::new(
4493 KeyParameterValue::Digest(Digest::MD5),
4494 SecurityLevel::TRUSTED_ENVIRONMENT,
4495 ),
4496 KeyParameter::new(
4497 KeyParameterValue::Digest(Digest::SHA_2_224),
4498 SecurityLevel::TRUSTED_ENVIRONMENT,
4499 ),
4500 KeyParameter::new(
4501 KeyParameterValue::Digest(Digest::SHA_2_256),
4502 SecurityLevel::STRONGBOX,
4503 ),
4504 KeyParameter::new(
4505 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4506 SecurityLevel::TRUSTED_ENVIRONMENT,
4507 ),
4508 KeyParameter::new(
4509 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4510 SecurityLevel::TRUSTED_ENVIRONMENT,
4511 ),
4512 KeyParameter::new(
4513 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4514 SecurityLevel::STRONGBOX,
4515 ),
4516 KeyParameter::new(
4517 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4518 SecurityLevel::TRUSTED_ENVIRONMENT,
4519 ),
4520 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4521 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4522 KeyParameter::new(
4523 KeyParameterValue::EcCurve(EcCurve::P_224),
4524 SecurityLevel::TRUSTED_ENVIRONMENT,
4525 ),
4526 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4527 KeyParameter::new(
4528 KeyParameterValue::EcCurve(EcCurve::P_384),
4529 SecurityLevel::TRUSTED_ENVIRONMENT,
4530 ),
4531 KeyParameter::new(
4532 KeyParameterValue::EcCurve(EcCurve::P_521),
4533 SecurityLevel::TRUSTED_ENVIRONMENT,
4534 ),
4535 KeyParameter::new(
4536 KeyParameterValue::RSAPublicExponent(3),
4537 SecurityLevel::TRUSTED_ENVIRONMENT,
4538 ),
4539 KeyParameter::new(
4540 KeyParameterValue::IncludeUniqueID,
4541 SecurityLevel::TRUSTED_ENVIRONMENT,
4542 ),
4543 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4544 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4545 KeyParameter::new(
4546 KeyParameterValue::ActiveDateTime(1234567890),
4547 SecurityLevel::STRONGBOX,
4548 ),
4549 KeyParameter::new(
4550 KeyParameterValue::OriginationExpireDateTime(1234567890),
4551 SecurityLevel::TRUSTED_ENVIRONMENT,
4552 ),
4553 KeyParameter::new(
4554 KeyParameterValue::UsageExpireDateTime(1234567890),
4555 SecurityLevel::TRUSTED_ENVIRONMENT,
4556 ),
4557 KeyParameter::new(
4558 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4559 SecurityLevel::TRUSTED_ENVIRONMENT,
4560 ),
4561 KeyParameter::new(
4562 KeyParameterValue::MaxUsesPerBoot(1234567890),
4563 SecurityLevel::TRUSTED_ENVIRONMENT,
4564 ),
4565 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004566 KeyParameter::new(
4567 KeyParameterValue::NoAuthRequired,
4568 SecurityLevel::TRUSTED_ENVIRONMENT,
4569 ),
4570 KeyParameter::new(
4571 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4572 SecurityLevel::TRUSTED_ENVIRONMENT,
4573 ),
4574 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4575 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4576 KeyParameter::new(
4577 KeyParameterValue::TrustedUserPresenceRequired,
4578 SecurityLevel::TRUSTED_ENVIRONMENT,
4579 ),
4580 KeyParameter::new(
4581 KeyParameterValue::TrustedConfirmationRequired,
4582 SecurityLevel::TRUSTED_ENVIRONMENT,
4583 ),
4584 KeyParameter::new(
4585 KeyParameterValue::UnlockedDeviceRequired,
4586 SecurityLevel::TRUSTED_ENVIRONMENT,
4587 ),
4588 KeyParameter::new(
4589 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4590 SecurityLevel::SOFTWARE,
4591 ),
4592 KeyParameter::new(
4593 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4594 SecurityLevel::SOFTWARE,
4595 ),
4596 KeyParameter::new(
4597 KeyParameterValue::CreationDateTime(12345677890),
4598 SecurityLevel::SOFTWARE,
4599 ),
4600 KeyParameter::new(
4601 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4602 SecurityLevel::TRUSTED_ENVIRONMENT,
4603 ),
4604 KeyParameter::new(
4605 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4606 SecurityLevel::TRUSTED_ENVIRONMENT,
4607 ),
4608 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4609 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4610 KeyParameter::new(
4611 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4612 SecurityLevel::SOFTWARE,
4613 ),
4614 KeyParameter::new(
4615 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4616 SecurityLevel::TRUSTED_ENVIRONMENT,
4617 ),
4618 KeyParameter::new(
4619 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4620 SecurityLevel::TRUSTED_ENVIRONMENT,
4621 ),
4622 KeyParameter::new(
4623 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4624 SecurityLevel::TRUSTED_ENVIRONMENT,
4625 ),
4626 KeyParameter::new(
4627 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4628 SecurityLevel::TRUSTED_ENVIRONMENT,
4629 ),
4630 KeyParameter::new(
4631 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4632 SecurityLevel::TRUSTED_ENVIRONMENT,
4633 ),
4634 KeyParameter::new(
4635 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4636 SecurityLevel::TRUSTED_ENVIRONMENT,
4637 ),
4638 KeyParameter::new(
4639 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4640 SecurityLevel::TRUSTED_ENVIRONMENT,
4641 ),
4642 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004643 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4644 SecurityLevel::TRUSTED_ENVIRONMENT,
4645 ),
4646 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004647 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4648 SecurityLevel::TRUSTED_ENVIRONMENT,
4649 ),
4650 KeyParameter::new(
4651 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4652 SecurityLevel::TRUSTED_ENVIRONMENT,
4653 ),
4654 KeyParameter::new(
4655 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4656 SecurityLevel::TRUSTED_ENVIRONMENT,
4657 ),
4658 KeyParameter::new(
4659 KeyParameterValue::VendorPatchLevel(3),
4660 SecurityLevel::TRUSTED_ENVIRONMENT,
4661 ),
4662 KeyParameter::new(
4663 KeyParameterValue::BootPatchLevel(4),
4664 SecurityLevel::TRUSTED_ENVIRONMENT,
4665 ),
4666 KeyParameter::new(
4667 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4668 SecurityLevel::TRUSTED_ENVIRONMENT,
4669 ),
4670 KeyParameter::new(
4671 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4672 SecurityLevel::TRUSTED_ENVIRONMENT,
4673 ),
4674 KeyParameter::new(
4675 KeyParameterValue::MacLength(256),
4676 SecurityLevel::TRUSTED_ENVIRONMENT,
4677 ),
4678 KeyParameter::new(
4679 KeyParameterValue::ResetSinceIdRotation,
4680 SecurityLevel::TRUSTED_ENVIRONMENT,
4681 ),
4682 KeyParameter::new(
4683 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4684 SecurityLevel::TRUSTED_ENVIRONMENT,
4685 ),
Qi Wub9433b52020-12-01 14:52:46 +08004686 ];
4687 if let Some(value) = max_usage_count {
4688 params.push(KeyParameter::new(
4689 KeyParameterValue::UsageCountLimit(value),
4690 SecurityLevel::SOFTWARE,
4691 ));
4692 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004693
4694 for sid in user_secure_ids.iter() {
4695 params.push(KeyParameter::new(
4696 KeyParameterValue::UserSecureID(*sid),
4697 SecurityLevel::STRONGBOX,
4698 ));
4699 }
Qi Wub9433b52020-12-01 14:52:46 +08004700 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004701 }
4702
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004703 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004704 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004705 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004706 namespace: i64,
4707 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004708 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004709 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004710 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4711 }
4712
4713 pub fn make_test_key_entry_with_sids(
4714 db: &mut KeystoreDB,
4715 domain: Domain,
4716 namespace: i64,
4717 alias: &str,
4718 max_usage_count: Option<i32>,
4719 sids: &[i64],
4720 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004721 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004722 let mut blob_metadata = BlobMetaData::new();
4723 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4724 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4725 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4726 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4727 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4728
4729 db.set_blob(
4730 &key_id,
4731 SubComponentType::KEY_BLOB,
4732 Some(TEST_KEY_BLOB),
4733 Some(&blob_metadata),
4734 )?;
4735 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4736 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004737
Eran Messeri4dc27b52024-01-09 12:43:31 +00004738 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004739 db.insert_keyparameter(&key_id, &params)?;
4740
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004741 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004742 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004743 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004744 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004745 Ok(key_id)
4746 }
4747
Qi Wub9433b52020-12-01 14:52:46 +08004748 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4749 let params = make_test_params(max_usage_count);
4750
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004751 let mut blob_metadata = BlobMetaData::new();
4752 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4753 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4754 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4755 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4756 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4757
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004758 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004759 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004760
4761 KeyEntry {
4762 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004763 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004764 cert: Some(TEST_CERT_BLOB.to_vec()),
4765 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004766 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004767 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004768 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004769 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004770 }
4771 }
4772
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004773 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004774 db: &mut KeystoreDB,
4775 domain: Domain,
4776 namespace: i64,
4777 alias: &str,
4778 logical_only: bool,
4779 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004780 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004781 let mut blob_metadata = BlobMetaData::new();
4782 if !logical_only {
4783 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4784 }
4785 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4786
4787 db.set_blob(
4788 &key_id,
4789 SubComponentType::KEY_BLOB,
4790 Some(TEST_KEY_BLOB),
4791 Some(&blob_metadata),
4792 )?;
4793 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4794 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4795
4796 let mut params = make_test_params(None);
4797 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4798
4799 db.insert_keyparameter(&key_id, &params)?;
4800
4801 let mut metadata = KeyMetaData::new();
4802 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4803 db.insert_key_metadata(&key_id, &metadata)?;
4804 rebind_alias(db, &key_id, alias, domain, namespace)?;
4805 Ok(key_id)
4806 }
4807
Eric Biggersb0478cf2023-10-27 03:55:29 +00004808 // Creates an app key that is marked as being superencrypted by the given
4809 // super key ID and that has the given authentication and unlocked device
4810 // parameters. This does not actually superencrypt the key blob.
4811 fn make_superencrypted_key_entry(
4812 db: &mut KeystoreDB,
4813 namespace: i64,
4814 alias: &str,
4815 requires_authentication: bool,
4816 requires_unlocked_device: bool,
4817 super_key_id: i64,
4818 ) -> Result<KeyIdGuard> {
4819 let domain = Domain::APP;
David Drysdale8c4c4f32023-10-31 12:14:11 +00004820 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Eric Biggersb0478cf2023-10-27 03:55:29 +00004821
4822 let mut blob_metadata = BlobMetaData::new();
4823 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4824 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4825 db.set_blob(
4826 &key_id,
4827 SubComponentType::KEY_BLOB,
4828 Some(TEST_KEY_BLOB),
4829 Some(&blob_metadata),
4830 )?;
4831
4832 let mut params = vec![];
4833 if requires_unlocked_device {
4834 params.push(KeyParameter::new(
4835 KeyParameterValue::UnlockedDeviceRequired,
4836 SecurityLevel::TRUSTED_ENVIRONMENT,
4837 ));
4838 }
4839 if requires_authentication {
4840 params.push(KeyParameter::new(
4841 KeyParameterValue::UserSecureID(42),
4842 SecurityLevel::TRUSTED_ENVIRONMENT,
4843 ));
4844 }
4845 db.insert_keyparameter(&key_id, &params)?;
4846
4847 let mut metadata = KeyMetaData::new();
4848 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4849 db.insert_key_metadata(&key_id, &metadata)?;
4850
4851 rebind_alias(db, &key_id, alias, domain, namespace)?;
4852 Ok(key_id)
4853 }
4854
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004855 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4856 let mut params = make_test_params(None);
4857 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4858
4859 let mut blob_metadata = BlobMetaData::new();
4860 if !logical_only {
4861 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4862 }
4863 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4864
4865 let mut metadata = KeyMetaData::new();
4866 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4867
4868 KeyEntry {
4869 id: key_id,
4870 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4871 cert: Some(TEST_CERT_BLOB.to_vec()),
4872 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4873 km_uuid: KEYSTORE_UUID,
4874 parameters: params,
4875 metadata,
4876 pure_cert: false,
4877 }
4878 }
4879
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004880 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004881 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004882 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004883 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004884 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004885 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004886 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004887 Ok((
4888 row.get(0)?,
4889 row.get(1)?,
4890 row.get(2)?,
4891 row.get(3)?,
4892 row.get(4)?,
4893 row.get(5)?,
4894 row.get(6)?,
4895 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004896 },
4897 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004898
4899 println!("Key entry table rows:");
4900 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004901 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004902 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004903 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4904 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004905 );
4906 }
4907 Ok(())
4908 }
4909
4910 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004911 let mut stmt = db
4912 .conn
4913 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004914 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004915 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4916 })?;
4917
4918 println!("Grant table rows:");
4919 for r in rows {
4920 let (id, gt, ki, av) = r.unwrap();
4921 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4922 }
4923 Ok(())
4924 }
4925
Joel Galenson0891bc12020-07-20 10:37:03 -07004926 // Use a custom random number generator that repeats each number once.
4927 // This allows us to test repeated elements.
4928
4929 thread_local! {
Charisee43391152024-04-02 16:16:30 +00004930 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07004931 }
4932
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004933 fn reset_random() {
4934 RANDOM_COUNTER.with(|counter| {
4935 *counter.borrow_mut() = 0;
4936 })
4937 }
4938
Joel Galenson0891bc12020-07-20 10:37:03 -07004939 pub fn random() -> i64 {
4940 RANDOM_COUNTER.with(|counter| {
4941 let result = *counter.borrow() / 2;
4942 *counter.borrow_mut() += 1;
4943 result
4944 })
4945 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004946
4947 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00004948 fn test_unbind_keys_for_user() -> Result<()> {
4949 let mut db = new_test_db()?;
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004950 db.unbind_keys_for_user(1)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004951
4952 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4953 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004954 db.unbind_keys_for_user(2)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004955
Eran Messeri24f31972023-01-25 17:00:33 +00004956 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4957 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004958
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004959 db.unbind_keys_for_user(1)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004960 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004961
4962 Ok(())
4963 }
4964
4965 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004966 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4967 let mut db = new_test_db()?;
4968 let super_key = keystore2_crypto::generate_aes256_key()?;
4969 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4970 let (encrypted_super_key, metadata) =
4971 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4972
4973 let key_name_enc = SuperKeyType {
4974 alias: "test_super_key_1",
4975 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004976 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004977 };
4978
4979 let key_name_nonenc = SuperKeyType {
4980 alias: "test_super_key_2",
4981 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004982 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004983 };
4984
4985 // Install two super keys.
4986 db.store_super_key(
4987 1,
4988 &key_name_nonenc,
4989 &super_key,
4990 &BlobMetaData::new(),
4991 &KeyMetaData::new(),
4992 )?;
4993 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4994
4995 // Check that both can be found in the database.
4996 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
4997 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
4998
4999 // Install the same keys for a different user.
5000 db.store_super_key(
5001 2,
5002 &key_name_nonenc,
5003 &super_key,
5004 &BlobMetaData::new(),
5005 &KeyMetaData::new(),
5006 )?;
5007 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5008
5009 // Check that the second pair of keys can be found in the database.
5010 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5011 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5012
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00005013 // Delete all keys for user 1.
5014 db.unbind_keys_for_user(1)?;
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005015
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00005016 // All of user 1's keys should be gone.
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005017 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5018 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5019
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00005020 // User 2's keys should not have been touched.
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005021 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5022 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5023
5024 Ok(())
5025 }
5026
Eric Biggersb0478cf2023-10-27 03:55:29 +00005027 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5028 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5029 }
5030
5031 // Tests the unbind_auth_bound_keys_for_user() function.
5032 #[test]
5033 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5034 let mut db = new_test_db()?;
5035 let user_id = 1;
5036 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5037 let other_user_id = 2;
5038 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5039 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5040
5041 // Create a superencryption key.
5042 let super_key = keystore2_crypto::generate_aes256_key()?;
5043 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5044 let (encrypted_super_key, blob_metadata) =
5045 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5046 db.store_super_key(
5047 user_id,
5048 super_key_type,
5049 &encrypted_super_key,
5050 &blob_metadata,
5051 &KeyMetaData::new(),
5052 )?;
5053 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5054
5055 // Store 4 superencrypted app keys, one for each possible combination of
5056 // (authentication required, unlocked device required).
5057 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5058 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5059 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5060 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5061 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5062 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5063 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5064 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5065
5066 // Also store a key for a different user that requires authentication.
5067 make_superencrypted_key_entry(
5068 &mut db,
5069 other_user_nspace,
5070 "auth_ud",
5071 true,
5072 true,
5073 super_key_id,
5074 )?;
5075
5076 db.unbind_auth_bound_keys_for_user(user_id)?;
5077
5078 // Verify that only the user's app keys that require authentication were
5079 // deleted. Keys that require an unlocked device but not authentication
5080 // should *not* have been deleted, nor should the super key have been
5081 // deleted, nor should other users' keys have been deleted.
5082 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5083 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5084 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5085 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5086 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5087 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5088
5089 Ok(())
5090 }
5091
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005092 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005093 fn test_store_super_key() -> Result<()> {
5094 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005095 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005096 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005097 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005098 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005099 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005100
5101 let (encrypted_super_key, metadata) =
5102 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005103 db.store_super_key(
5104 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005105 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005106 &encrypted_super_key,
5107 &metadata,
5108 &KeyMetaData::new(),
5109 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005110
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005111 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005112 assert!(db.key_exists(
5113 Domain::APP,
5114 1,
5115 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5116 KeyType::Super
5117 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005118
Eric Biggers673d34a2023-10-18 01:54:18 +00005119 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005120 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005121 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005122 key_entry,
5123 &pw,
5124 None,
5125 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005126
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005127 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005128 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005129
Hasini Gunasingheda895552021-01-27 19:34:37 +00005130 Ok(())
5131 }
Seth Moore78c091f2021-04-09 21:38:30 +00005132
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005133 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005134 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005135 MetricsStorage::KEY_ENTRY,
5136 MetricsStorage::KEY_ENTRY_ID_INDEX,
5137 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5138 MetricsStorage::BLOB_ENTRY,
5139 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5140 MetricsStorage::KEY_PARAMETER,
5141 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5142 MetricsStorage::KEY_METADATA,
5143 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5144 MetricsStorage::GRANT,
5145 MetricsStorage::AUTH_TOKEN,
5146 MetricsStorage::BLOB_METADATA,
5147 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005148 ]
5149 }
5150
5151 /// Perform a simple check to ensure that we can query all the storage types
5152 /// that are supported by the DB. Check for reasonable values.
5153 #[test]
5154 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005155 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005156
5157 let mut db = new_test_db()?;
5158
5159 for t in get_valid_statsd_storage_types() {
5160 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005161 // AuthToken can be less than a page since it's in a btree, not sqlite
5162 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005163 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005164 } else {
5165 assert!(stat.size >= PAGE_SIZE);
5166 }
Seth Moore78c091f2021-04-09 21:38:30 +00005167 assert!(stat.size >= stat.unused_size);
5168 }
5169
5170 Ok(())
5171 }
5172
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005173 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005174 get_valid_statsd_storage_types()
5175 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005176 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005177 .collect()
5178 }
5179
5180 fn assert_storage_increased(
5181 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005182 increased_storage_types: Vec<MetricsStorage>,
5183 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005184 ) {
5185 for storage in increased_storage_types {
5186 // Verify the expected storage increased.
5187 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005188 let old = &baseline[&storage.0];
5189 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005190 assert!(
5191 new.unused_size <= old.unused_size,
5192 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005193 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005194 new.unused_size,
5195 old.unused_size
5196 );
5197
5198 // Update the baseline with the new value so that it succeeds in the
5199 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005200 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005201 }
5202
5203 // Get an updated map of the storage and verify there were no unexpected changes.
5204 let updated_stats = get_storage_stats_map(db);
5205 assert_eq!(updated_stats.len(), baseline.len());
5206
5207 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005208 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005209 let mut s = String::new();
5210 for &k in map.keys() {
5211 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5212 .expect("string concat failed");
5213 }
5214 s
5215 };
5216
5217 assert!(
5218 updated_stats[&k].size == baseline[&k].size
5219 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5220 "updated_stats:\n{}\nbaseline:\n{}",
5221 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005222 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005223 );
5224 }
5225 }
5226
5227 #[test]
5228 fn test_verify_key_table_size_reporting() -> Result<()> {
5229 let mut db = new_test_db()?;
5230 let mut working_stats = get_storage_stats_map(&mut db);
5231
David Drysdale8c4c4f32023-10-31 12:14:11 +00005232 let key_id = create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005233 assert_storage_increased(
5234 &mut db,
5235 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005236 MetricsStorage::KEY_ENTRY,
5237 MetricsStorage::KEY_ENTRY_ID_INDEX,
5238 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005239 ],
5240 &mut working_stats,
5241 );
5242
5243 let mut blob_metadata = BlobMetaData::new();
5244 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5245 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5246 assert_storage_increased(
5247 &mut db,
5248 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005249 MetricsStorage::BLOB_ENTRY,
5250 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5251 MetricsStorage::BLOB_METADATA,
5252 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005253 ],
5254 &mut working_stats,
5255 );
5256
5257 let params = make_test_params(None);
5258 db.insert_keyparameter(&key_id, &params)?;
5259 assert_storage_increased(
5260 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005261 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005262 &mut working_stats,
5263 );
5264
5265 let mut metadata = KeyMetaData::new();
5266 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5267 db.insert_key_metadata(&key_id, &metadata)?;
5268 assert_storage_increased(
5269 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005270 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005271 &mut working_stats,
5272 );
5273
5274 let mut sum = 0;
5275 for stat in working_stats.values() {
5276 sum += stat.size;
5277 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005278 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005279 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5280
5281 Ok(())
5282 }
5283
5284 #[test]
5285 fn test_verify_auth_table_size_reporting() -> Result<()> {
5286 let mut db = new_test_db()?;
5287 let mut working_stats = get_storage_stats_map(&mut db);
5288 db.insert_auth_token(&HardwareAuthToken {
5289 challenge: 123,
5290 userId: 456,
5291 authenticatorId: 789,
5292 authenticatorType: kmhw_authenticator_type::ANY,
5293 timestamp: Timestamp { milliSeconds: 10 },
5294 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005295 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005296 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005297 Ok(())
5298 }
5299
5300 #[test]
5301 fn test_verify_grant_table_size_reporting() -> Result<()> {
5302 const OWNER: i64 = 1;
5303 let mut db = new_test_db()?;
5304 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5305
5306 let mut working_stats = get_storage_stats_map(&mut db);
5307 db.grant(
5308 &KeyDescriptor {
5309 domain: Domain::APP,
5310 nspace: 0,
5311 alias: Some(TEST_ALIAS.to_string()),
5312 blob: None,
5313 },
5314 OWNER as u32,
5315 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005316 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005317 |_, _| Ok(()),
5318 )?;
5319
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005320 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005321
5322 Ok(())
5323 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005324
5325 #[test]
5326 fn find_auth_token_entry_returns_latest() -> Result<()> {
5327 let mut db = new_test_db()?;
5328 db.insert_auth_token(&HardwareAuthToken {
5329 challenge: 123,
5330 userId: 456,
5331 authenticatorId: 789,
5332 authenticatorType: kmhw_authenticator_type::ANY,
5333 timestamp: Timestamp { milliSeconds: 10 },
5334 mac: b"mac0".to_vec(),
5335 });
5336 std::thread::sleep(std::time::Duration::from_millis(1));
5337 db.insert_auth_token(&HardwareAuthToken {
5338 challenge: 123,
5339 userId: 457,
5340 authenticatorId: 789,
5341 authenticatorType: kmhw_authenticator_type::ANY,
5342 timestamp: Timestamp { milliSeconds: 12 },
5343 mac: b"mac1".to_vec(),
5344 });
5345 std::thread::sleep(std::time::Duration::from_millis(1));
5346 db.insert_auth_token(&HardwareAuthToken {
5347 challenge: 123,
5348 userId: 458,
5349 authenticatorId: 789,
5350 authenticatorType: kmhw_authenticator_type::ANY,
5351 timestamp: Timestamp { milliSeconds: 3 },
5352 mac: b"mac2".to_vec(),
5353 });
5354 // All three entries are in the database
5355 assert_eq!(db.perboot.auth_tokens_len(), 3);
5356 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005357 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005358 Ok(())
5359 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005360
5361 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005362 fn test_load_key_descriptor() -> Result<()> {
5363 let mut db = new_test_db()?;
5364 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5365
5366 let key = db.load_key_descriptor(key_id)?.unwrap();
5367
5368 assert_eq!(key.domain, Domain::APP);
5369 assert_eq!(key.nspace, 1);
5370 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5371
5372 // No such id
5373 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5374 Ok(())
5375 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005376
5377 #[test]
5378 fn test_get_list_app_uids_for_sid() -> Result<()> {
5379 let uid: i32 = 1;
5380 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5381 let first_sid = 667;
5382 let second_sid = 669;
5383 let first_app_id: i64 = 123 + uid_offset;
5384 let second_app_id: i64 = 456 + uid_offset;
5385 let third_app_id: i64 = 789 + uid_offset;
5386 let unrelated_app_id: i64 = 1011 + uid_offset;
5387 let mut db = new_test_db()?;
5388 make_test_key_entry_with_sids(
5389 &mut db,
5390 Domain::APP,
5391 first_app_id,
5392 TEST_ALIAS,
5393 None,
5394 &[first_sid],
5395 )
5396 .context("test_get_list_app_uids_for_sid")?;
5397 make_test_key_entry_with_sids(
5398 &mut db,
5399 Domain::APP,
5400 second_app_id,
5401 "alias2",
5402 None,
5403 &[first_sid],
5404 )
5405 .context("test_get_list_app_uids_for_sid")?;
5406 make_test_key_entry_with_sids(
5407 &mut db,
5408 Domain::APP,
5409 second_app_id,
5410 TEST_ALIAS,
5411 None,
5412 &[second_sid],
5413 )
5414 .context("test_get_list_app_uids_for_sid")?;
5415 make_test_key_entry_with_sids(
5416 &mut db,
5417 Domain::APP,
5418 third_app_id,
5419 "alias3",
5420 None,
5421 &[second_sid],
5422 )
5423 .context("test_get_list_app_uids_for_sid")?;
5424 make_test_key_entry_with_sids(
5425 &mut db,
5426 Domain::APP,
5427 unrelated_app_id,
5428 TEST_ALIAS,
5429 None,
5430 &[],
5431 )
5432 .context("test_get_list_app_uids_for_sid")?;
5433
5434 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5435 first_sid_apps.sort();
5436 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5437 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5438 second_sid_apps.sort();
5439 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5440 Ok(())
5441 }
5442
5443 #[test]
5444 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5445 let uid: i32 = 1;
5446 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5447 let first_sid = 667;
5448 let second_sid = 669;
5449 let third_sid = 772;
5450 let first_app_id: i64 = 123 + uid_offset;
5451 let second_app_id: i64 = 456 + uid_offset;
5452 let mut db = new_test_db()?;
5453 make_test_key_entry_with_sids(
5454 &mut db,
5455 Domain::APP,
5456 first_app_id,
5457 TEST_ALIAS,
5458 None,
5459 &[first_sid, second_sid],
5460 )
5461 .context("test_get_list_app_uids_for_sid")?;
5462 make_test_key_entry_with_sids(
5463 &mut db,
5464 Domain::APP,
5465 second_app_id,
5466 "alias2",
5467 None,
5468 &[second_sid, third_sid],
5469 )
5470 .context("test_get_list_app_uids_for_sid")?;
5471
5472 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5473 assert_eq!(first_sid_apps, vec![first_app_id]);
5474
5475 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5476 second_sid_apps.sort();
5477 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5478
5479 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5480 assert_eq!(third_sid_apps, vec![second_app_id]);
5481 Ok(())
5482 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005483}