blob: ffc80c9696607443d2382272a7356d6c01d69760 [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
Janis Danisevskis030ba022021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskis11bd2592022-01-04 19:59:26 -080048use crate::gc::Gc;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use crate::impl_metadata; // This is in db_utils.rs
Eric Biggersb0478cf2023-10-27 03:55:29 +000050use crate::key_parameter::{KeyParameter, KeyParameterValue, Tag};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000051use crate::ks_err;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070052use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000053use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070055 error::{Error as KsError, ErrorCode, ResponseCode},
56 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080057};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000058use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Tri Voa1634bb2022-12-01 15:54:19 -080059 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
60 SecurityLevel::SecurityLevel,
61};
62use android_security_metrics::aidl::android::security::metrics::{
Tri Vo0346bbe2023-05-12 14:16:31 -040063 Storage::Storage as MetricsStorage, StorageStats::StorageStats,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080064};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070065use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070066 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070067};
Shaquille Johnson7f5a8152023-09-27 18:46:27 +010068use anyhow::{anyhow, Context, Result};
69use keystore2_flags;
70use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
71use utils as db_utils;
72use utils::SqlField;
Max Bires2b2e6562020-09-22 11:22:36 -070073
74use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080075use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000076use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070077#[cfg(not(test))]
78use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070079use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070080 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080081 types::FromSql,
82 types::FromSqlResult,
83 types::ToSqlOutput,
84 types::{FromSqlError, Value, ValueRef},
David Drysdale7b9ca232024-05-23 18:19:46 +010085 Connection, OptionalExtension, ToSql, Transaction,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070086};
Max Bires2b2e6562020-09-22 11:22:36 -070087
Janis Danisevskisaec14592020-11-12 09:41:49 -080088use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080089 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080090 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070091 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080093};
Max Bires2b2e6562020-09-22 11:22:36 -070094
David Drysdale7b9ca232024-05-23 18:19:46 +010095use TransactionBehavior::Immediate;
96
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
David Drysdale7b9ca232024-05-23 18:19:46 +0100100/// Wrapper for `rusqlite::TransactionBehavior` which includes information about the transaction
101/// being performed.
102#[derive(Clone, Copy)]
103enum TransactionBehavior {
104 Deferred,
105 Immediate(&'static str),
106}
107
108impl From<TransactionBehavior> for rusqlite::TransactionBehavior {
109 fn from(val: TransactionBehavior) -> Self {
110 match val {
111 TransactionBehavior::Deferred => rusqlite::TransactionBehavior::Deferred,
112 TransactionBehavior::Immediate(_) => rusqlite::TransactionBehavior::Immediate,
113 }
114 }
115}
116
117impl TransactionBehavior {
118 fn name(&self) -> Option<&'static str> {
119 match self {
120 TransactionBehavior::Deferred => None,
121 TransactionBehavior::Immediate(v) => Some(v),
122 }
123 }
124}
125
David Drysdale115c4722024-04-15 14:11:52 +0100126/// If the database returns a busy error code, retry after this interval.
127const DB_BUSY_RETRY_INTERVAL: Duration = Duration::from_micros(500);
David Drysdale115c4722024-04-15 14:11:52 +0100128
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800129impl_metadata!(
130 /// A set of metadata for key entries.
131 #[derive(Debug, Default, Eq, PartialEq)]
132 pub struct KeyMetaData;
133 /// A metadata entry for key entries.
134 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
135 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800136 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 CreationDate(DateTime) with accessor creation_date,
138 /// Expiration date for attestation keys.
139 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700140 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
141 /// provisioning
142 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
143 /// Vector representing the raw public key so results from the server can be matched
144 /// to the right entry
145 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700146 /// SEC1 public key for ECDH encryption
147 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800148 // --- ADD NEW META DATA FIELDS HERE ---
149 // For backwards compatibility add new entries only to
150 // end of this list and above this comment.
151 };
152);
153
154impl KeyMetaData {
155 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
156 let mut stmt = tx
157 .prepare(
158 "SELECT tag, data from persistent.keymetadata
159 WHERE keyentryid = ?;",
160 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000161 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800162
163 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
164
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000165 let mut rows = stmt
166 .query(params![key_id])
167 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800168 db_utils::with_rows_extract_all(&mut rows, |row| {
169 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
170 metadata.insert(
171 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700172 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800173 .context("Failed to read KeyMetaEntry.")?,
174 );
175 Ok(())
176 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000177 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800178
179 Ok(Self { data: metadata })
180 }
181
182 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
183 let mut stmt = tx
184 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000185 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800186 VALUES (?, ?, ?);",
187 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000188 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800189
190 let iter = self.data.iter();
191 for (tag, entry) in iter {
192 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000193 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800194 })?;
195 }
196 Ok(())
197 }
198}
199
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800200impl_metadata!(
201 /// A set of metadata for key blobs.
202 #[derive(Debug, Default, Eq, PartialEq)]
203 pub struct BlobMetaData;
204 /// A metadata entry for key blobs.
205 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
206 pub enum BlobMetaEntry {
207 /// If present, indicates that the blob is encrypted with another key or a key derived
208 /// from a password.
209 EncryptedBy(EncryptedBy) with accessor encrypted_by,
210 /// If the blob is password encrypted this field is set to the
211 /// salt used for the key derivation.
212 Salt(Vec<u8>) with accessor salt,
213 /// If the blob is encrypted, this field is set to the initialization vector.
214 Iv(Vec<u8>) with accessor iv,
215 /// If the blob is encrypted, this field holds the AEAD TAG.
216 AeadTag(Vec<u8>) with accessor aead_tag,
217 /// The uuid of the owning KeyMint instance.
218 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700219 /// If the key is ECDH encrypted, this is the ephemeral public key
220 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000221 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
222 /// of that key
223 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800224 // --- ADD NEW META DATA FIELDS HERE ---
225 // For backwards compatibility add new entries only to
226 // end of this list and above this comment.
227 };
228);
229
230impl BlobMetaData {
231 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
232 let mut stmt = tx
233 .prepare(
234 "SELECT tag, data from persistent.blobmetadata
235 WHERE blobentryid = ?;",
236 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000237 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800238
239 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
240
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000241 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800242 db_utils::with_rows_extract_all(&mut rows, |row| {
243 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
244 metadata.insert(
245 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700246 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800247 .context("Failed to read BlobMetaEntry.")?,
248 );
249 Ok(())
250 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000251 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800252
253 Ok(Self { data: metadata })
254 }
255
256 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
257 let mut stmt = tx
258 .prepare(
259 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
260 VALUES (?, ?, ?);",
261 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000262 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800263
264 let iter = self.data.iter();
265 for (tag, entry) in iter {
266 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000267 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800268 })?;
269 }
270 Ok(())
271 }
272}
273
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800274/// Indicates the type of the keyentry.
275#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
276pub enum KeyType {
277 /// This is a client key type. These keys are created or imported through the Keystore 2.0
278 /// AIDL interface android.system.keystore2.
279 Client,
280 /// This is a super key type. These keys are created by keystore itself and used to encrypt
281 /// other key blobs to provide LSKF binding.
282 Super,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800283}
284
285impl ToSql for KeyType {
286 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
287 Ok(ToSqlOutput::Owned(Value::Integer(match self {
288 KeyType::Client => 0,
289 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800290 })))
291 }
292}
293
294impl FromSql for KeyType {
295 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
296 match i64::column_result(value)? {
297 0 => Ok(KeyType::Client),
298 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800299 v => Err(FromSqlError::OutOfRange(v)),
300 }
301 }
302}
303
Max Bires8e93d2b2021-01-14 13:17:59 -0800304/// Uuid representation that can be stored in the database.
305/// Right now it can only be initialized from SecurityLevel.
306/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
307#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
308pub struct Uuid([u8; 16]);
309
310impl Deref for Uuid {
311 type Target = [u8; 16];
312
313 fn deref(&self) -> &Self::Target {
314 &self.0
315 }
316}
317
318impl From<SecurityLevel> for Uuid {
319 fn from(sec_level: SecurityLevel) -> Self {
320 Self((sec_level.0 as u128).to_be_bytes())
321 }
322}
323
324impl ToSql for Uuid {
325 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
326 self.0.to_sql()
327 }
328}
329
330impl FromSql for Uuid {
331 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
332 let blob = Vec::<u8>::column_result(value)?;
333 if blob.len() != 16 {
334 return Err(FromSqlError::OutOfRange(blob.len() as i64));
335 }
336 let mut arr = [0u8; 16];
337 arr.copy_from_slice(&blob);
338 Ok(Self(arr))
339 }
340}
341
342/// Key entries that are not associated with any KeyMint instance, such as pure certificate
343/// entries are associated with this UUID.
344pub static KEYSTORE_UUID: Uuid = Uuid([
345 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
346]);
347
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800348/// Indicates how the sensitive part of this key blob is encrypted.
349#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
350pub enum EncryptedBy {
351 /// The keyblob is encrypted by a user password.
352 /// In the database this variant is represented as NULL.
353 Password,
354 /// The keyblob is encrypted by another key with wrapped key id.
355 /// In the database this variant is represented as non NULL value
356 /// that is convertible to i64, typically NUMERIC.
357 KeyId(i64),
358}
359
360impl ToSql for EncryptedBy {
361 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
362 match self {
363 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
364 Self::KeyId(id) => id.to_sql(),
365 }
366 }
367}
368
369impl FromSql for EncryptedBy {
370 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
371 match value {
372 ValueRef::Null => Ok(Self::Password),
373 _ => Ok(Self::KeyId(i64::column_result(value)?)),
374 }
375 }
376}
377
378/// A database representation of wall clock time. DateTime stores unix epoch time as
379/// i64 in milliseconds.
380#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
381pub struct DateTime(i64);
382
383/// Error type returned when creating DateTime or converting it from and to
384/// SystemTime.
385#[derive(thiserror::Error, Debug)]
386pub enum DateTimeError {
387 /// This is returned when SystemTime and Duration computations fail.
388 #[error(transparent)]
389 SystemTimeError(#[from] SystemTimeError),
390
391 /// This is returned when type conversions fail.
392 #[error(transparent)]
393 TypeConversion(#[from] std::num::TryFromIntError),
394
395 /// This is returned when checked time arithmetic failed.
396 #[error("Time arithmetic failed.")]
397 TimeArithmetic,
398}
399
400impl DateTime {
401 /// Constructs a new DateTime object denoting the current time. This may fail during
402 /// conversion to unix epoch time and during conversion to the internal i64 representation.
403 pub fn now() -> Result<Self, DateTimeError> {
404 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
405 }
406
407 /// Constructs a new DateTime object from milliseconds.
408 pub fn from_millis_epoch(millis: i64) -> Self {
409 Self(millis)
410 }
411
412 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700413 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800414 self.0
415 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800416}
417
418impl ToSql for DateTime {
419 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
420 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
421 }
422}
423
424impl FromSql for DateTime {
425 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
426 Ok(Self(i64::column_result(value)?))
427 }
428}
429
430impl TryInto<SystemTime> for DateTime {
431 type Error = DateTimeError;
432
433 fn try_into(self) -> Result<SystemTime, Self::Error> {
434 // We want to construct a SystemTime representation equivalent to self, denoting
435 // a point in time THEN, but we cannot set the time directly. We can only construct
436 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
437 // and between EPOCH and THEN. With this common reference we can construct the
438 // duration between NOW and THEN which we can add to our SystemTime representation
439 // of NOW to get a SystemTime representation of THEN.
440 // Durations can only be positive, thus the if statement below.
441 let now = SystemTime::now();
442 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
443 let then_epoch = Duration::from_millis(self.0.try_into()?);
444 Ok(if now_epoch > then_epoch {
445 // then = now - (now_epoch - then_epoch)
446 now_epoch
447 .checked_sub(then_epoch)
448 .and_then(|d| now.checked_sub(d))
449 .ok_or(DateTimeError::TimeArithmetic)?
450 } else {
451 // then = now + (then_epoch - now_epoch)
452 then_epoch
453 .checked_sub(now_epoch)
454 .and_then(|d| now.checked_add(d))
455 .ok_or(DateTimeError::TimeArithmetic)?
456 })
457 }
458}
459
460impl TryFrom<SystemTime> for DateTime {
461 type Error = DateTimeError;
462
463 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
464 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
465 }
466}
467
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800468#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
469enum KeyLifeCycle {
470 /// Existing keys have a key ID but are not fully populated yet.
471 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
472 /// them to Unreferenced for garbage collection.
473 Existing,
474 /// A live key is fully populated and usable by clients.
475 Live,
476 /// An unreferenced key is scheduled for garbage collection.
477 Unreferenced,
478}
479
480impl ToSql for KeyLifeCycle {
481 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
482 match self {
483 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
484 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
485 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
486 }
487 }
488}
489
490impl FromSql for KeyLifeCycle {
491 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
492 match i64::column_result(value)? {
493 0 => Ok(KeyLifeCycle::Existing),
494 1 => Ok(KeyLifeCycle::Live),
495 2 => Ok(KeyLifeCycle::Unreferenced),
496 v => Err(FromSqlError::OutOfRange(v)),
497 }
498 }
499}
500
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700501/// Keys have a KeyMint blob component and optional public certificate and
502/// certificate chain components.
503/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
504/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800505#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700506pub struct KeyEntryLoadBits(u32);
507
508impl KeyEntryLoadBits {
509 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
510 pub const NONE: KeyEntryLoadBits = Self(0);
511 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
512 pub const KM: KeyEntryLoadBits = Self(1);
513 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
514 pub const PUBLIC: KeyEntryLoadBits = Self(2);
515 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
516 pub const BOTH: KeyEntryLoadBits = Self(3);
517
518 /// Returns true if this object indicates that the public components shall be loaded.
519 pub const fn load_public(&self) -> bool {
520 self.0 & Self::PUBLIC.0 != 0
521 }
522
523 /// Returns true if the object indicates that the KeyMint component shall be loaded.
524 pub const fn load_km(&self) -> bool {
525 self.0 & Self::KM.0 != 0
526 }
527}
528
Janis Danisevskisaec14592020-11-12 09:41:49 -0800529lazy_static! {
530 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
531}
532
533struct KeyIdLockDb {
534 locked_keys: Mutex<HashSet<i64>>,
535 cond_var: Condvar,
536}
537
538/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
539/// from the database a second time. Most functions manipulating the key blob database
540/// require a KeyIdGuard.
541#[derive(Debug)]
542pub struct KeyIdGuard(i64);
543
544impl KeyIdLockDb {
545 fn new() -> Self {
546 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
547 }
548
549 /// This function blocks until an exclusive lock for the given key entry id can
550 /// be acquired. It returns a guard object, that represents the lifecycle of the
551 /// acquired lock.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000552 fn get(&self, key_id: i64) -> KeyIdGuard {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800553 let mut locked_keys = self.locked_keys.lock().unwrap();
554 while locked_keys.contains(&key_id) {
555 locked_keys = self.cond_var.wait(locked_keys).unwrap();
556 }
557 locked_keys.insert(key_id);
558 KeyIdGuard(key_id)
559 }
560
561 /// This function attempts to acquire an exclusive lock on a given key id. If the
562 /// given key id is already taken the function returns None immediately. If a lock
563 /// can be acquired this function returns a guard object, that represents the
564 /// lifecycle of the acquired lock.
David Drysdale8c4c4f32023-10-31 12:14:11 +0000565 fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
Janis Danisevskisaec14592020-11-12 09:41:49 -0800566 let mut locked_keys = self.locked_keys.lock().unwrap();
567 if locked_keys.insert(key_id) {
568 Some(KeyIdGuard(key_id))
569 } else {
570 None
571 }
572 }
573}
574
575impl KeyIdGuard {
576 /// Get the numeric key id of the locked key.
577 pub fn id(&self) -> i64 {
578 self.0
579 }
580}
581
582impl Drop for KeyIdGuard {
583 fn drop(&mut self) {
584 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
585 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800586 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800587 KEY_ID_LOCK.cond_var.notify_all();
588 }
589}
590
Max Bires8e93d2b2021-01-14 13:17:59 -0800591/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700592#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800593pub struct CertificateInfo {
594 cert: Option<Vec<u8>>,
595 cert_chain: Option<Vec<u8>>,
596}
597
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800598/// This type represents a Blob with its metadata and an optional superseded blob.
599#[derive(Debug)]
600pub struct BlobInfo<'a> {
601 blob: &'a [u8],
602 metadata: &'a BlobMetaData,
603 /// Superseded blobs are an artifact of legacy import. In some rare occasions
604 /// the key blob needs to be upgraded during import. In that case two
605 /// blob are imported, the superseded one will have to be imported first,
606 /// so that the garbage collector can reap it.
607 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
608}
609
610impl<'a> BlobInfo<'a> {
611 /// Create a new instance of blob info with blob and corresponding metadata
612 /// and no superseded blob info.
613 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
614 Self { blob, metadata, superseded_blob: None }
615 }
616
617 /// Create a new instance of blob info with blob and corresponding metadata
618 /// as well as superseded blob info.
619 pub fn new_with_superseded(
620 blob: &'a [u8],
621 metadata: &'a BlobMetaData,
622 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
623 ) -> Self {
624 Self { blob, metadata, superseded_blob }
625 }
626}
627
Max Bires8e93d2b2021-01-14 13:17:59 -0800628impl CertificateInfo {
629 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
630 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
631 Self { cert, cert_chain }
632 }
633
634 /// Take the cert
635 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
636 self.cert.take()
637 }
638
639 /// Take the cert chain
640 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
641 self.cert_chain.take()
642 }
643}
644
Max Bires2b2e6562020-09-22 11:22:36 -0700645/// This type represents a certificate chain with a private key corresponding to the leaf
646/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700647pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800648 /// A KM key blob
649 pub private_key: ZVec,
650 /// A batch cert for private_key
651 pub batch_cert: Vec<u8>,
652 /// A full certificate chain from root signing authority to private_key, including batch_cert
653 /// for convenience.
654 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700655}
656
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700657/// This type represents a Keystore 2.0 key entry.
658/// An entry has a unique `id` by which it can be found in the database.
659/// It has a security level field, key parameters, and three optional fields
660/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800661#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700662pub struct KeyEntry {
663 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800664 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700665 cert: Option<Vec<u8>>,
666 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800667 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700668 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800669 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800670 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700671}
672
673impl KeyEntry {
674 /// Returns the unique id of the Key entry.
675 pub fn id(&self) -> i64 {
676 self.id
677 }
678 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800679 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
680 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800682 /// Extracts the Optional KeyMint blob including its metadata.
683 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
684 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 }
686 /// Exposes the optional public certificate.
687 pub fn cert(&self) -> &Option<Vec<u8>> {
688 &self.cert
689 }
690 /// Extracts the optional public certificate.
691 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
692 self.cert.take()
693 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700694 /// Extracts the optional public certificate_chain.
695 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
696 self.cert_chain.take()
697 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800698 /// Returns the uuid of the owning KeyMint instance.
699 pub fn km_uuid(&self) -> &Uuid {
700 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700701 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700702 /// Consumes this key entry and extracts the keyparameters from it.
703 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
704 self.parameters
705 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800706 /// Exposes the key metadata of this key entry.
707 pub fn metadata(&self) -> &KeyMetaData {
708 &self.metadata
709 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800710 /// This returns true if the entry is a pure certificate entry with no
711 /// private key component.
712 pub fn pure_cert(&self) -> bool {
713 self.pure_cert
714 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700715}
716
717/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800718#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700719pub struct SubComponentType(u32);
720impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800721 /// Persistent identifier for a key blob.
722 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700723 /// Persistent identifier for a certificate blob.
724 pub const CERT: SubComponentType = Self(1);
725 /// Persistent identifier for a certificate chain blob.
726 pub const CERT_CHAIN: SubComponentType = Self(2);
727}
728
729impl ToSql for SubComponentType {
730 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
731 self.0.to_sql()
732 }
733}
734
735impl FromSql for SubComponentType {
736 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
737 Ok(Self(u32::column_result(value)?))
738 }
739}
740
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800741/// This trait is private to the database module. It is used to convey whether or not the garbage
742/// collector shall be invoked after a database access. All closures passed to
743/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
744/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
745/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
746/// `.need_gc()`.
747trait DoGc<T> {
748 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
749
750 fn no_gc(self) -> Result<(bool, T)>;
751
752 fn need_gc(self) -> Result<(bool, T)>;
753}
754
755impl<T> DoGc<T> for Result<T> {
756 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
757 self.map(|r| (need_gc, r))
758 }
759
760 fn no_gc(self) -> Result<(bool, T)> {
761 self.do_gc(false)
762 }
763
764 fn need_gc(self) -> Result<(bool, T)> {
765 self.do_gc(true)
766 }
767}
768
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700769/// KeystoreDB wraps a connection to an SQLite database and tracks its
770/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700771pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700772 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700773 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700774 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700775}
776
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000777/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000778/// CLOCK_BOOTTIME. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000779#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000780pub struct BootTime(i64);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000781
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000782impl BootTime {
783 /// Constructs a new BootTime
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000784 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000785 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000786 }
787
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000788 /// Returns the value of BootTime in milliseconds as i64
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000789 pub fn milliseconds(&self) -> i64 {
790 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000791 }
792
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000793 /// Returns the integer value of BootTime as i64
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000794 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000795 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000796 }
797
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 /// Like i64::checked_sub.
799 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
800 self.0.checked_sub(other.0).map(Self)
801 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000802}
803
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000804impl ToSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000805 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
806 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
807 }
808}
809
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000810impl FromSql for BootTime {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000811 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
812 Ok(Self(i64::column_result(value)?))
813 }
814}
815
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000816/// This struct encapsulates the information to be stored in the database about the auth tokens
817/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700818#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000819pub struct AuthTokenEntry {
820 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000821 // Time received in milliseconds
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000822 time_received: BootTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000823}
824
825impl AuthTokenEntry {
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000826 fn new(auth_token: HardwareAuthToken, time_received: BootTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000827 AuthTokenEntry { auth_token, time_received }
828 }
829
830 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800831 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000832 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800833 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000834 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000835 })
836 }
837
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000838 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800839 pub fn auth_token(&self) -> &HardwareAuthToken {
840 &self.auth_token
841 }
842
843 /// Returns the auth token wrapped by the AuthTokenEntry
844 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000845 self.auth_token
846 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800847
848 /// Returns the time that this auth token was received.
Eric Biggers19b3b0d2024-01-31 22:46:47 +0000849 pub fn time_received(&self) -> BootTime {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800850 self.time_received
851 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000852
853 /// Returns the challenge value of the auth token.
854 pub fn challenge(&self) -> i64 {
855 self.auth_token.challenge
856 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000857}
858
Joel Galenson26f4d012020-07-17 14:57:21 -0700859impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800860 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700861 const CURRENT_DB_VERSION: u32 = 1;
862 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800863
Seth Moore78c091f2021-04-09 21:38:30 +0000864 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700865 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000866
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700867 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868 /// files persistent.sqlite and perboot.sqlite in the given directory.
869 /// It also attempts to initialize all of the tables.
870 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700871 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700872 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
David Drysdale541846b2024-05-23 13:16:07 +0100873 let _wp = wd::watch("KeystoreDB::new");
Janis Danisevskis850d4862021-05-05 08:41:14 -0700874
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700875 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700876 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800877
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700878 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
David Drysdale7b9ca232024-05-23 18:19:46 +0100879 db.with_transaction(Immediate("TX_new"), |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700880 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000881 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800882 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800883 })?;
884 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700885 }
886
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700887 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
888 // cryptographic binding to the boot level keys was implemented.
889 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
890 tx.execute(
891 "UPDATE persistent.keyentry SET state = ?
892 WHERE
893 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
894 AND
895 id NOT IN (
896 SELECT keyentryid FROM persistent.blobentry
897 WHERE id IN (
898 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
899 )
900 );",
901 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
902 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000903 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700904 Ok(1)
905 }
906
Janis Danisevskis66784c42021-01-27 08:40:25 -0800907 fn init_tables(tx: &Transaction) -> Result<()> {
908 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700910 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800911 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700912 domain INTEGER,
913 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800914 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800915 state INTEGER,
916 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000917 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700918 )
919 .context("Failed to initialize \"keyentry\" table.")?;
920
Janis Danisevskis66784c42021-01-27 08:40:25 -0800921 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800922 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
923 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000924 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800925 )
926 .context("Failed to create index keyentry_id_index.")?;
927
928 tx.execute(
929 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
930 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000931 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800932 )
933 .context("Failed to create index keyentry_domain_namespace_index.")?;
934
935 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700936 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
937 id INTEGER PRIMARY KEY,
938 subcomponent_type INTEGER,
939 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800940 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000941 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700942 )
943 .context("Failed to initialize \"blobentry\" table.")?;
944
Janis Danisevskis66784c42021-01-27 08:40:25 -0800945 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800946 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
947 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000948 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800949 )
950 .context("Failed to create index blobentry_keyentryid_index.")?;
951
952 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800953 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
954 id INTEGER PRIMARY KEY,
955 blobentryid INTEGER,
956 tag INTEGER,
957 data ANY,
958 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000959 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800960 )
961 .context("Failed to initialize \"blobmetadata\" table.")?;
962
963 tx.execute(
964 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
965 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000966 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800967 )
968 .context("Failed to create index blobmetadata_blobentryid_index.")?;
969
970 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700971 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000972 keyentryid INTEGER,
973 tag INTEGER,
974 data ANY,
975 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000976 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700977 )
978 .context("Failed to initialize \"keyparameter\" table.")?;
979
Janis Danisevskis66784c42021-01-27 08:40:25 -0800980 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800981 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
982 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000983 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800984 )
985 .context("Failed to create index keyparameter_keyentryid_index.")?;
986
987 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800988 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
989 keyentryid INTEGER,
990 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000991 data ANY,
992 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000993 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800994 )
995 .context("Failed to initialize \"keymetadata\" table.")?;
996
Janis Danisevskis66784c42021-01-27 08:40:25 -0800997 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800998 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
999 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001000 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -08001001 )
1002 .context("Failed to create index keymetadata_keyentryid_index.")?;
1003
1004 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001005 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001006 id INTEGER UNIQUE,
1007 grantee INTEGER,
1008 keyentryid INTEGER,
1009 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001010 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001011 )
1012 .context("Failed to initialize \"grant\" table.")?;
1013
Joel Galenson0891bc12020-07-20 10:37:03 -07001014 Ok(())
1015 }
1016
Seth Moore472fcbb2021-05-12 10:07:51 -07001017 fn make_persistent_path(db_root: &Path) -> Result<String> {
1018 // Build the path to the sqlite file.
1019 let mut persistent_path = db_root.to_path_buf();
1020 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1021
1022 // Now convert them to strings prefixed with "file:"
1023 let mut persistent_path_str = "file:".to_owned();
1024 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1025
Shaquille Johnson52b8c932023-12-19 19:45:32 +00001026 // Connect to database in specific mode
1027 let persistent_path_mode = if keystore2_flags::wal_db_journalmode_v3() {
1028 "?journal_mode=WAL".to_owned()
1029 } else {
1030 "?journal_mode=DELETE".to_owned()
1031 };
1032 persistent_path_str.push_str(&persistent_path_mode);
1033
Seth Moore472fcbb2021-05-12 10:07:51 -07001034 Ok(persistent_path_str)
1035 }
1036
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001037 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001038 let conn =
1039 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1040
Janis Danisevskis66784c42021-01-27 08:40:25 -08001041 loop {
1042 if let Err(e) = conn
1043 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1044 .context("Failed to attach database persistent.")
1045 {
1046 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001047 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001048 continue;
1049 } else {
1050 return Err(e);
1051 }
1052 }
1053 break;
1054 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001055
Matthew Maurer4fb19112021-05-06 15:40:44 -07001056 // Drop the cache size from default (2M) to 0.5M
1057 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1058 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001059
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001060 Ok(conn)
1061 }
1062
Seth Moore78c091f2021-04-09 21:38:30 +00001063 fn do_table_size_query(
1064 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001065 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001066 query: &str,
1067 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001068 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001069 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001070 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001071 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001072 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001073 })
1074 .no_gc()
1075 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001076 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001077 }
1078
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001079 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001080 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001081 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001082 "SELECT page_count * page_size, freelist_count * page_size
1083 FROM pragma_page_count('persistent'),
1084 pragma_page_size('persistent'),
1085 persistent.pragma_freelist_count();",
1086 &[],
1087 )
1088 }
1089
1090 fn get_table_size(
1091 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001092 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001093 schema: &str,
1094 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001095 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001096 self.do_table_size_query(
1097 storage_type,
1098 "SELECT pgsize,unused FROM dbstat(?1)
1099 WHERE name=?2 AND aggregate=TRUE;",
1100 &[schema, table],
1101 )
1102 }
1103
1104 /// Fetches a storage statisitics atom for a given storage type. For storage
1105 /// types that map to a table, information about the table's storage is
1106 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
David Drysdale541846b2024-05-23 13:16:07 +01001108 let _wp = wd::watch("KeystoreDB::get_storage_stat");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001109
Seth Moore78c091f2021-04-09 21:38:30 +00001110 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001111 MetricsStorage::DATABASE => self.get_total_size(),
1112 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001113 self.get_table_size(storage_type, "persistent", "keyentry")
1114 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001115 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001116 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1117 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001118 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001119 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1120 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001121 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001122 self.get_table_size(storage_type, "persistent", "blobentry")
1123 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001124 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001125 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1126 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001128 self.get_table_size(storage_type, "persistent", "keyparameter")
1129 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001131 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1132 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001133 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001134 self.get_table_size(storage_type, "persistent", "keymetadata")
1135 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001137 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1138 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1140 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001141 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1142 // reportable
1143 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001144 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001145 storage_type,
1146 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001147 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001148 unused_size: 0,
1149 })
Seth Moore78c091f2021-04-09 21:38:30 +00001150 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001151 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001152 self.get_table_size(storage_type, "persistent", "blobmetadata")
1153 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001154 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001155 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1156 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001157 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001158 }
1159 }
1160
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001162 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1163 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1165 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001166 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001168 blob_ids_to_delete: &[i64],
1169 max_blobs: usize,
1170 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
David Drysdale541846b2024-05-23 13:16:07 +01001171 let _wp = wd::watch("KeystoreDB::handle_next_superseded_blob");
David Drysdale7b9ca232024-05-23 18:19:46 +01001172 self.with_transaction(Immediate("TX_handle_next_superseded_blob"), |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001173 // Delete the given blobs.
1174 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001175 tx.execute(
1176 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001177 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001178 )
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001179 .context(ks_err!("Trying to delete blob metadata: {:?}", blob_id))?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001180 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
Shaquille Johnsonf23fc942024-02-13 17:01:29 +00001181 .context(ks_err!("Trying to delete blob: {:?}", blob_id))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001182 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001183
1184 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1185
Janis Danisevskis3395f862021-05-06 10:54:17 -07001186 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1187 let result: Vec<(i64, Vec<u8>)> = {
1188 let mut stmt = tx
1189 .prepare(
1190 "SELECT id, blob FROM persistent.blobentry
1191 WHERE subcomponent_type = ?
1192 AND (
1193 id NOT IN (
1194 SELECT MAX(id) FROM persistent.blobentry
1195 WHERE subcomponent_type = ?
1196 GROUP BY keyentryid, subcomponent_type
1197 )
1198 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1199 ) LIMIT ?;",
1200 )
1201 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001202
Janis Danisevskis3395f862021-05-06 10:54:17 -07001203 let rows = stmt
1204 .query_map(
1205 params![
1206 SubComponentType::KEY_BLOB,
1207 SubComponentType::KEY_BLOB,
1208 max_blobs as i64,
1209 ],
1210 |row| Ok((row.get(0)?, row.get(1)?)),
1211 )
1212 .context("Trying to query superseded blob.")?;
1213
1214 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1215 .context("Trying to extract superseded blobs.")?
1216 };
1217
1218 let result = result
1219 .into_iter()
1220 .map(|(blob_id, blob)| {
1221 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1222 })
1223 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1224 .context("Trying to load blob metadata.")?;
1225 if !result.is_empty() {
1226 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001227 }
1228
1229 // We did not find any superseded key blob, so let's remove other superseded blob in
1230 // one transaction.
1231 tx.execute(
1232 "DELETE FROM persistent.blobentry
1233 WHERE NOT subcomponent_type = ?
1234 AND (
1235 id NOT IN (
1236 SELECT MAX(id) FROM persistent.blobentry
1237 WHERE NOT subcomponent_type = ?
1238 GROUP BY keyentryid, subcomponent_type
1239 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1240 );",
1241 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1242 )
1243 .context("Trying to purge superseded blobs.")?;
1244
Janis Danisevskis3395f862021-05-06 10:54:17 -07001245 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001246 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001247 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001248 }
1249
1250 /// This maintenance function should be called only once before the database is used for the
1251 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1252 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1253 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1254 /// Keystore crashed at some point during key generation. Callers may want to log such
1255 /// occurrences.
1256 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1257 /// it to `KeyLifeCycle::Live` may have grants.
1258 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01001259 let _wp = wd::watch("KeystoreDB::cleanup_leftovers");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001260
David Drysdale7b9ca232024-05-23 18:19:46 +01001261 self.with_transaction(Immediate("TX_cleanup_leftovers"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001262 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001263 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1264 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1265 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001266 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001267 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001268 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001269 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001270 }
1271
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001272 /// Checks if a key exists with given key type and key descriptor properties.
1273 pub fn key_exists(
1274 &mut self,
1275 domain: Domain,
1276 nspace: i64,
1277 alias: &str,
1278 key_type: KeyType,
1279 ) -> Result<bool> {
David Drysdale541846b2024-05-23 13:16:07 +01001280 let _wp = wd::watch("KeystoreDB::key_exists");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001281
David Drysdale7b9ca232024-05-23 18:19:46 +01001282 self.with_transaction(Immediate("TX_key_exists"), |tx| {
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001283 let key_descriptor =
1284 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001285 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001286 match result {
1287 Ok(_) => Ok(true),
1288 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1289 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001290 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001291 },
1292 }
1293 .no_gc()
1294 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001295 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001296 }
1297
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 /// Stores a super key in the database.
1299 pub fn store_super_key(
1300 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001301 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001302 key_type: &SuperKeyType,
1303 blob: &[u8],
1304 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001305 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001306 ) -> Result<KeyEntry> {
David Drysdale541846b2024-05-23 13:16:07 +01001307 let _wp = wd::watch("KeystoreDB::store_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001308
David Drysdale7b9ca232024-05-23 18:19:46 +01001309 self.with_transaction(Immediate("TX_store_super_key"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00001310 let key_id = Self::insert_with_retry(|id| {
1311 tx.execute(
1312 "INSERT into persistent.keyentry
1313 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001314 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001315 params![
1316 id,
1317 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001318 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001319 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001320 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001321 KeyLifeCycle::Live,
1322 &KEYSTORE_UUID,
1323 ],
1324 )
1325 })
1326 .context("Failed to insert into keyentry table.")?;
1327
Paul Crowley8d5b2532021-03-19 10:53:07 -07001328 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1329
Hasini Gunasingheda895552021-01-27 19:34:37 +00001330 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001331 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001332 key_id,
1333 SubComponentType::KEY_BLOB,
1334 Some(blob),
1335 Some(blob_metadata),
1336 )
1337 .context("Failed to store key blob.")?;
1338
1339 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1340 .context("Trying to load key components.")
1341 .no_gc()
1342 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001343 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001344 }
1345
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001347 pub fn load_super_key(
1348 &mut self,
1349 key_type: &SuperKeyType,
1350 user_id: u32,
1351 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
David Drysdale541846b2024-05-23 13:16:07 +01001352 let _wp = wd::watch("KeystoreDB::load_super_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001353
David Drysdale7b9ca232024-05-23 18:19:46 +01001354 self.with_transaction(Immediate("TX_load_super_key"), |tx| {
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001355 let key_descriptor = KeyDescriptor {
1356 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001357 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001358 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001359 blob: None,
1360 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001361 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001362 match id {
1363 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001364 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001365 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001366 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1367 }
1368 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1369 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001370 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001371 },
1372 }
1373 .no_gc()
1374 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001375 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001376 }
1377
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001378 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001379 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1380 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001381 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1382 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001383 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001384 {
David Drysdale7b9ca232024-05-23 18:19:46 +01001385 let name = behavior.name();
Janis Danisevskis66784c42021-01-27 08:40:25 -08001386 loop {
James Farrellefe1a2f2024-02-28 21:36:47 +00001387 let result = self
Janis Danisevskis66784c42021-01-27 08:40:25 -08001388 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01001389 .transaction_with_behavior(behavior.into())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001390 .context(ks_err!())
David Drysdale7b9ca232024-05-23 18:19:46 +01001391 .and_then(|tx| {
1392 let _wp = name.map(wd::watch);
1393 f(&tx).map(|result| (result, tx))
1394 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001395 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001396 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 Ok(result)
James Farrellefe1a2f2024-02-28 21:36:47 +00001398 });
1399 match result {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 Ok(result) => break Ok(result),
1401 Err(e) => {
1402 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01001403 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 continue;
1405 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001406 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 }
1408 }
1409 }
1410 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001411 .map(|(need_gc, result)| {
1412 if need_gc {
1413 if let Some(ref gc) = self.gc {
1414 gc.notify_gc();
1415 }
1416 }
1417 result
1418 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 }
1420
1421 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001422 matches!(
1423 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1424 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1425 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1426 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001427 }
1428
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001429 fn create_key_entry_internal(
1430 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001431 domain: &Domain,
1432 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001433 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001434 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001435 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001436 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001437 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001438 _ => {
1439 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001440 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001441 }
1442 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001443 Ok(KEY_ID_LOCK.get(
1444 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001445 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001446 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001447 (id, key_type, domain, namespace, alias, state, km_uuid)
1448 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001449 params![
1450 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001451 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001452 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001453 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001454 KeyLifeCycle::Existing,
1455 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001456 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001457 )
1458 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001459 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001460 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001461 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001462
Janis Danisevskis377d1002021-01-27 19:07:48 -08001463 /// Set a new blob and associates it with the given key id. Each blob
1464 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001465 /// Each key can have one of each sub component type associated. If more
1466 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001467 /// will get garbage collected.
1468 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1469 /// removed by setting blob to None.
1470 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001471 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001472 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001473 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001474 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001475 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001476 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001477 let _wp = wd::watch("KeystoreDB::set_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001478
David Drysdale7b9ca232024-05-23 18:19:46 +01001479 self.with_transaction(Immediate("TX_set_blob"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001480 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001481 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001482 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001483 }
1484
Janis Danisevskiseed69842021-02-18 20:04:10 -08001485 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1486 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1487 /// We use this to insert key blobs into the database which can then be garbage collected
1488 /// lazily by the key garbage collector.
1489 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001490 let _wp = wd::watch("KeystoreDB::set_deleted_blob");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001491
David Drysdale7b9ca232024-05-23 18:19:46 +01001492 self.with_transaction(Immediate("TX_set_deleted_blob"), |tx| {
Janis Danisevskiseed69842021-02-18 20:04:10 -08001493 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001494 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001495 Self::UNASSIGNED_KEY_ID,
1496 SubComponentType::KEY_BLOB,
1497 Some(blob),
1498 Some(blob_metadata),
1499 )
1500 .need_gc()
1501 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001502 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001503 }
1504
Janis Danisevskis377d1002021-01-27 19:07:48 -08001505 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001506 tx: &Transaction,
1507 key_id: i64,
1508 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001509 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001510 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001511 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001512 match (blob, sc_type) {
1513 (Some(blob), _) => {
1514 tx.execute(
1515 "INSERT INTO persistent.blobentry
1516 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1517 params![sc_type, key_id, blob],
1518 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001519 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001520 if let Some(blob_metadata) = blob_metadata {
1521 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001522 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001523 row.get(0)
1524 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001525 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001526 blob_metadata
1527 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001528 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001529 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001530 }
1531 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1532 tx.execute(
1533 "DELETE FROM persistent.blobentry
1534 WHERE subcomponent_type = ? AND keyentryid = ?;",
1535 params![sc_type, key_id],
1536 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001537 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001538 }
1539 (None, _) => {
1540 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001541 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001542 }
1543 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001544 Ok(())
1545 }
1546
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001547 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1548 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001549 #[cfg(test)]
1550 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001551 self.with_transaction(Immediate("TX_insert_keyparameter"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001552 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001553 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001554 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001555 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001556
Janis Danisevskis66784c42021-01-27 08:40:25 -08001557 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001558 tx: &Transaction,
1559 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001560 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001561 ) -> Result<()> {
1562 let mut stmt = tx
1563 .prepare(
1564 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1565 VALUES (?, ?, ?, ?);",
1566 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001567 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001568
Janis Danisevskis66784c42021-01-27 08:40:25 -08001569 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001570 stmt.insert(params![
1571 key_id.0,
1572 p.get_tag().0,
1573 p.key_parameter_value(),
1574 p.security_level().0
1575 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001576 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001577 }
1578 Ok(())
1579 }
1580
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001581 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001582 #[cfg(test)]
1583 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
David Drysdale7b9ca232024-05-23 18:19:46 +01001584 self.with_transaction(Immediate("TX_insert_key_metadata"), |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001585 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001586 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001587 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001588 }
1589
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001590 /// Updates the alias column of the given key id `newid` with the given alias,
1591 /// and atomically, removes the alias, domain, and namespace from another row
1592 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001593 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1594 /// collector.
1595 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001596 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001597 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001598 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001599 domain: &Domain,
1600 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001601 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001602 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001603 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001604 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001605 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001606 return Err(KsError::sys())
1607 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001608 }
1609 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001610 let updated = tx
1611 .execute(
1612 "UPDATE persistent.keyentry
1613 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001614 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1615 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001616 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001617 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001618 let result = tx
1619 .execute(
1620 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001621 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001622 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001623 params![
1624 alias,
1625 KeyLifeCycle::Live,
1626 newid.0,
1627 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001628 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001629 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001630 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001631 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001632 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001633 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001634 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001635 return Err(KsError::sys()).context(ks_err!(
1636 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001637 result
1638 ));
1639 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001640 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001641 }
1642
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001643 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1644 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1645 pub fn migrate_key_namespace(
1646 &mut self,
1647 key_id_guard: KeyIdGuard,
1648 destination: &KeyDescriptor,
1649 caller_uid: u32,
1650 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1651 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01001652 let _wp = wd::watch("KeystoreDB::migrate_key_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001653
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001654 let destination = match destination.domain {
1655 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1656 Domain::SELINUX => (*destination).clone(),
1657 domain => {
1658 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1659 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1660 }
1661 };
1662
1663 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001664 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001665
1666 let alias = destination
1667 .alias
1668 .as_ref()
1669 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001670 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001671
David Drysdale7b9ca232024-05-23 18:19:46 +01001672 self.with_transaction(Immediate("TX_migrate_key_namespace"), |tx| {
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001673 // Query the destination location. If there is a key, the migration request fails.
1674 if tx
1675 .query_row(
1676 "SELECT id FROM persistent.keyentry
1677 WHERE alias = ? AND domain = ? AND namespace = ?;",
1678 params![alias, destination.domain.0, destination.nspace],
1679 |_| Ok(()),
1680 )
1681 .optional()
1682 .context("Failed to query destination.")?
1683 .is_some()
1684 {
1685 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1686 .context("Target already exists.");
1687 }
1688
1689 let updated = tx
1690 .execute(
1691 "UPDATE persistent.keyentry
1692 SET alias = ?, domain = ?, namespace = ?
1693 WHERE id = ?;",
1694 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1695 )
1696 .context("Failed to update key entry.")?;
1697
1698 if updated != 1 {
1699 return Err(KsError::sys())
1700 .context(format!("Update succeeded, but {} rows were updated.", updated));
1701 }
1702 Ok(()).no_gc()
1703 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001704 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001705 }
1706
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001707 /// Store a new key in a single transaction.
1708 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1709 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001710 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1711 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001712 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001713 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001714 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001715 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001716 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001717 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001718 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001719 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001720 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001721 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001722 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001723 let _wp = wd::watch("KeystoreDB::store_new_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001724
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001725 let (alias, domain, namespace) = match key {
1726 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1727 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1728 (alias, key.domain, nspace)
1729 }
1730 _ => {
1731 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001732 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 }
1734 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001735 self.with_transaction(Immediate("TX_store_new_key"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001736 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001737 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001738 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1739
1740 // In some occasions the key blob is already upgraded during the import.
1741 // In order to make sure it gets properly deleted it is inserted into the
1742 // database here and then immediately replaced by the superseding blob.
1743 // The garbage collector will then subject the blob to deleteKey of the
1744 // KM back end to permanently invalidate the key.
1745 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1746 Self::set_blob_internal(
1747 tx,
1748 key_id.id(),
1749 SubComponentType::KEY_BLOB,
1750 Some(blob),
1751 Some(blob_metadata),
1752 )
1753 .context("Trying to insert superseded key blob.")?;
1754 true
1755 } else {
1756 false
1757 };
1758
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001759 Self::set_blob_internal(
1760 tx,
1761 key_id.id(),
1762 SubComponentType::KEY_BLOB,
1763 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001764 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001765 )
1766 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001767 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001768 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001769 .context("Trying to insert the certificate.")?;
1770 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001771 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001772 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001773 tx,
1774 key_id.id(),
1775 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001776 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001777 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001778 )
1779 .context("Trying to insert the certificate chain.")?;
1780 }
1781 Self::insert_keyparameter_internal(tx, &key_id, params)
1782 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001783 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001784 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001785 .context("Trying to rebind alias.")?
1786 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001787 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001788 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001789 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001790 }
1791
Janis Danisevskis377d1002021-01-27 19:07:48 -08001792 /// Store a new certificate
1793 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1794 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001795 pub fn store_new_certificate(
1796 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001797 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001798 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001799 cert: &[u8],
1800 km_uuid: &Uuid,
1801 ) -> Result<KeyIdGuard> {
David Drysdale541846b2024-05-23 13:16:07 +01001802 let _wp = wd::watch("KeystoreDB::store_new_certificate");
Janis Danisevskis850d4862021-05-05 08:41:14 -07001803
Janis Danisevskis377d1002021-01-27 19:07:48 -08001804 let (alias, domain, namespace) = match key {
1805 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1806 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1807 (alias, key.domain, nspace)
1808 }
1809 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001810 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1811 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001812 }
1813 };
David Drysdale7b9ca232024-05-23 18:19:46 +01001814 self.with_transaction(Immediate("TX_store_new_certificate"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001815 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001816 .context("Trying to create new key entry.")?;
1817
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001818 Self::set_blob_internal(
1819 tx,
1820 key_id.id(),
1821 SubComponentType::CERT_CHAIN,
1822 Some(cert),
1823 None,
1824 )
1825 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001826
1827 let mut metadata = KeyMetaData::new();
1828 metadata.add(KeyMetaEntry::CreationDate(
1829 DateTime::now().context("Trying to make creation time.")?,
1830 ));
1831
1832 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1833
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001834 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001835 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001836 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001837 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001838 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001839 }
1840
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001841 // Helper function loading the key_id given the key descriptor
1842 // tuple comprising domain, namespace, and alias.
1843 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001844 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001845 let alias = key
1846 .alias
1847 .as_ref()
1848 .map_or_else(|| Err(KsError::sys()), Ok)
1849 .context("In load_key_entry_id: Alias must be specified.")?;
1850 let mut stmt = tx
1851 .prepare(
1852 "SELECT id FROM persistent.keyentry
1853 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001854 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001855 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001856 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001857 AND alias = ?
1858 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001859 )
1860 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1861 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001862 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001863 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001864 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001865 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001866 .get(0)
1867 .context("Failed to unpack id.")
1868 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001869 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001870 }
1871
1872 /// This helper function completes the access tuple of a key, which is required
1873 /// to perform access control. The strategy depends on the `domain` field in the
1874 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001875 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001876 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001877 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001878 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001879 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001880 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001881 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001882 /// `namespace`.
1883 /// In each case the information returned is sufficient to perform the access
1884 /// check and the key id can be used to load further key artifacts.
1885 fn load_access_tuple(
1886 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001887 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001888 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001889 caller_uid: u32,
1890 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1891 match key.domain {
1892 // Domain App or SELinux. In this case we load the key_id from
1893 // the keyentry database for further loading of key components.
1894 // We already have the full access tuple to perform access control.
1895 // The only distinction is that we use the caller_uid instead
1896 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001897 // Domain::APP.
1898 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001899 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001900 if access_key.domain == Domain::APP {
1901 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001902 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001903 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001904 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001905
1906 Ok((key_id, access_key, None))
1907 }
1908
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001909 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001910 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001911 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001912 let mut stmt = tx
1913 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001914 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001915 WHERE grantee = ? AND id = ? AND
1916 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001917 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001918 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001919 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00001920 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001921 .context("Domain:Grant: query failed.")?;
1922 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001923 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001924 let r =
1925 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001926 Ok((
1927 r.get(0).context("Failed to unpack key_id.")?,
1928 r.get(1).context("Failed to unpack access_vector.")?,
1929 ))
1930 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001931 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001932 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001933 }
1934
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001935 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001936 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001937 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08001938 let (domain, namespace): (Domain, i64) = {
1939 let mut stmt = tx
1940 .prepare(
1941 "SELECT domain, namespace FROM persistent.keyentry
1942 WHERE
1943 id = ?
1944 AND state = ?;",
1945 )
1946 .context("Domain::KEY_ID: prepare statement failed")?;
1947 let mut rows = stmt
1948 .query(params![key.nspace, KeyLifeCycle::Live])
1949 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001950 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001951 let r =
1952 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001953 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001954 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001955 r.get(1).context("Failed to unpack namespace.")?,
1956 ))
1957 })
Janis Danisevskis45760022021-01-19 16:34:10 -08001958 .context("Domain::KEY_ID.")?
1959 };
1960
1961 // We may use a key by id after loading it by grant.
1962 // In this case we have to check if the caller has a grant for this particular
1963 // key. We can skip this if we already know that the caller is the owner.
1964 // But we cannot know this if domain is anything but App. E.g. in the case
1965 // of Domain::SELINUX we have to speculatively check for grants because we have to
1966 // consult the SEPolicy before we know if the caller is the owner.
1967 let access_vector: Option<KeyPermSet> =
1968 if domain != Domain::APP || namespace != caller_uid as i64 {
1969 let access_vector: Option<i32> = tx
1970 .query_row(
1971 "SELECT access_vector FROM persistent.grant
1972 WHERE grantee = ? AND keyentryid = ?;",
1973 params![caller_uid as i64, key.nspace],
1974 |row| row.get(0),
1975 )
1976 .optional()
1977 .context("Domain::KEY_ID: query grant failed.")?;
1978 access_vector.map(|p| p.into())
1979 } else {
1980 None
1981 };
1982
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001983 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001984 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001985 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001986 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001987
Janis Danisevskis45760022021-01-19 16:34:10 -08001988 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001989 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00001990 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001991 }
1992 }
1993
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001994 fn load_blob_components(
1995 key_id: i64,
1996 load_bits: KeyEntryLoadBits,
1997 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001998 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001999 let mut stmt = tx
2000 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002001 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002002 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2003 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002004 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002005
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002006 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002007
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002008 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002009 let mut cert_blob: Option<Vec<u8>> = None;
2010 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002011 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002012 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002013 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002014 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002015 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002016 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2017 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002018 key_blob = Some((
2019 row.get(0).context("Failed to extract key blob id.")?,
2020 row.get(2).context("Failed to extract key blob.")?,
2021 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002022 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002023 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002024 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002025 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002026 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002027 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002028 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002029 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002030 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002031 (SubComponentType::CERT, _, _)
2032 | (SubComponentType::CERT_CHAIN, _, _)
2033 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002034 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2035 }
2036 Ok(())
2037 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002038 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002039
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002040 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2041 Ok(Some((
2042 blob,
2043 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002044 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002045 )))
2046 })?;
2047
2048 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002049 }
2050
2051 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2052 let mut stmt = tx
2053 .prepare(
2054 "SELECT tag, data, security_level from persistent.keyparameter
2055 WHERE keyentryid = ?;",
2056 )
2057 .context("In load_key_parameters: prepare statement failed.")?;
2058
2059 let mut parameters: Vec<KeyParameter> = Vec::new();
2060
2061 let mut rows =
2062 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002063 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002064 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2065 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002066 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002067 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002068 .context("Failed to read KeyParameter.")?,
2069 );
2070 Ok(())
2071 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002072 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002073
2074 Ok(parameters)
2075 }
2076
Qi Wub9433b52020-12-01 14:52:46 +08002077 /// Decrements the usage count of a limited use key. This function first checks whether the
2078 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2079 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2080 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002081 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002082 let _wp = wd::watch("KeystoreDB::check_and_update_key_usage_count");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002083
David Drysdale7b9ca232024-05-23 18:19:46 +01002084 self.with_transaction(Immediate("TX_check_and_update_key_usage_count"), |tx| {
Qi Wub9433b52020-12-01 14:52:46 +08002085 let limit: Option<i32> = tx
2086 .query_row(
2087 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2088 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2089 |row| row.get(0),
2090 )
2091 .optional()
2092 .context("Trying to load usage count")?;
2093
2094 let limit = limit
2095 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2096 .context("The Key no longer exists. Key is exhausted.")?;
2097
2098 tx.execute(
2099 "UPDATE persistent.keyparameter
2100 SET data = data - 1
2101 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2102 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2103 )
2104 .context("Failed to update key usage count.")?;
2105
2106 match limit {
2107 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002108 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002109 .context("Trying to mark limited use key for deletion."),
2110 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002111 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002112 }
2113 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002114 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002115 }
2116
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002117 /// Load a key entry by the given key descriptor.
2118 /// It uses the `check_permission` callback to verify if the access is allowed
2119 /// given the key access tuple read from the database using `load_access_tuple`.
2120 /// With `load_bits` the caller may specify which blobs shall be loaded from
2121 /// the blob database.
2122 pub fn load_key_entry(
2123 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002124 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002125 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002126 load_bits: KeyEntryLoadBits,
2127 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002128 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2129 ) -> Result<(KeyIdGuard, KeyEntry)> {
David Drysdale541846b2024-05-23 13:16:07 +01002130 let _wp = wd::watch("KeystoreDB::load_key_entry");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002131
Janis Danisevskis66784c42021-01-27 08:40:25 -08002132 loop {
2133 match self.load_key_entry_internal(
2134 key,
2135 key_type,
2136 load_bits,
2137 caller_uid,
2138 &check_permission,
2139 ) {
2140 Ok(result) => break Ok(result),
2141 Err(e) => {
2142 if Self::is_locked_error(&e) {
David Drysdale115c4722024-04-15 14:11:52 +01002143 std::thread::sleep(DB_BUSY_RETRY_INTERVAL);
Janis Danisevskis66784c42021-01-27 08:40:25 -08002144 continue;
2145 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002146 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002147 }
2148 }
2149 }
2150 }
2151 }
2152
2153 fn load_key_entry_internal(
2154 &mut self,
2155 key: &KeyDescriptor,
2156 key_type: KeyType,
2157 load_bits: KeyEntryLoadBits,
2158 caller_uid: u32,
2159 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002160 ) -> Result<(KeyIdGuard, KeyEntry)> {
2161 // KEY ID LOCK 1/2
2162 // If we got a key descriptor with a key id we can get the lock right away.
2163 // Otherwise we have to defer it until we know the key id.
2164 let key_id_guard = match key.domain {
2165 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2166 _ => None,
2167 };
2168
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002169 let tx = self
2170 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002171 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002172 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002173
2174 // Load the key_id and complete the access control tuple.
2175 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002176 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002177
2178 // Perform access control. It is vital that we return here if the permission is denied.
2179 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002180 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002181
Janis Danisevskisaec14592020-11-12 09:41:49 -08002182 // KEY ID LOCK 2/2
2183 // If we did not get a key id lock by now, it was because we got a key descriptor
2184 // without a key id. At this point we got the key id, so we can try and get a lock.
2185 // However, we cannot block here, because we are in the middle of the transaction.
2186 // So first we try to get the lock non blocking. If that fails, we roll back the
2187 // transaction and block until we get the lock. After we successfully got the lock,
2188 // we start a new transaction and load the access tuple again.
2189 //
2190 // We don't need to perform access control again, because we already established
2191 // that the caller had access to the given key. But we need to make sure that the
2192 // key id still exists. So we have to load the key entry by key id this time.
2193 let (key_id_guard, tx) = match key_id_guard {
2194 None => match KEY_ID_LOCK.try_get(key_id) {
2195 None => {
2196 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002197 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002198
Janis Danisevskisaec14592020-11-12 09:41:49 -08002199 // Block until we have a key id lock.
2200 let key_id_guard = KEY_ID_LOCK.get(key_id);
2201
2202 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002203 let tx = self
2204 .conn
2205 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002206 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002207
2208 Self::load_access_tuple(
2209 &tx,
2210 // This time we have to load the key by the retrieved key id, because the
2211 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002212 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002213 domain: Domain::KEY_ID,
2214 nspace: key_id,
2215 ..Default::default()
2216 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002217 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002218 caller_uid,
2219 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002220 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002221 (key_id_guard, tx)
2222 }
2223 Some(l) => (l, tx),
2224 },
2225 Some(key_id_guard) => (key_id_guard, tx),
2226 };
2227
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002228 let key_entry =
2229 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002230
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002231 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002232
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002233 Ok((key_id_guard, key_entry))
2234 }
2235
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002236 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002237 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002238 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2239 .context("Trying to delete keyentry.")?;
2240 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2241 .context("Trying to delete keymetadata.")?;
2242 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2243 .context("Trying to delete keyparameters.")?;
2244 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2245 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002246 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002247 }
2248
2249 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002250 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002251 pub fn unbind_key(
2252 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002253 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002254 key_type: KeyType,
2255 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002256 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002257 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002258 let _wp = wd::watch("KeystoreDB::unbind_key");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002259
David Drysdale7b9ca232024-05-23 18:19:46 +01002260 self.with_transaction(Immediate("TX_unbind_key"), |tx| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002261 let (key_id, access_key_descriptor, access_vector) =
2262 Self::load_access_tuple(tx, key, key_type, caller_uid)
2263 .context("Trying to get access tuple.")?;
2264
2265 // Perform access control. It is vital that we return here if the permission is denied.
2266 // So do not touch that '?' at the end.
2267 check_permission(&access_key_descriptor, access_vector)
2268 .context("While checking permission.")?;
2269
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002270 Self::mark_unreferenced(tx, key_id)
2271 .map(|need_gc| (need_gc, ()))
2272 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002274 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002275 }
2276
Max Bires8e93d2b2021-01-14 13:17:59 -08002277 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2278 tx.query_row(
2279 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2280 params![key_id],
2281 |row| row.get(0),
2282 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002283 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002284 }
2285
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002286 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2287 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2288 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002289 let _wp = wd::watch("KeystoreDB::unbind_keys_for_namespace");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002290
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002291 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002292 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002293 }
David Drysdale7b9ca232024-05-23 18:19:46 +01002294 self.with_transaction(Immediate("TX_unbind_keys_for_namespace"), |tx| {
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002295 tx.execute(
2296 "DELETE FROM persistent.keymetadata
2297 WHERE keyentryid IN (
2298 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002299 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002300 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002301 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002302 )
2303 .context("Trying to delete keymetadata.")?;
2304 tx.execute(
2305 "DELETE FROM persistent.keyparameter
2306 WHERE keyentryid IN (
2307 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002308 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002309 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002310 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002311 )
2312 .context("Trying to delete keyparameters.")?;
2313 tx.execute(
2314 "DELETE FROM persistent.grant
2315 WHERE keyentryid IN (
2316 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002317 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002318 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002319 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002320 )
2321 .context("Trying to delete grants.")?;
2322 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002323 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002324 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2325 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002326 )
2327 .context("Trying to delete keyentry.")?;
2328 Ok(()).need_gc()
2329 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002330 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002331 }
2332
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002333 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002334 let _wp = wd::watch("KeystoreDB::cleanup_unreferenced");
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002335 {
2336 tx.execute(
2337 "DELETE FROM persistent.keymetadata
2338 WHERE keyentryid IN (
2339 SELECT id FROM persistent.keyentry
2340 WHERE state = ?
2341 );",
2342 params![KeyLifeCycle::Unreferenced],
2343 )
2344 .context("Trying to delete keymetadata.")?;
2345 tx.execute(
2346 "DELETE FROM persistent.keyparameter
2347 WHERE keyentryid IN (
2348 SELECT id FROM persistent.keyentry
2349 WHERE state = ?
2350 );",
2351 params![KeyLifeCycle::Unreferenced],
2352 )
2353 .context("Trying to delete keyparameters.")?;
2354 tx.execute(
2355 "DELETE FROM persistent.grant
2356 WHERE keyentryid IN (
2357 SELECT id FROM persistent.keyentry
2358 WHERE state = ?
2359 );",
2360 params![KeyLifeCycle::Unreferenced],
2361 )
2362 .context("Trying to delete grants.")?;
2363 tx.execute(
2364 "DELETE FROM persistent.keyentry
2365 WHERE state = ?;",
2366 params![KeyLifeCycle::Unreferenced],
2367 )
2368 .context("Trying to delete keyentry.")?;
2369 Result::<()>::Ok(())
2370 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002371 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002372 }
2373
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00002374 /// Deletes all keys for the given user, including both client keys and super keys.
2375 pub fn unbind_keys_for_user(&mut self, user_id: u32) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002376 let _wp = wd::watch("KeystoreDB::unbind_keys_for_user");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002377
David Drysdale7b9ca232024-05-23 18:19:46 +01002378 self.with_transaction(Immediate("TX_unbind_keys_for_user"), |tx| {
Hasini Gunasingheda895552021-01-27 19:34:37 +00002379 let mut stmt = tx
2380 .prepare(&format!(
2381 "SELECT id from persistent.keyentry
2382 WHERE (
2383 key_type = ?
2384 AND domain = ?
2385 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2386 AND state = ?
2387 ) OR (
2388 key_type = ?
2389 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002390 AND state = ?
2391 );",
2392 aid_user_offset = AID_USER_OFFSET
2393 ))
2394 .context(concat!(
2395 "In unbind_keys_for_user. ",
2396 "Failed to prepare the query to find the keys created by apps."
2397 ))?;
2398
2399 let mut rows = stmt
2400 .query(params![
2401 // WHERE client key:
2402 KeyType::Client,
2403 Domain::APP.0 as u32,
2404 user_id,
2405 KeyLifeCycle::Live,
2406 // OR super key:
2407 KeyType::Super,
2408 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002409 KeyLifeCycle::Live
2410 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002411 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002412
2413 let mut key_ids: Vec<i64> = Vec::new();
2414 db_utils::with_rows_extract_all(&mut rows, |row| {
2415 key_ids
2416 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2417 Ok(())
2418 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002419 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002420
2421 let mut notify_gc = false;
2422 for key_id in key_ids {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002423 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002424 .context("In unbind_keys_for_user.")?
2425 || notify_gc;
2426 }
2427 Ok(()).do_gc(notify_gc)
2428 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002429 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002430 }
2431
Eric Biggersb0478cf2023-10-27 03:55:29 +00002432 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2433 /// This runs when the user's lock screen is being changed to Swipe or None.
2434 ///
2435 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2436 /// such keys also require user authentication. Keystore's concept of user authentication is
2437 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2438 /// authentication is no longer possible. In contrast, keys that just require that the device
2439 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2440 /// is always considered "unlocked" in that case.
2441 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002442 let _wp = wd::watch("KeystoreDB::unbind_auth_bound_keys_for_user");
Eric Biggersb0478cf2023-10-27 03:55:29 +00002443
David Drysdale7b9ca232024-05-23 18:19:46 +01002444 self.with_transaction(Immediate("TX_unbind_auth_bound_keys_for_user"), |tx| {
Eric Biggersb0478cf2023-10-27 03:55:29 +00002445 let mut stmt = tx
2446 .prepare(&format!(
2447 "SELECT id from persistent.keyentry
2448 WHERE key_type = ?
2449 AND domain = ?
2450 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2451 AND state = ?;",
2452 aid_user_offset = AID_USER_OFFSET
2453 ))
2454 .context(concat!(
2455 "In unbind_auth_bound_keys_for_user. ",
2456 "Failed to prepare the query to find the keys created by apps."
2457 ))?;
2458
2459 let mut rows = stmt
2460 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2461 .context(ks_err!("Failed to query the keys created by apps."))?;
2462
2463 let mut key_ids: Vec<i64> = Vec::new();
2464 db_utils::with_rows_extract_all(&mut rows, |row| {
2465 key_ids
2466 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2467 Ok(())
2468 })
2469 .context(ks_err!())?;
2470
2471 let mut notify_gc = false;
2472 let mut num_unbound = 0;
2473 for key_id in key_ids {
2474 // Load the key parameters and filter out non-auth-bound keys. To identify
2475 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2476 // could also be used, but UserSecureID is what Keystore treats as authoritative
2477 // when actually enforcing the key parameters (it might not matter, though).
2478 let params = Self::load_key_parameters(key_id, tx)
2479 .context("Failed to load key parameters.")?;
2480 let is_auth_bound_key = params.iter().any(|kp| {
2481 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2482 });
2483 if is_auth_bound_key {
2484 notify_gc = Self::mark_unreferenced(tx, key_id)
2485 .context("In unbind_auth_bound_keys_for_user.")?
2486 || notify_gc;
2487 num_unbound += 1;
2488 }
2489 }
2490 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2491 Ok(()).do_gc(notify_gc)
2492 })
2493 .context(ks_err!())
2494 }
2495
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002496 fn load_key_components(
2497 tx: &Transaction,
2498 load_bits: KeyEntryLoadBits,
2499 key_id: i64,
2500 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002501 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002502
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002503 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002504 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002505
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002506 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002507 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002508
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002509 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002510 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002511
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002512 Ok(KeyEntry {
2513 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002514 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002515 cert: cert_blob,
2516 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002517 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002518 parameters,
2519 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002520 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002521 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002522 }
2523
Eran Messeri24f31972023-01-25 17:00:33 +00002524 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2525 /// aliases are greater than the specified 'start_past_alias'. If no value
2526 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002527 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002528 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002529 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002530 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002531 &mut self,
2532 domain: Domain,
2533 namespace: i64,
2534 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002535 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002536 ) -> Result<Vec<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002537 let _wp = wd::watch("KeystoreDB::list_past_alias");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002538
Eran Messeri24f31972023-01-25 17:00:33 +00002539 let query = format!(
2540 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002541 WHERE domain = ?
2542 AND namespace = ?
2543 AND alias IS NOT NULL
2544 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002545 AND key_type = ?
2546 {}
2547 ORDER BY alias ASC;",
2548 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2549 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002550
Eran Messeri24f31972023-01-25 17:00:33 +00002551 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2552 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2553
2554 let mut rows = match start_past_alias {
2555 Some(past_alias) => stmt
2556 .query(params![
2557 domain.0 as u32,
2558 namespace,
2559 KeyLifeCycle::Live,
2560 key_type,
2561 past_alias
2562 ])
2563 .context(ks_err!("Failed to query."))?,
2564 None => stmt
2565 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2566 .context(ks_err!("Failed to query."))?,
2567 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002568
Janis Danisevskis66784c42021-01-27 08:40:25 -08002569 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2570 db_utils::with_rows_extract_all(&mut rows, |row| {
2571 descriptors.push(KeyDescriptor {
2572 domain,
2573 nspace: namespace,
2574 alias: Some(row.get(0).context("Trying to extract alias.")?),
2575 blob: None,
2576 });
2577 Ok(())
2578 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002579 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002580 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002581 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002582 }
2583
Eran Messeri24f31972023-01-25 17:00:33 +00002584 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2585 /// Domain must be APP or SELINUX, the caller must make sure of that.
2586 pub fn count_keys(
2587 &mut self,
2588 domain: Domain,
2589 namespace: i64,
2590 key_type: KeyType,
2591 ) -> Result<usize> {
David Drysdale541846b2024-05-23 13:16:07 +01002592 let _wp = wd::watch("KeystoreDB::countKeys");
Eran Messeri24f31972023-01-25 17:00:33 +00002593
2594 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2595 tx.query_row(
2596 "SELECT COUNT(alias) FROM persistent.keyentry
2597 WHERE domain = ?
2598 AND namespace = ?
2599 AND alias IS NOT NULL
2600 AND state = ?
2601 AND key_type = ?;",
2602 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2603 |row| row.get(0),
2604 )
2605 .context(ks_err!("Failed to count number of keys."))
2606 .no_gc()
2607 })?;
2608 Ok(num_keys)
2609 }
2610
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002611 /// Adds a grant to the grant table.
2612 /// Like `load_key_entry` this function loads the access tuple before
2613 /// it uses the callback for a permission check. Upon success,
2614 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2615 /// grant table. The new row will have a randomized id, which is used as
2616 /// grant id in the namespace field of the resulting KeyDescriptor.
2617 pub fn grant(
2618 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002619 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002620 caller_uid: u32,
2621 grantee_uid: u32,
2622 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002623 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002624 ) -> Result<KeyDescriptor> {
David Drysdale541846b2024-05-23 13:16:07 +01002625 let _wp = wd::watch("KeystoreDB::grant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002626
David Drysdale7b9ca232024-05-23 18:19:46 +01002627 self.with_transaction(Immediate("TX_grant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002628 // Load the key_id and complete the access control tuple.
2629 // We ignore the access vector here because grants cannot be granted.
2630 // The access vector returned here expresses the permissions the
2631 // grantee has if key.domain == Domain::GRANT. But this vector
2632 // cannot include the grant permission by design, so there is no way the
2633 // subsequent permission check can pass.
2634 // We could check key.domain == Domain::GRANT and fail early.
2635 // But even if we load the access tuple by grant here, the permission
2636 // check denies the attempt to create a grant by grant descriptor.
2637 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002638 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002639
Janis Danisevskis66784c42021-01-27 08:40:25 -08002640 // Perform access control. It is vital that we return here if the permission
2641 // was denied. So do not touch that '?' at the end of the line.
2642 // This permission check checks if the caller has the grant permission
2643 // for the given key and in addition to all of the permissions
2644 // expressed in `access_vector`.
2645 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002646 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002647
Janis Danisevskis66784c42021-01-27 08:40:25 -08002648 let grant_id = if let Some(grant_id) = tx
2649 .query_row(
2650 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002651 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002652 params![key_id, grantee_uid],
2653 |row| row.get(0),
2654 )
2655 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002656 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002657 {
2658 tx.execute(
2659 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002660 SET access_vector = ?
2661 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002662 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002663 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002664 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002665 grant_id
2666 } else {
2667 Self::insert_with_retry(|id| {
2668 tx.execute(
2669 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2670 VALUES (?, ?, ?, ?);",
2671 params![id, grantee_uid, key_id, i32::from(access_vector)],
2672 )
2673 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002674 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002675 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002676
Janis Danisevskis66784c42021-01-27 08:40:25 -08002677 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002678 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002679 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002680 }
2681
2682 /// This function checks permissions like `grant` and `load_key_entry`
2683 /// before removing a grant from the grant table.
2684 pub fn ungrant(
2685 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002686 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002687 caller_uid: u32,
2688 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002689 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002690 ) -> Result<()> {
David Drysdale541846b2024-05-23 13:16:07 +01002691 let _wp = wd::watch("KeystoreDB::ungrant");
Janis Danisevskis850d4862021-05-05 08:41:14 -07002692
David Drysdale7b9ca232024-05-23 18:19:46 +01002693 self.with_transaction(Immediate("TX_ungrant"), |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002694 // Load the key_id and complete the access control tuple.
2695 // We ignore the access vector here because grants cannot be granted.
2696 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002697 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002698
Janis Danisevskis66784c42021-01-27 08:40:25 -08002699 // Perform access control. We must return here if the permission
2700 // was denied. So do not touch the '?' at the end of this line.
2701 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002702 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002703
Janis Danisevskis66784c42021-01-27 08:40:25 -08002704 tx.execute(
2705 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002706 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002707 params![key_id, grantee_uid],
2708 )
2709 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002710
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002711 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002712 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002713 }
2714
Joel Galenson845f74b2020-09-09 14:11:55 -07002715 // Generates a random id and passes it to the given function, which will
2716 // try to insert it into a database. If that insertion fails, retry;
2717 // otherwise return the id.
2718 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2719 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002720 let newid: i64 = match random() {
2721 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2722 i => i,
2723 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002724 match inserter(newid) {
2725 // If the id already existed, try again.
2726 Err(rusqlite::Error::SqliteFailure(
2727 libsqlite3_sys::Error {
2728 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2729 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2730 },
2731 _,
2732 )) => (),
2733 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002734 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002735 }
2736 _ => return Ok(newid),
2737 }
2738 }
2739 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002740
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002741 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2742 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
Eric Biggers19b3b0d2024-01-31 22:46:47 +00002743 self.perboot
2744 .insert_auth_token_entry(AuthTokenEntry::new(auth_token.clone(), BootTime::now()))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002745 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002746
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002747 /// Find the newest auth token matching the given predicate.
Eric Biggersb5613da2024-03-13 19:31:42 +00002748 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<AuthTokenEntry>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002749 where
2750 F: Fn(&AuthTokenEntry) -> bool,
2751 {
Eric Biggersb5613da2024-03-13 19:31:42 +00002752 self.perboot.find_auth_token_entry(p)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002753 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002754
2755 /// Load descriptor of a key by key id
2756 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
David Drysdale541846b2024-05-23 13:16:07 +01002757 let _wp = wd::watch("KeystoreDB::load_key_descriptor");
Pavel Grafovf45034a2021-05-12 22:35:45 +01002758
2759 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2760 tx.query_row(
2761 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2762 params![key_id],
2763 |row| {
2764 Ok(KeyDescriptor {
2765 domain: Domain(row.get(0)?),
2766 nspace: row.get(1)?,
2767 alias: row.get(2)?,
2768 blob: None,
2769 })
2770 },
2771 )
2772 .optional()
2773 .context("Trying to load key descriptor")
2774 .no_gc()
2775 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002776 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002777 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00002778
2779 /// Returns a list of app UIDs that have keys authenticated by the given secure_user_id
2780 /// (for the given user_id).
2781 /// This is helpful for finding out which apps will have their keys invalidated when
2782 /// the user changes biometrics enrollment or removes their LSKF.
2783 pub fn get_app_uids_affected_by_sid(
2784 &mut self,
2785 user_id: i32,
2786 secure_user_id: i64,
2787 ) -> Result<Vec<i64>> {
David Drysdale541846b2024-05-23 13:16:07 +01002788 let _wp = wd::watch("KeystoreDB::get_app_uids_affected_by_sid");
Eran Messeri4dc27b52024-01-09 12:43:31 +00002789
David Drysdale7b9ca232024-05-23 18:19:46 +01002790 let ids = self.with_transaction(Immediate("TX_get_app_uids_affected_by_sid"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002791 let mut stmt = tx
2792 .prepare(&format!(
2793 "SELECT id, namespace from persistent.keyentry
2794 WHERE key_type = ?
2795 AND domain = ?
2796 AND cast ( (namespace/{AID_USER_OFFSET}) as int) = ?
2797 AND state = ?;",
2798 ))
2799 .context(concat!(
2800 "In get_app_uids_affected_by_sid, ",
2801 "failed to prepare the query to find the keys created by apps."
2802 ))?;
2803
2804 let mut rows = stmt
2805 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2806 .context(ks_err!("Failed to query the keys created by apps."))?;
2807
2808 let mut key_ids_and_app_uids: HashMap<i64, i64> = Default::default();
2809 db_utils::with_rows_extract_all(&mut rows, |row| {
2810 key_ids_and_app_uids.insert(
2811 row.get(0).context("Failed to read key id of a key created by an app.")?,
2812 row.get(1).context("Failed to read the app uid")?,
2813 );
2814 Ok(())
2815 })?;
2816 Ok(key_ids_and_app_uids).no_gc()
2817 })?;
2818 let mut app_uids_affected_by_sid: HashSet<i64> = Default::default();
David Drysdale7b9ca232024-05-23 18:19:46 +01002819 for (key_id, app_uid) in ids {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002820 // Read the key parameters for each key in its own transaction. It is OK to ignore
2821 // an error to get the properties of a particular key since it might have been deleted
2822 // under our feet after the previous transaction concluded. If the key was deleted
2823 // then it is no longer applicable if it was auth-bound or not.
2824 if let Ok(is_key_bound_to_sid) =
David Drysdale7b9ca232024-05-23 18:19:46 +01002825 self.with_transaction(Immediate("TX_get_app_uids_affects_by_sid 2"), |tx| {
Eran Messeri4dc27b52024-01-09 12:43:31 +00002826 let params = Self::load_key_parameters(key_id, tx)
2827 .context("Failed to load key parameters.")?;
2828 // Check if the key is bound to this secure user ID.
2829 let is_key_bound_to_sid = params.iter().any(|kp| {
2830 matches!(
2831 kp.key_parameter_value(),
2832 KeyParameterValue::UserSecureID(sid) if *sid == secure_user_id
2833 )
2834 });
2835 Ok(is_key_bound_to_sid).no_gc()
2836 })
2837 {
2838 if is_key_bound_to_sid {
2839 app_uids_affected_by_sid.insert(app_uid);
2840 }
2841 }
2842 }
2843
2844 let app_uids_vec: Vec<i64> = app_uids_affected_by_sid.into_iter().collect();
2845 Ok(app_uids_vec)
2846 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002847}
2848
2849#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002850pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002851
2852 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002853 use crate::key_parameter::{
2854 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2855 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2856 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002857 use crate::key_perm_set;
2858 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002859 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002860 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002861 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2862 HardwareAuthToken::HardwareAuthToken,
2863 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002864 };
2865 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002866 Timestamp::Timestamp,
2867 };
Joel Galenson0891bc12020-07-20 10:37:03 -07002868 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002869 use std::collections::BTreeMap;
2870 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002871 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002872 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002873 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002874 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002875 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002876 #[cfg(disabled)]
2877 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002878
Seth Moore7ee79f92021-12-07 11:42:49 -08002879 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002880 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002881
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002882 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
David Drysdale7b9ca232024-05-23 18:19:46 +01002883 db.with_transaction(Immediate("TX_new_test_db"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002884 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002885 })?;
2886 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002887 }
2888
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002889 fn rebind_alias(
2890 db: &mut KeystoreDB,
2891 newid: &KeyIdGuard,
2892 alias: &str,
2893 domain: Domain,
2894 namespace: i64,
2895 ) -> Result<bool> {
David Drysdale7b9ca232024-05-23 18:19:46 +01002896 db.with_transaction(Immediate("TX_rebind_alias"), |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002897 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002898 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002899 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002900 }
2901
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002902 #[test]
2903 fn datetime() -> Result<()> {
2904 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002905 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002906 let now = SystemTime::now();
2907 let duration = Duration::from_secs(1000);
2908 let then = now.checked_sub(duration).unwrap();
2909 let soon = now.checked_add(duration).unwrap();
2910 conn.execute(
2911 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2912 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2913 )?;
2914 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002915 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002916 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2917 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2918 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2919 assert!(rows.next()?.is_none());
2920 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2921 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2922 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2923 Ok(())
2924 }
2925
Joel Galenson0891bc12020-07-20 10:37:03 -07002926 // Ensure that we're using the "injected" random function, not the real one.
2927 #[test]
2928 fn test_mocked_random() {
2929 let rand1 = random();
2930 let rand2 = random();
2931 let rand3 = random();
2932 if rand1 == rand2 {
2933 assert_eq!(rand2 + 1, rand3);
2934 } else {
2935 assert_eq!(rand1 + 1, rand2);
2936 assert_eq!(rand2, rand3);
2937 }
2938 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002939
Joel Galenson26f4d012020-07-17 14:57:21 -07002940 // Test that we have the correct tables.
2941 #[test]
2942 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002943 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002944 let tables = db
2945 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002946 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002947 .query_map(params![], |row| row.get(0))?
2948 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002949 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002950 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002951 assert_eq!(tables[1], "blobmetadata");
2952 assert_eq!(tables[2], "grant");
2953 assert_eq!(tables[3], "keyentry");
2954 assert_eq!(tables[4], "keymetadata");
2955 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07002956 Ok(())
2957 }
2958
2959 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002960 fn test_auth_token_table_invariant() -> Result<()> {
2961 let mut db = new_test_db()?;
2962 let auth_token1 = HardwareAuthToken {
2963 challenge: i64::MAX,
2964 userId: 200,
2965 authenticatorId: 200,
2966 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2967 timestamp: Timestamp { milliSeconds: 500 },
2968 mac: String::from("mac").into_bytes(),
2969 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002970 db.insert_auth_token(&auth_token1);
2971 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002972 assert_eq!(auth_tokens_returned.len(), 1);
2973
2974 // insert another auth token with the same values for the columns in the UNIQUE constraint
2975 // of the auth token table and different value for timestamp
2976 let auth_token2 = HardwareAuthToken {
2977 challenge: i64::MAX,
2978 userId: 200,
2979 authenticatorId: 200,
2980 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2981 timestamp: Timestamp { milliSeconds: 600 },
2982 mac: String::from("mac").into_bytes(),
2983 };
2984
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002985 db.insert_auth_token(&auth_token2);
2986 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002987 assert_eq!(auth_tokens_returned.len(), 1);
2988
2989 if let Some(auth_token) = auth_tokens_returned.pop() {
2990 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
2991 }
2992
2993 // insert another auth token with the different values for the columns in the UNIQUE
2994 // constraint of the auth token table
2995 let auth_token3 = HardwareAuthToken {
2996 challenge: i64::MAX,
2997 userId: 201,
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_token3);
3005 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003006 assert_eq!(auth_tokens_returned.len(), 2);
3007
3008 Ok(())
3009 }
3010
3011 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003012 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3013 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003014 }
3015
David Drysdale8c4c4f32023-10-31 12:14:11 +00003016 fn create_key_entry(
3017 db: &mut KeystoreDB,
3018 domain: &Domain,
3019 namespace: &i64,
3020 key_type: KeyType,
3021 km_uuid: &Uuid,
3022 ) -> Result<KeyIdGuard> {
David Drysdale7b9ca232024-05-23 18:19:46 +01003023 db.with_transaction(Immediate("TX_create_key_entry"), |tx| {
David Drysdale8c4c4f32023-10-31 12:14:11 +00003024 KeystoreDB::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
3025 })
3026 }
3027
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003028 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003029 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003030 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003031 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003032
David Drysdale8c4c4f32023-10-31 12:14:11 +00003033 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003034 let entries = get_keyentry(&db)?;
3035 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003036
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003037 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003038
3039 let entries_new = get_keyentry(&db)?;
3040 assert_eq!(entries, entries_new);
3041 Ok(())
3042 }
3043
3044 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003045 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003046 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3047 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003048 }
3049
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003050 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003051
David Drysdale8c4c4f32023-10-31 12:14:11 +00003052 create_key_entry(&mut db, &Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3053 create_key_entry(&mut db, &Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003054
3055 let entries = get_keyentry(&db)?;
3056 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003057 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3058 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003059
3060 // Test that we must pass in a valid Domain.
3061 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003062 create_key_entry(&mut db, &Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003063 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003064 );
3065 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003066 create_key_entry(&mut db, &Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003067 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003068 );
3069 check_result_is_error_containing_string(
David Drysdale8c4c4f32023-10-31 12:14:11 +00003070 create_key_entry(&mut db, &Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003071 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003072 );
3073
3074 Ok(())
3075 }
3076
Joel Galenson33c04ad2020-08-03 11:04:38 -07003077 #[test]
3078 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003079 fn extractor(
3080 ke: &KeyEntryRow,
3081 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3082 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003083 }
3084
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003085 let mut db = new_test_db()?;
David Drysdale8c4c4f32023-10-31 12:14:11 +00003086 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3087 create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003088 let entries = get_keyentry(&db)?;
3089 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003090 assert_eq!(
3091 extractor(&entries[0]),
3092 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3093 );
3094 assert_eq!(
3095 extractor(&entries[1]),
3096 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3097 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003098
3099 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003100 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003101 let entries = get_keyentry(&db)?;
3102 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003103 assert_eq!(
3104 extractor(&entries[0]),
3105 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3106 );
3107 assert_eq!(
3108 extractor(&entries[1]),
3109 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3110 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003111
3112 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003113 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003114 let entries = get_keyentry(&db)?;
3115 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003116 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3117 assert_eq!(
3118 extractor(&entries[1]),
3119 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3120 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003121
3122 // Test that we must pass in a valid Domain.
3123 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003124 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003125 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003126 );
3127 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003128 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003129 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003130 );
3131 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003132 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003133 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003134 );
3135
3136 // Test that we correctly handle setting an alias for something that does not exist.
3137 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003138 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003139 "Expected to update a single entry but instead updated 0",
3140 );
3141 // Test that we correctly abort the transaction in this case.
3142 let entries = get_keyentry(&db)?;
3143 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003144 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3145 assert_eq!(
3146 extractor(&entries[1]),
3147 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3148 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003149
3150 Ok(())
3151 }
3152
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003153 #[test]
3154 fn test_grant_ungrant() -> Result<()> {
3155 const CALLER_UID: u32 = 15;
3156 const GRANTEE_UID: u32 = 12;
3157 const SELINUX_NAMESPACE: i64 = 7;
3158
3159 let mut db = new_test_db()?;
3160 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003161 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3162 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3163 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003164 )?;
3165 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003166 domain: super::Domain::APP,
3167 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003168 alias: Some("key".to_string()),
3169 blob: None,
3170 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003171 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3172 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003173
3174 // Reset totally predictable random number generator in case we
3175 // are not the first test running on this thread.
3176 reset_random();
3177 let next_random = 0i64;
3178
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003179 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003180 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003181 assert_eq!(*a, PVEC1);
3182 assert_eq!(
3183 *k,
3184 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003185 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003186 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003187 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003188 alias: Some("key".to_string()),
3189 blob: None,
3190 }
3191 );
3192 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003193 })
3194 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003195
3196 assert_eq!(
3197 app_granted_key,
3198 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003199 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003200 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003201 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003202 alias: None,
3203 blob: None,
3204 }
3205 );
3206
3207 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003208 domain: super::Domain::SELINUX,
3209 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003210 alias: Some("yek".to_string()),
3211 blob: None,
3212 };
3213
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003214 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003215 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003216 assert_eq!(*a, PVEC1);
3217 assert_eq!(
3218 *k,
3219 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003220 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003221 // namespace must be the supplied SELinux
3222 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003223 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003224 alias: Some("yek".to_string()),
3225 blob: None,
3226 }
3227 );
3228 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003229 })
3230 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003231
3232 assert_eq!(
3233 selinux_granted_key,
3234 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003235 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003236 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003237 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003238 alias: None,
3239 blob: None,
3240 }
3241 );
3242
3243 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003244 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003245 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003246 assert_eq!(*a, PVEC2);
3247 assert_eq!(
3248 *k,
3249 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003250 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003251 // namespace must be the supplied SELinux
3252 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003253 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003254 alias: Some("yek".to_string()),
3255 blob: None,
3256 }
3257 );
3258 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003259 })
3260 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003261
3262 assert_eq!(
3263 selinux_granted_key,
3264 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003265 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003266 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003267 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003268 alias: None,
3269 blob: None,
3270 }
3271 );
3272
3273 {
3274 // Limiting scope of stmt, because it borrows db.
3275 let mut stmt = db
3276 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003277 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003278 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3279 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3280 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003281
3282 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003283 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003284 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003285 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003286 assert!(rows.next().is_none());
3287 }
3288
3289 debug_dump_keyentry_table(&mut db)?;
3290 println!("app_key {:?}", app_key);
3291 println!("selinux_key {:?}", selinux_key);
3292
Janis Danisevskis66784c42021-01-27 08:40:25 -08003293 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3294 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003295
3296 Ok(())
3297 }
3298
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003299 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003300 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3301 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3302
3303 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003304 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003305 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003306 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003307 let mut blob_metadata = BlobMetaData::new();
3308 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3309 db.set_blob(
3310 &key_id,
3311 SubComponentType::KEY_BLOB,
3312 Some(TEST_KEY_BLOB),
3313 Some(&blob_metadata),
3314 )?;
3315 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3316 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003317 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003318
3319 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003320 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003321 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003322 )?;
3323 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003324 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003325 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003326 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003327 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003328 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003329 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003330 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003331 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003332 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003333
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003334 drop(rows);
3335 drop(stmt);
3336
3337 assert_eq!(
David Drysdale7b9ca232024-05-23 18:19:46 +01003338 db.with_transaction(Immediate("TX_test"), |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003339 BlobMetaData::load_from_db(id, tx).no_gc()
3340 })
3341 .expect("Should find blob metadata."),
3342 blob_metadata
3343 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003344 Ok(())
3345 }
3346
3347 static TEST_ALIAS: &str = "my super duper key";
3348
3349 #[test]
3350 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3351 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003352 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003353 .context("test_insert_and_load_full_keyentry_domain_app")?
3354 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003355 let (_key_guard, key_entry) = db
3356 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003357 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003358 domain: Domain::APP,
3359 nspace: 0,
3360 alias: Some(TEST_ALIAS.to_string()),
3361 blob: None,
3362 },
3363 KeyType::Client,
3364 KeyEntryLoadBits::BOTH,
3365 1,
3366 |_k, _av| Ok(()),
3367 )
3368 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003369 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003370
3371 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003372 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003373 domain: Domain::APP,
3374 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003375 alias: Some(TEST_ALIAS.to_string()),
3376 blob: None,
3377 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003378 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003379 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003380 |_, _| Ok(()),
3381 )
3382 .unwrap();
3383
3384 assert_eq!(
3385 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3386 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003387 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003388 domain: Domain::APP,
3389 nspace: 0,
3390 alias: Some(TEST_ALIAS.to_string()),
3391 blob: None,
3392 },
3393 KeyType::Client,
3394 KeyEntryLoadBits::NONE,
3395 1,
3396 |_k, _av| Ok(()),
3397 )
3398 .unwrap_err()
3399 .root_cause()
3400 .downcast_ref::<KsError>()
3401 );
3402
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003403 Ok(())
3404 }
3405
3406 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003407 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3408 let mut db = new_test_db()?;
3409
3410 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003411 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003412 domain: Domain::APP,
3413 nspace: 1,
3414 alias: Some(TEST_ALIAS.to_string()),
3415 blob: None,
3416 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003417 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003418 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003419 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003420 )
3421 .expect("Trying to insert cert.");
3422
3423 let (_key_guard, mut key_entry) = db
3424 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003425 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003426 domain: Domain::APP,
3427 nspace: 1,
3428 alias: Some(TEST_ALIAS.to_string()),
3429 blob: None,
3430 },
3431 KeyType::Client,
3432 KeyEntryLoadBits::PUBLIC,
3433 1,
3434 |_k, _av| Ok(()),
3435 )
3436 .expect("Trying to read certificate entry.");
3437
3438 assert!(key_entry.pure_cert());
3439 assert!(key_entry.cert().is_none());
3440 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3441
3442 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003443 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003444 domain: Domain::APP,
3445 nspace: 1,
3446 alias: Some(TEST_ALIAS.to_string()),
3447 blob: None,
3448 },
3449 KeyType::Client,
3450 1,
3451 |_, _| Ok(()),
3452 )
3453 .unwrap();
3454
3455 assert_eq!(
3456 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3457 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003458 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003459 domain: Domain::APP,
3460 nspace: 1,
3461 alias: Some(TEST_ALIAS.to_string()),
3462 blob: None,
3463 },
3464 KeyType::Client,
3465 KeyEntryLoadBits::NONE,
3466 1,
3467 |_k, _av| Ok(()),
3468 )
3469 .unwrap_err()
3470 .root_cause()
3471 .downcast_ref::<KsError>()
3472 );
3473
3474 Ok(())
3475 }
3476
3477 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003478 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3479 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003480 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003481 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3482 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003483 let (_key_guard, key_entry) = db
3484 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003485 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003486 domain: Domain::SELINUX,
3487 nspace: 1,
3488 alias: Some(TEST_ALIAS.to_string()),
3489 blob: None,
3490 },
3491 KeyType::Client,
3492 KeyEntryLoadBits::BOTH,
3493 1,
3494 |_k, _av| Ok(()),
3495 )
3496 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003497 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003498
3499 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003500 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003501 domain: Domain::SELINUX,
3502 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003503 alias: Some(TEST_ALIAS.to_string()),
3504 blob: None,
3505 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003506 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003507 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003508 |_, _| Ok(()),
3509 )
3510 .unwrap();
3511
3512 assert_eq!(
3513 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3514 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003515 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003516 domain: Domain::SELINUX,
3517 nspace: 1,
3518 alias: Some(TEST_ALIAS.to_string()),
3519 blob: None,
3520 },
3521 KeyType::Client,
3522 KeyEntryLoadBits::NONE,
3523 1,
3524 |_k, _av| Ok(()),
3525 )
3526 .unwrap_err()
3527 .root_cause()
3528 .downcast_ref::<KsError>()
3529 );
3530
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003531 Ok(())
3532 }
3533
3534 #[test]
3535 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3536 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003537 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003538 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3539 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003540 let (_, key_entry) = db
3541 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003542 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003543 KeyType::Client,
3544 KeyEntryLoadBits::BOTH,
3545 1,
3546 |_k, _av| Ok(()),
3547 )
3548 .unwrap();
3549
Qi Wub9433b52020-12-01 14:52:46 +08003550 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003551
3552 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003553 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003554 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003555 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003556 |_, _| Ok(()),
3557 )
3558 .unwrap();
3559
3560 assert_eq!(
3561 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3562 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003563 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003564 KeyType::Client,
3565 KeyEntryLoadBits::NONE,
3566 1,
3567 |_k, _av| Ok(()),
3568 )
3569 .unwrap_err()
3570 .root_cause()
3571 .downcast_ref::<KsError>()
3572 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003573
3574 Ok(())
3575 }
3576
3577 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003578 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3579 let mut db = new_test_db()?;
3580 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3581 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3582 .0;
3583 // Update the usage count of the limited use key.
3584 db.check_and_update_key_usage_count(key_id)?;
3585
3586 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003587 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003588 KeyType::Client,
3589 KeyEntryLoadBits::BOTH,
3590 1,
3591 |_k, _av| Ok(()),
3592 )?;
3593
3594 // The usage count is decremented now.
3595 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3596
3597 Ok(())
3598 }
3599
3600 #[test]
3601 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3602 let mut db = new_test_db()?;
3603 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3604 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3605 .0;
3606 // Update the usage count of the limited use key.
3607 db.check_and_update_key_usage_count(key_id).expect(concat!(
3608 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3609 "This should succeed."
3610 ));
3611
3612 // Try to update the exhausted limited use key.
3613 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3614 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3615 "This should fail."
3616 ));
3617 assert_eq!(
3618 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3619 e.root_cause().downcast_ref::<KsError>().unwrap()
3620 );
3621
3622 Ok(())
3623 }
3624
3625 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003626 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3627 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003628 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003629 .context("test_insert_and_load_full_keyentry_from_grant")?
3630 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003631
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003632 let granted_key = db
3633 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003634 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003635 domain: Domain::APP,
3636 nspace: 0,
3637 alias: Some(TEST_ALIAS.to_string()),
3638 blob: None,
3639 },
3640 1,
3641 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003642 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003643 |_k, _av| Ok(()),
3644 )
3645 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003646
3647 debug_dump_grant_table(&mut db)?;
3648
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003649 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003650 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3651 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003652 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003653 Ok(())
3654 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003655 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003656
Qi Wub9433b52020-12-01 14:52:46 +08003657 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003658
Janis Danisevskis66784c42021-01-27 08:40:25 -08003659 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003660
3661 assert_eq!(
3662 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3663 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003664 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003665 KeyType::Client,
3666 KeyEntryLoadBits::NONE,
3667 2,
3668 |_k, _av| Ok(()),
3669 )
3670 .unwrap_err()
3671 .root_cause()
3672 .downcast_ref::<KsError>()
3673 );
3674
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003675 Ok(())
3676 }
3677
Janis Danisevskis45760022021-01-19 16:34:10 -08003678 // This test attempts to load a key by key id while the caller is not the owner
3679 // but a grant exists for the given key and the caller.
3680 #[test]
3681 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3682 let mut db = new_test_db()?;
3683 const OWNER_UID: u32 = 1u32;
3684 const GRANTEE_UID: u32 = 2u32;
3685 const SOMEONE_ELSE_UID: u32 = 3u32;
3686 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3687 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3688 .0;
3689
3690 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003691 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003692 domain: Domain::APP,
3693 nspace: 0,
3694 alias: Some(TEST_ALIAS.to_string()),
3695 blob: None,
3696 },
3697 OWNER_UID,
3698 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003699 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003700 |_k, _av| Ok(()),
3701 )
3702 .unwrap();
3703
3704 debug_dump_grant_table(&mut db)?;
3705
3706 let id_descriptor =
3707 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3708
3709 let (_, key_entry) = db
3710 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003711 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003712 KeyType::Client,
3713 KeyEntryLoadBits::BOTH,
3714 GRANTEE_UID,
3715 |k, av| {
3716 assert_eq!(Domain::APP, k.domain);
3717 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003718 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003719 Ok(())
3720 },
3721 )
3722 .unwrap();
3723
3724 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3725
3726 let (_, key_entry) = db
3727 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003728 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003729 KeyType::Client,
3730 KeyEntryLoadBits::BOTH,
3731 SOMEONE_ELSE_UID,
3732 |k, av| {
3733 assert_eq!(Domain::APP, k.domain);
3734 assert_eq!(OWNER_UID as i64, k.nspace);
3735 assert!(av.is_none());
3736 Ok(())
3737 },
3738 )
3739 .unwrap();
3740
3741 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3742
Janis Danisevskis66784c42021-01-27 08:40:25 -08003743 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003744
3745 assert_eq!(
3746 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3747 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003748 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003749 KeyType::Client,
3750 KeyEntryLoadBits::NONE,
3751 GRANTEE_UID,
3752 |_k, _av| Ok(()),
3753 )
3754 .unwrap_err()
3755 .root_cause()
3756 .downcast_ref::<KsError>()
3757 );
3758
3759 Ok(())
3760 }
3761
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003762 // Creates a key migrates it to a different location and then tries to access it by the old
3763 // and new location.
3764 #[test]
3765 fn test_migrate_key_app_to_app() -> Result<()> {
3766 let mut db = new_test_db()?;
3767 const SOURCE_UID: u32 = 1u32;
3768 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003769 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3770 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003771 let key_id_guard =
3772 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3773 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3774
3775 let source_descriptor: KeyDescriptor = KeyDescriptor {
3776 domain: Domain::APP,
3777 nspace: -1,
3778 alias: Some(SOURCE_ALIAS.to_string()),
3779 blob: None,
3780 };
3781
3782 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3783 domain: Domain::APP,
3784 nspace: -1,
3785 alias: Some(DESTINATION_ALIAS.to_string()),
3786 blob: None,
3787 };
3788
3789 let key_id = key_id_guard.id();
3790
3791 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3792 Ok(())
3793 })
3794 .unwrap();
3795
3796 let (_, key_entry) = db
3797 .load_key_entry(
3798 &destination_descriptor,
3799 KeyType::Client,
3800 KeyEntryLoadBits::BOTH,
3801 DESTINATION_UID,
3802 |k, av| {
3803 assert_eq!(Domain::APP, k.domain);
3804 assert_eq!(DESTINATION_UID as i64, k.nspace);
3805 assert!(av.is_none());
3806 Ok(())
3807 },
3808 )
3809 .unwrap();
3810
3811 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3812
3813 assert_eq!(
3814 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3815 db.load_key_entry(
3816 &source_descriptor,
3817 KeyType::Client,
3818 KeyEntryLoadBits::NONE,
3819 SOURCE_UID,
3820 |_k, _av| Ok(()),
3821 )
3822 .unwrap_err()
3823 .root_cause()
3824 .downcast_ref::<KsError>()
3825 );
3826
3827 Ok(())
3828 }
3829
3830 // Creates a key migrates it to a different location and then tries to access it by the old
3831 // and new location.
3832 #[test]
3833 fn test_migrate_key_app_to_selinux() -> Result<()> {
3834 let mut db = new_test_db()?;
3835 const SOURCE_UID: u32 = 1u32;
3836 const DESTINATION_UID: u32 = 2u32;
3837 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003838 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3839 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003840 let key_id_guard =
3841 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3842 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3843
3844 let source_descriptor: KeyDescriptor = KeyDescriptor {
3845 domain: Domain::APP,
3846 nspace: -1,
3847 alias: Some(SOURCE_ALIAS.to_string()),
3848 blob: None,
3849 };
3850
3851 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3852 domain: Domain::SELINUX,
3853 nspace: DESTINATION_NAMESPACE,
3854 alias: Some(DESTINATION_ALIAS.to_string()),
3855 blob: None,
3856 };
3857
3858 let key_id = key_id_guard.id();
3859
3860 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3861 Ok(())
3862 })
3863 .unwrap();
3864
3865 let (_, key_entry) = db
3866 .load_key_entry(
3867 &destination_descriptor,
3868 KeyType::Client,
3869 KeyEntryLoadBits::BOTH,
3870 DESTINATION_UID,
3871 |k, av| {
3872 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003873 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003874 assert!(av.is_none());
3875 Ok(())
3876 },
3877 )
3878 .unwrap();
3879
3880 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3881
3882 assert_eq!(
3883 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3884 db.load_key_entry(
3885 &source_descriptor,
3886 KeyType::Client,
3887 KeyEntryLoadBits::NONE,
3888 SOURCE_UID,
3889 |_k, _av| Ok(()),
3890 )
3891 .unwrap_err()
3892 .root_cause()
3893 .downcast_ref::<KsError>()
3894 );
3895
3896 Ok(())
3897 }
3898
3899 // Creates two keys and tries to migrate the first to the location of the second which
3900 // is expected to fail.
3901 #[test]
3902 fn test_migrate_key_destination_occupied() -> Result<()> {
3903 let mut db = new_test_db()?;
3904 const SOURCE_UID: u32 = 1u32;
3905 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003906 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3907 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003908 let key_id_guard =
3909 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3910 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3911 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3912 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3913
3914 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3915 domain: Domain::APP,
3916 nspace: -1,
3917 alias: Some(DESTINATION_ALIAS.to_string()),
3918 blob: None,
3919 };
3920
3921 assert_eq!(
3922 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3923 db.migrate_key_namespace(
3924 key_id_guard,
3925 &destination_descriptor,
3926 DESTINATION_UID,
3927 |_k| Ok(())
3928 )
3929 .unwrap_err()
3930 .root_cause()
3931 .downcast_ref::<KsError>()
3932 );
3933
3934 Ok(())
3935 }
3936
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003937 #[test]
3938 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003939 const ALIAS1: &str = "test_upgrade_0_to_1_1";
3940 const ALIAS2: &str = "test_upgrade_0_to_1_2";
3941 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003942 const UID: u32 = 33;
3943 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3944 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3945 let key_id_untouched1 =
3946 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3947 let key_id_untouched2 =
3948 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
3949 let key_id_deleted =
3950 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
3951
3952 let (_, key_entry) = db
3953 .load_key_entry(
3954 &KeyDescriptor {
3955 domain: Domain::APP,
3956 nspace: -1,
3957 alias: Some(ALIAS1.to_string()),
3958 blob: None,
3959 },
3960 KeyType::Client,
3961 KeyEntryLoadBits::BOTH,
3962 UID,
3963 |k, av| {
3964 assert_eq!(Domain::APP, k.domain);
3965 assert_eq!(UID as i64, k.nspace);
3966 assert!(av.is_none());
3967 Ok(())
3968 },
3969 )
3970 .unwrap();
3971 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
3972 let (_, key_entry) = db
3973 .load_key_entry(
3974 &KeyDescriptor {
3975 domain: Domain::APP,
3976 nspace: -1,
3977 alias: Some(ALIAS2.to_string()),
3978 blob: None,
3979 },
3980 KeyType::Client,
3981 KeyEntryLoadBits::BOTH,
3982 UID,
3983 |k, av| {
3984 assert_eq!(Domain::APP, k.domain);
3985 assert_eq!(UID as i64, k.nspace);
3986 assert!(av.is_none());
3987 Ok(())
3988 },
3989 )
3990 .unwrap();
3991 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
3992 let (_, key_entry) = db
3993 .load_key_entry(
3994 &KeyDescriptor {
3995 domain: Domain::APP,
3996 nspace: -1,
3997 alias: Some(ALIAS3.to_string()),
3998 blob: None,
3999 },
4000 KeyType::Client,
4001 KeyEntryLoadBits::BOTH,
4002 UID,
4003 |k, av| {
4004 assert_eq!(Domain::APP, k.domain);
4005 assert_eq!(UID as i64, k.nspace);
4006 assert!(av.is_none());
4007 Ok(())
4008 },
4009 )
4010 .unwrap();
4011 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4012
David Drysdale7b9ca232024-05-23 18:19:46 +01004013 db.with_transaction(Immediate("TX_test"), |tx| KeystoreDB::from_0_to_1(tx).no_gc())
4014 .unwrap();
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004015
4016 let (_, key_entry) = db
4017 .load_key_entry(
4018 &KeyDescriptor {
4019 domain: Domain::APP,
4020 nspace: -1,
4021 alias: Some(ALIAS1.to_string()),
4022 blob: None,
4023 },
4024 KeyType::Client,
4025 KeyEntryLoadBits::BOTH,
4026 UID,
4027 |k, av| {
4028 assert_eq!(Domain::APP, k.domain);
4029 assert_eq!(UID as i64, k.nspace);
4030 assert!(av.is_none());
4031 Ok(())
4032 },
4033 )
4034 .unwrap();
4035 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4036 let (_, key_entry) = db
4037 .load_key_entry(
4038 &KeyDescriptor {
4039 domain: Domain::APP,
4040 nspace: -1,
4041 alias: Some(ALIAS2.to_string()),
4042 blob: None,
4043 },
4044 KeyType::Client,
4045 KeyEntryLoadBits::BOTH,
4046 UID,
4047 |k, av| {
4048 assert_eq!(Domain::APP, k.domain);
4049 assert_eq!(UID as i64, k.nspace);
4050 assert!(av.is_none());
4051 Ok(())
4052 },
4053 )
4054 .unwrap();
4055 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4056 assert_eq!(
4057 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4058 db.load_key_entry(
4059 &KeyDescriptor {
4060 domain: Domain::APP,
4061 nspace: -1,
4062 alias: Some(ALIAS3.to_string()),
4063 blob: None,
4064 },
4065 KeyType::Client,
4066 KeyEntryLoadBits::BOTH,
4067 UID,
4068 |k, av| {
4069 assert_eq!(Domain::APP, k.domain);
4070 assert_eq!(UID as i64, k.nspace);
4071 assert!(av.is_none());
4072 Ok(())
4073 },
4074 )
4075 .unwrap_err()
4076 .root_cause()
4077 .downcast_ref::<KsError>()
4078 );
4079 }
4080
Janis Danisevskisaec14592020-11-12 09:41:49 -08004081 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4082
Janis Danisevskisaec14592020-11-12 09:41:49 -08004083 #[test]
4084 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4085 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004086 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4087 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004088 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004089 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004090 .context("test_insert_and_load_full_keyentry_domain_app")?
4091 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004092 let (_key_guard, key_entry) = db
4093 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004094 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004095 domain: Domain::APP,
4096 nspace: 0,
4097 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4098 blob: None,
4099 },
4100 KeyType::Client,
4101 KeyEntryLoadBits::BOTH,
4102 33,
4103 |_k, _av| Ok(()),
4104 )
4105 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004106 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004107 let state = Arc::new(AtomicU8::new(1));
4108 let state2 = state.clone();
4109
4110 // Spawning a second thread that attempts to acquire the key id lock
4111 // for the same key as the primary thread. The primary thread then
4112 // waits, thereby forcing the secondary thread into the second stage
4113 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4114 // The test succeeds if the secondary thread observes the transition
4115 // of `state` from 1 to 2, despite having a whole second to overtake
4116 // the primary thread.
4117 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004118 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004119 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004120 assert!(db
4121 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004122 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004123 domain: Domain::APP,
4124 nspace: 0,
4125 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4126 blob: None,
4127 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004128 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004129 KeyEntryLoadBits::BOTH,
4130 33,
4131 |_k, _av| Ok(()),
4132 )
4133 .is_ok());
4134 // We should only see a 2 here because we can only return
4135 // from load_key_entry when the `_key_guard` expires,
4136 // which happens at the end of the scope.
4137 assert_eq!(2, state2.load(Ordering::Relaxed));
4138 });
4139
4140 thread::sleep(std::time::Duration::from_millis(1000));
4141
4142 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4143
4144 // Return the handle from this scope so we can join with the
4145 // secondary thread after the key id lock has expired.
4146 handle
4147 // This is where the `_key_guard` goes out of scope,
4148 // which is the reason for concurrent load_key_entry on the same key
4149 // to unblock.
4150 };
4151 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4152 // main test thread. We will not see failing asserts in secondary threads otherwise.
4153 handle.join().unwrap();
4154 Ok(())
4155 }
4156
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004157 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004158 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004159 let temp_dir =
4160 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4161
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004162 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4163 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004164
4165 let _tx1 = db1
4166 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004167 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004168 .expect("Failed to create first transaction.");
4169
4170 let error = db2
4171 .conn
David Drysdale7b9ca232024-05-23 18:19:46 +01004172 .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
Janis Danisevskis66784c42021-01-27 08:40:25 -08004173 .context("Transaction begin failed.")
4174 .expect_err("This should fail.");
4175 let root_cause = error.root_cause();
4176 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4177 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4178 {
4179 return;
4180 }
4181 panic!(
4182 "Unexpected error {:?} \n{:?} \n{:?}",
4183 error,
4184 root_cause,
4185 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4186 )
4187 }
4188
4189 #[cfg(disabled)]
4190 #[test]
4191 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4192 let temp_dir = Arc::new(
4193 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4194 .expect("Failed to create temp dir."),
4195 );
4196
4197 let test_begin = Instant::now();
4198
Janis Danisevskis66784c42021-01-27 08:40:25 -08004199 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004200 let mut db =
4201 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004202 const OPEN_DB_COUNT: u32 = 50u32;
4203
4204 let mut actual_key_count = KEY_COUNT;
4205 // First insert KEY_COUNT keys.
4206 for count in 0..KEY_COUNT {
4207 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4208 actual_key_count = count;
4209 break;
4210 }
4211 let alias = format!("test_alias_{}", count);
4212 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4213 .expect("Failed to make key entry.");
4214 }
4215
4216 // Insert more keys from a different thread and into a different namespace.
4217 let temp_dir1 = temp_dir.clone();
4218 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004219 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4220 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004221
4222 for count in 0..actual_key_count {
4223 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4224 return;
4225 }
4226 let alias = format!("test_alias_{}", count);
4227 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4228 .expect("Failed to make key entry.");
4229 }
4230
4231 // then unbind them again.
4232 for count in 0..actual_key_count {
4233 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4234 return;
4235 }
4236 let key = KeyDescriptor {
4237 domain: Domain::APP,
4238 nspace: -1,
4239 alias: Some(format!("test_alias_{}", count)),
4240 blob: None,
4241 };
4242 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4243 }
4244 });
4245
4246 // And start unbinding the first set of keys.
4247 let temp_dir2 = temp_dir.clone();
4248 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004249 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4250 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004251
4252 for count in 0..actual_key_count {
4253 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4254 return;
4255 }
4256 let key = KeyDescriptor {
4257 domain: Domain::APP,
4258 nspace: -1,
4259 alias: Some(format!("test_alias_{}", count)),
4260 blob: None,
4261 };
4262 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4263 }
4264 });
4265
Janis Danisevskis66784c42021-01-27 08:40:25 -08004266 // While a lot of inserting and deleting is going on we have to open database connections
4267 // successfully and use them.
4268 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4269 // out of scope.
4270 #[allow(clippy::redundant_clone)]
4271 let temp_dir4 = temp_dir.clone();
4272 let handle4 = thread::spawn(move || {
4273 for count in 0..OPEN_DB_COUNT {
4274 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4275 return;
4276 }
Seth Moore444b51a2021-06-11 09:49:49 -07004277 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4278 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004279
4280 let alias = format!("test_alias_{}", count);
4281 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4282 .expect("Failed to make key entry.");
4283 let key = KeyDescriptor {
4284 domain: Domain::APP,
4285 nspace: -1,
4286 alias: Some(alias),
4287 blob: None,
4288 };
4289 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4290 }
4291 });
4292
4293 handle1.join().expect("Thread 1 panicked.");
4294 handle2.join().expect("Thread 2 panicked.");
4295 handle4.join().expect("Thread 4 panicked.");
4296
Janis Danisevskis66784c42021-01-27 08:40:25 -08004297 Ok(())
4298 }
4299
4300 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004301 fn list() -> Result<()> {
4302 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004303 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004304 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4305 (Domain::APP, 1, "test1"),
4306 (Domain::APP, 1, "test2"),
4307 (Domain::APP, 1, "test3"),
4308 (Domain::APP, 1, "test4"),
4309 (Domain::APP, 1, "test5"),
4310 (Domain::APP, 1, "test6"),
4311 (Domain::APP, 1, "test7"),
4312 (Domain::APP, 2, "test1"),
4313 (Domain::APP, 2, "test2"),
4314 (Domain::APP, 2, "test3"),
4315 (Domain::APP, 2, "test4"),
4316 (Domain::APP, 2, "test5"),
4317 (Domain::APP, 2, "test6"),
4318 (Domain::APP, 2, "test8"),
4319 (Domain::SELINUX, 100, "test1"),
4320 (Domain::SELINUX, 100, "test2"),
4321 (Domain::SELINUX, 100, "test3"),
4322 (Domain::SELINUX, 100, "test4"),
4323 (Domain::SELINUX, 100, "test5"),
4324 (Domain::SELINUX, 100, "test6"),
4325 (Domain::SELINUX, 100, "test9"),
4326 ];
4327
4328 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4329 .iter()
4330 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004331 let entry =
4332 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004333 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4334 });
4335 (entry.id(), *ns)
4336 })
4337 .collect();
4338
4339 for (domain, namespace) in
4340 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4341 {
4342 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4343 .iter()
4344 .filter_map(|(domain, ns, alias)| match ns {
4345 ns if *ns == *namespace => Some(KeyDescriptor {
4346 domain: *domain,
4347 nspace: *ns,
4348 alias: Some(alias.to_string()),
4349 blob: None,
4350 }),
4351 _ => None,
4352 })
4353 .collect();
4354 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004355 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004356 list_result.sort();
4357 assert_eq!(list_o_descriptors, list_result);
4358
4359 let mut list_o_ids: Vec<i64> = list_o_descriptors
4360 .into_iter()
4361 .map(|d| {
4362 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004363 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004364 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004365 KeyType::Client,
4366 KeyEntryLoadBits::NONE,
4367 *namespace as u32,
4368 |_, _| Ok(()),
4369 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004370 .unwrap();
4371 entry.id()
4372 })
4373 .collect();
4374 list_o_ids.sort_unstable();
4375 let mut loaded_entries: Vec<i64> = list_o_keys
4376 .iter()
4377 .filter_map(|(id, ns)| match ns {
4378 ns if *ns == *namespace => Some(*id),
4379 _ => None,
4380 })
4381 .collect();
4382 loaded_entries.sort_unstable();
4383 assert_eq!(list_o_ids, loaded_entries);
4384 }
Eran Messeri24f31972023-01-25 17:00:33 +00004385 assert_eq!(
4386 Vec::<KeyDescriptor>::new(),
4387 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4388 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004389
4390 Ok(())
4391 }
4392
Joel Galenson0891bc12020-07-20 10:37:03 -07004393 // Helpers
4394
4395 // Checks that the given result is an error containing the given string.
4396 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4397 let error_str = format!(
4398 "{:#?}",
4399 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4400 );
4401 assert!(
4402 error_str.contains(target),
4403 "The string \"{}\" should contain \"{}\"",
4404 error_str,
4405 target
4406 );
4407 }
4408
Joel Galenson2aab4432020-07-22 15:27:57 -07004409 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004410 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004411 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004412 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004413 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004414 namespace: Option<i64>,
4415 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004416 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004417 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004418 }
4419
4420 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4421 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004422 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004423 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004424 Ok(KeyEntryRow {
4425 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004426 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004427 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004428 namespace: row.get(3)?,
4429 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004430 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004431 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004432 })
4433 })?
4434 .map(|r| r.context("Could not read keyentry row."))
4435 .collect::<Result<Vec<_>>>()
4436 }
4437
Eran Messeri4dc27b52024-01-09 12:43:31 +00004438 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4439 make_test_params_with_sids(max_usage_count, &[42])
4440 }
4441
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004442 // Note: The parameters and SecurityLevel associations are nonsensical. This
4443 // collection is only used to check if the parameters are preserved as expected by the
4444 // database.
Eran Messeri4dc27b52024-01-09 12:43:31 +00004445 fn make_test_params_with_sids(
4446 max_usage_count: Option<i32>,
4447 user_secure_ids: &[i64],
4448 ) -> Vec<KeyParameter> {
Qi Wub9433b52020-12-01 14:52:46 +08004449 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004450 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4451 KeyParameter::new(
4452 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4453 SecurityLevel::TRUSTED_ENVIRONMENT,
4454 ),
4455 KeyParameter::new(
4456 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4457 SecurityLevel::TRUSTED_ENVIRONMENT,
4458 ),
4459 KeyParameter::new(
4460 KeyParameterValue::Algorithm(Algorithm::RSA),
4461 SecurityLevel::TRUSTED_ENVIRONMENT,
4462 ),
4463 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4464 KeyParameter::new(
4465 KeyParameterValue::BlockMode(BlockMode::ECB),
4466 SecurityLevel::TRUSTED_ENVIRONMENT,
4467 ),
4468 KeyParameter::new(
4469 KeyParameterValue::BlockMode(BlockMode::GCM),
4470 SecurityLevel::TRUSTED_ENVIRONMENT,
4471 ),
4472 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4473 KeyParameter::new(
4474 KeyParameterValue::Digest(Digest::MD5),
4475 SecurityLevel::TRUSTED_ENVIRONMENT,
4476 ),
4477 KeyParameter::new(
4478 KeyParameterValue::Digest(Digest::SHA_2_224),
4479 SecurityLevel::TRUSTED_ENVIRONMENT,
4480 ),
4481 KeyParameter::new(
4482 KeyParameterValue::Digest(Digest::SHA_2_256),
4483 SecurityLevel::STRONGBOX,
4484 ),
4485 KeyParameter::new(
4486 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4487 SecurityLevel::TRUSTED_ENVIRONMENT,
4488 ),
4489 KeyParameter::new(
4490 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4491 SecurityLevel::TRUSTED_ENVIRONMENT,
4492 ),
4493 KeyParameter::new(
4494 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4495 SecurityLevel::STRONGBOX,
4496 ),
4497 KeyParameter::new(
4498 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4499 SecurityLevel::TRUSTED_ENVIRONMENT,
4500 ),
4501 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4502 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4503 KeyParameter::new(
4504 KeyParameterValue::EcCurve(EcCurve::P_224),
4505 SecurityLevel::TRUSTED_ENVIRONMENT,
4506 ),
4507 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4508 KeyParameter::new(
4509 KeyParameterValue::EcCurve(EcCurve::P_384),
4510 SecurityLevel::TRUSTED_ENVIRONMENT,
4511 ),
4512 KeyParameter::new(
4513 KeyParameterValue::EcCurve(EcCurve::P_521),
4514 SecurityLevel::TRUSTED_ENVIRONMENT,
4515 ),
4516 KeyParameter::new(
4517 KeyParameterValue::RSAPublicExponent(3),
4518 SecurityLevel::TRUSTED_ENVIRONMENT,
4519 ),
4520 KeyParameter::new(
4521 KeyParameterValue::IncludeUniqueID,
4522 SecurityLevel::TRUSTED_ENVIRONMENT,
4523 ),
4524 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4525 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4526 KeyParameter::new(
4527 KeyParameterValue::ActiveDateTime(1234567890),
4528 SecurityLevel::STRONGBOX,
4529 ),
4530 KeyParameter::new(
4531 KeyParameterValue::OriginationExpireDateTime(1234567890),
4532 SecurityLevel::TRUSTED_ENVIRONMENT,
4533 ),
4534 KeyParameter::new(
4535 KeyParameterValue::UsageExpireDateTime(1234567890),
4536 SecurityLevel::TRUSTED_ENVIRONMENT,
4537 ),
4538 KeyParameter::new(
4539 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4540 SecurityLevel::TRUSTED_ENVIRONMENT,
4541 ),
4542 KeyParameter::new(
4543 KeyParameterValue::MaxUsesPerBoot(1234567890),
4544 SecurityLevel::TRUSTED_ENVIRONMENT,
4545 ),
4546 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004547 KeyParameter::new(
4548 KeyParameterValue::NoAuthRequired,
4549 SecurityLevel::TRUSTED_ENVIRONMENT,
4550 ),
4551 KeyParameter::new(
4552 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4553 SecurityLevel::TRUSTED_ENVIRONMENT,
4554 ),
4555 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4556 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4557 KeyParameter::new(
4558 KeyParameterValue::TrustedUserPresenceRequired,
4559 SecurityLevel::TRUSTED_ENVIRONMENT,
4560 ),
4561 KeyParameter::new(
4562 KeyParameterValue::TrustedConfirmationRequired,
4563 SecurityLevel::TRUSTED_ENVIRONMENT,
4564 ),
4565 KeyParameter::new(
4566 KeyParameterValue::UnlockedDeviceRequired,
4567 SecurityLevel::TRUSTED_ENVIRONMENT,
4568 ),
4569 KeyParameter::new(
4570 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4571 SecurityLevel::SOFTWARE,
4572 ),
4573 KeyParameter::new(
4574 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4575 SecurityLevel::SOFTWARE,
4576 ),
4577 KeyParameter::new(
4578 KeyParameterValue::CreationDateTime(12345677890),
4579 SecurityLevel::SOFTWARE,
4580 ),
4581 KeyParameter::new(
4582 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4583 SecurityLevel::TRUSTED_ENVIRONMENT,
4584 ),
4585 KeyParameter::new(
4586 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4587 SecurityLevel::TRUSTED_ENVIRONMENT,
4588 ),
4589 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4590 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4591 KeyParameter::new(
4592 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4593 SecurityLevel::SOFTWARE,
4594 ),
4595 KeyParameter::new(
4596 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4597 SecurityLevel::TRUSTED_ENVIRONMENT,
4598 ),
4599 KeyParameter::new(
4600 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4601 SecurityLevel::TRUSTED_ENVIRONMENT,
4602 ),
4603 KeyParameter::new(
4604 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4605 SecurityLevel::TRUSTED_ENVIRONMENT,
4606 ),
4607 KeyParameter::new(
4608 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4609 SecurityLevel::TRUSTED_ENVIRONMENT,
4610 ),
4611 KeyParameter::new(
4612 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4613 SecurityLevel::TRUSTED_ENVIRONMENT,
4614 ),
4615 KeyParameter::new(
4616 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4617 SecurityLevel::TRUSTED_ENVIRONMENT,
4618 ),
4619 KeyParameter::new(
4620 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4621 SecurityLevel::TRUSTED_ENVIRONMENT,
4622 ),
4623 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004624 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4625 SecurityLevel::TRUSTED_ENVIRONMENT,
4626 ),
4627 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004628 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4629 SecurityLevel::TRUSTED_ENVIRONMENT,
4630 ),
4631 KeyParameter::new(
4632 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4633 SecurityLevel::TRUSTED_ENVIRONMENT,
4634 ),
4635 KeyParameter::new(
4636 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4637 SecurityLevel::TRUSTED_ENVIRONMENT,
4638 ),
4639 KeyParameter::new(
4640 KeyParameterValue::VendorPatchLevel(3),
4641 SecurityLevel::TRUSTED_ENVIRONMENT,
4642 ),
4643 KeyParameter::new(
4644 KeyParameterValue::BootPatchLevel(4),
4645 SecurityLevel::TRUSTED_ENVIRONMENT,
4646 ),
4647 KeyParameter::new(
4648 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4649 SecurityLevel::TRUSTED_ENVIRONMENT,
4650 ),
4651 KeyParameter::new(
4652 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4653 SecurityLevel::TRUSTED_ENVIRONMENT,
4654 ),
4655 KeyParameter::new(
4656 KeyParameterValue::MacLength(256),
4657 SecurityLevel::TRUSTED_ENVIRONMENT,
4658 ),
4659 KeyParameter::new(
4660 KeyParameterValue::ResetSinceIdRotation,
4661 SecurityLevel::TRUSTED_ENVIRONMENT,
4662 ),
4663 KeyParameter::new(
4664 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4665 SecurityLevel::TRUSTED_ENVIRONMENT,
4666 ),
Qi Wub9433b52020-12-01 14:52:46 +08004667 ];
4668 if let Some(value) = max_usage_count {
4669 params.push(KeyParameter::new(
4670 KeyParameterValue::UsageCountLimit(value),
4671 SecurityLevel::SOFTWARE,
4672 ));
4673 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00004674
4675 for sid in user_secure_ids.iter() {
4676 params.push(KeyParameter::new(
4677 KeyParameterValue::UserSecureID(*sid),
4678 SecurityLevel::STRONGBOX,
4679 ));
4680 }
Qi Wub9433b52020-12-01 14:52:46 +08004681 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004682 }
4683
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004684 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004685 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004686 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004687 namespace: i64,
4688 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004689 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004690 ) -> Result<KeyIdGuard> {
Eran Messeri4dc27b52024-01-09 12:43:31 +00004691 make_test_key_entry_with_sids(db, domain, namespace, alias, max_usage_count, &[42])
4692 }
4693
4694 pub fn make_test_key_entry_with_sids(
4695 db: &mut KeystoreDB,
4696 domain: Domain,
4697 namespace: i64,
4698 alias: &str,
4699 max_usage_count: Option<i32>,
4700 sids: &[i64],
4701 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004702 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004703 let mut blob_metadata = BlobMetaData::new();
4704 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4705 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4706 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4707 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4708 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4709
4710 db.set_blob(
4711 &key_id,
4712 SubComponentType::KEY_BLOB,
4713 Some(TEST_KEY_BLOB),
4714 Some(&blob_metadata),
4715 )?;
4716 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4717 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004718
Eran Messeri4dc27b52024-01-09 12:43:31 +00004719 let params = make_test_params_with_sids(max_usage_count, sids);
Qi Wub9433b52020-12-01 14:52:46 +08004720 db.insert_keyparameter(&key_id, &params)?;
4721
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004722 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004723 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004724 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004725 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004726 Ok(key_id)
4727 }
4728
Qi Wub9433b52020-12-01 14:52:46 +08004729 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4730 let params = make_test_params(max_usage_count);
4731
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004732 let mut blob_metadata = BlobMetaData::new();
4733 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4734 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4735 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4736 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4737 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4738
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004739 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004740 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004741
4742 KeyEntry {
4743 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004744 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004745 cert: Some(TEST_CERT_BLOB.to_vec()),
4746 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004747 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004748 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004749 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004750 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004751 }
4752 }
4753
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004754 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004755 db: &mut KeystoreDB,
4756 domain: Domain,
4757 namespace: i64,
4758 alias: &str,
4759 logical_only: bool,
4760 ) -> Result<KeyIdGuard> {
David Drysdale8c4c4f32023-10-31 12:14:11 +00004761 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004762 let mut blob_metadata = BlobMetaData::new();
4763 if !logical_only {
4764 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4765 }
4766 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4767
4768 db.set_blob(
4769 &key_id,
4770 SubComponentType::KEY_BLOB,
4771 Some(TEST_KEY_BLOB),
4772 Some(&blob_metadata),
4773 )?;
4774 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4775 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4776
4777 let mut params = make_test_params(None);
4778 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4779
4780 db.insert_keyparameter(&key_id, &params)?;
4781
4782 let mut metadata = KeyMetaData::new();
4783 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4784 db.insert_key_metadata(&key_id, &metadata)?;
4785 rebind_alias(db, &key_id, alias, domain, namespace)?;
4786 Ok(key_id)
4787 }
4788
Eric Biggersb0478cf2023-10-27 03:55:29 +00004789 // Creates an app key that is marked as being superencrypted by the given
4790 // super key ID and that has the given authentication and unlocked device
4791 // parameters. This does not actually superencrypt the key blob.
4792 fn make_superencrypted_key_entry(
4793 db: &mut KeystoreDB,
4794 namespace: i64,
4795 alias: &str,
4796 requires_authentication: bool,
4797 requires_unlocked_device: bool,
4798 super_key_id: i64,
4799 ) -> Result<KeyIdGuard> {
4800 let domain = Domain::APP;
David Drysdale8c4c4f32023-10-31 12:14:11 +00004801 let key_id = create_key_entry(db, &domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Eric Biggersb0478cf2023-10-27 03:55:29 +00004802
4803 let mut blob_metadata = BlobMetaData::new();
4804 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4805 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4806 db.set_blob(
4807 &key_id,
4808 SubComponentType::KEY_BLOB,
4809 Some(TEST_KEY_BLOB),
4810 Some(&blob_metadata),
4811 )?;
4812
4813 let mut params = vec![];
4814 if requires_unlocked_device {
4815 params.push(KeyParameter::new(
4816 KeyParameterValue::UnlockedDeviceRequired,
4817 SecurityLevel::TRUSTED_ENVIRONMENT,
4818 ));
4819 }
4820 if requires_authentication {
4821 params.push(KeyParameter::new(
4822 KeyParameterValue::UserSecureID(42),
4823 SecurityLevel::TRUSTED_ENVIRONMENT,
4824 ));
4825 }
4826 db.insert_keyparameter(&key_id, &params)?;
4827
4828 let mut metadata = KeyMetaData::new();
4829 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4830 db.insert_key_metadata(&key_id, &metadata)?;
4831
4832 rebind_alias(db, &key_id, alias, domain, namespace)?;
4833 Ok(key_id)
4834 }
4835
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004836 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4837 let mut params = make_test_params(None);
4838 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4839
4840 let mut blob_metadata = BlobMetaData::new();
4841 if !logical_only {
4842 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4843 }
4844 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4845
4846 let mut metadata = KeyMetaData::new();
4847 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4848
4849 KeyEntry {
4850 id: key_id,
4851 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4852 cert: Some(TEST_CERT_BLOB.to_vec()),
4853 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4854 km_uuid: KEYSTORE_UUID,
4855 parameters: params,
4856 metadata,
4857 pure_cert: false,
4858 }
4859 }
4860
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004861 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004862 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004863 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004864 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004865 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004866 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004867 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004868 Ok((
4869 row.get(0)?,
4870 row.get(1)?,
4871 row.get(2)?,
4872 row.get(3)?,
4873 row.get(4)?,
4874 row.get(5)?,
4875 row.get(6)?,
4876 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004877 },
4878 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004879
4880 println!("Key entry table rows:");
4881 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004882 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004883 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004884 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4885 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004886 );
4887 }
4888 Ok(())
4889 }
4890
4891 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004892 let mut stmt = db
4893 .conn
4894 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004895 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004896 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4897 })?;
4898
4899 println!("Grant table rows:");
4900 for r in rows {
4901 let (id, gt, ki, av) = r.unwrap();
4902 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4903 }
4904 Ok(())
4905 }
4906
Joel Galenson0891bc12020-07-20 10:37:03 -07004907 // Use a custom random number generator that repeats each number once.
4908 // This allows us to test repeated elements.
4909
4910 thread_local! {
Charisee43391152024-04-02 16:16:30 +00004911 static RANDOM_COUNTER: RefCell<i64> = const { RefCell::new(0) };
Joel Galenson0891bc12020-07-20 10:37:03 -07004912 }
4913
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004914 fn reset_random() {
4915 RANDOM_COUNTER.with(|counter| {
4916 *counter.borrow_mut() = 0;
4917 })
4918 }
4919
Joel Galenson0891bc12020-07-20 10:37:03 -07004920 pub fn random() -> i64 {
4921 RANDOM_COUNTER.with(|counter| {
4922 let result = *counter.borrow() / 2;
4923 *counter.borrow_mut() += 1;
4924 result
4925 })
4926 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004927
4928 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00004929 fn test_unbind_keys_for_user() -> Result<()> {
4930 let mut db = new_test_db()?;
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004931 db.unbind_keys_for_user(1)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004932
4933 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4934 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004935 db.unbind_keys_for_user(2)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004936
Eran Messeri24f31972023-01-25 17:00:33 +00004937 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4938 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004939
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004940 db.unbind_keys_for_user(1)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004941 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004942
4943 Ok(())
4944 }
4945
4946 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004947 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4948 let mut db = new_test_db()?;
4949 let super_key = keystore2_crypto::generate_aes256_key()?;
4950 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4951 let (encrypted_super_key, metadata) =
4952 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4953
4954 let key_name_enc = SuperKeyType {
4955 alias: "test_super_key_1",
4956 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004957 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004958 };
4959
4960 let key_name_nonenc = SuperKeyType {
4961 alias: "test_super_key_2",
4962 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004963 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004964 };
4965
4966 // Install two super keys.
4967 db.store_super_key(
4968 1,
4969 &key_name_nonenc,
4970 &super_key,
4971 &BlobMetaData::new(),
4972 &KeyMetaData::new(),
4973 )?;
4974 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4975
4976 // Check that both can be found in the database.
4977 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
4978 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
4979
4980 // Install the same keys for a different user.
4981 db.store_super_key(
4982 2,
4983 &key_name_nonenc,
4984 &super_key,
4985 &BlobMetaData::new(),
4986 &KeyMetaData::new(),
4987 )?;
4988 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4989
4990 // Check that the second pair of keys can be found in the database.
4991 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
4992 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
4993
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004994 // Delete all keys for user 1.
4995 db.unbind_keys_for_user(1)?;
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004996
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00004997 // All of user 1's keys should be gone.
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004998 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
4999 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5000
Eric Biggers9f7ebeb2024-06-20 14:59:32 +00005001 // User 2's keys should not have been touched.
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005002 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5003 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5004
5005 Ok(())
5006 }
5007
Eric Biggersb0478cf2023-10-27 03:55:29 +00005008 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5009 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5010 }
5011
5012 // Tests the unbind_auth_bound_keys_for_user() function.
5013 #[test]
5014 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5015 let mut db = new_test_db()?;
5016 let user_id = 1;
5017 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5018 let other_user_id = 2;
5019 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5020 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5021
5022 // Create a superencryption key.
5023 let super_key = keystore2_crypto::generate_aes256_key()?;
5024 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5025 let (encrypted_super_key, blob_metadata) =
5026 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5027 db.store_super_key(
5028 user_id,
5029 super_key_type,
5030 &encrypted_super_key,
5031 &blob_metadata,
5032 &KeyMetaData::new(),
5033 )?;
5034 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5035
5036 // Store 4 superencrypted app keys, one for each possible combination of
5037 // (authentication required, unlocked device required).
5038 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5039 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5040 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5041 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5042 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5043 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5044 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5045 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5046
5047 // Also store a key for a different user that requires authentication.
5048 make_superencrypted_key_entry(
5049 &mut db,
5050 other_user_nspace,
5051 "auth_ud",
5052 true,
5053 true,
5054 super_key_id,
5055 )?;
5056
5057 db.unbind_auth_bound_keys_for_user(user_id)?;
5058
5059 // Verify that only the user's app keys that require authentication were
5060 // deleted. Keys that require an unlocked device but not authentication
5061 // should *not* have been deleted, nor should the super key have been
5062 // deleted, nor should other users' keys have been deleted.
5063 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5064 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5065 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5066 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5067 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5068 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5069
5070 Ok(())
5071 }
5072
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005073 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005074 fn test_store_super_key() -> Result<()> {
5075 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005076 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005077 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005078 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005079 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005080 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005081
5082 let (encrypted_super_key, metadata) =
5083 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005084 db.store_super_key(
5085 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005086 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005087 &encrypted_super_key,
5088 &metadata,
5089 &KeyMetaData::new(),
5090 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005091
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005092 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005093 assert!(db.key_exists(
5094 Domain::APP,
5095 1,
5096 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5097 KeyType::Super
5098 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005099
Eric Biggers673d34a2023-10-18 01:54:18 +00005100 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005101 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005102 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005103 key_entry,
5104 &pw,
5105 None,
5106 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005107
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005108 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005109 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005110
Hasini Gunasingheda895552021-01-27 19:34:37 +00005111 Ok(())
5112 }
Seth Moore78c091f2021-04-09 21:38:30 +00005113
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005114 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005115 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005116 MetricsStorage::KEY_ENTRY,
5117 MetricsStorage::KEY_ENTRY_ID_INDEX,
5118 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5119 MetricsStorage::BLOB_ENTRY,
5120 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5121 MetricsStorage::KEY_PARAMETER,
5122 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5123 MetricsStorage::KEY_METADATA,
5124 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5125 MetricsStorage::GRANT,
5126 MetricsStorage::AUTH_TOKEN,
5127 MetricsStorage::BLOB_METADATA,
5128 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005129 ]
5130 }
5131
5132 /// Perform a simple check to ensure that we can query all the storage types
5133 /// that are supported by the DB. Check for reasonable values.
5134 #[test]
5135 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005136 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005137
5138 let mut db = new_test_db()?;
5139
5140 for t in get_valid_statsd_storage_types() {
5141 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005142 // AuthToken can be less than a page since it's in a btree, not sqlite
5143 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005144 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005145 } else {
5146 assert!(stat.size >= PAGE_SIZE);
5147 }
Seth Moore78c091f2021-04-09 21:38:30 +00005148 assert!(stat.size >= stat.unused_size);
5149 }
5150
5151 Ok(())
5152 }
5153
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005154 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005155 get_valid_statsd_storage_types()
5156 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005157 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005158 .collect()
5159 }
5160
5161 fn assert_storage_increased(
5162 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005163 increased_storage_types: Vec<MetricsStorage>,
5164 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005165 ) {
5166 for storage in increased_storage_types {
5167 // Verify the expected storage increased.
5168 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005169 let old = &baseline[&storage.0];
5170 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005171 assert!(
5172 new.unused_size <= old.unused_size,
5173 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005174 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005175 new.unused_size,
5176 old.unused_size
5177 );
5178
5179 // Update the baseline with the new value so that it succeeds in the
5180 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005181 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005182 }
5183
5184 // Get an updated map of the storage and verify there were no unexpected changes.
5185 let updated_stats = get_storage_stats_map(db);
5186 assert_eq!(updated_stats.len(), baseline.len());
5187
5188 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005189 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005190 let mut s = String::new();
5191 for &k in map.keys() {
5192 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5193 .expect("string concat failed");
5194 }
5195 s
5196 };
5197
5198 assert!(
5199 updated_stats[&k].size == baseline[&k].size
5200 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5201 "updated_stats:\n{}\nbaseline:\n{}",
5202 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005203 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005204 );
5205 }
5206 }
5207
5208 #[test]
5209 fn test_verify_key_table_size_reporting() -> Result<()> {
5210 let mut db = new_test_db()?;
5211 let mut working_stats = get_storage_stats_map(&mut db);
5212
David Drysdale8c4c4f32023-10-31 12:14:11 +00005213 let key_id = create_key_entry(&mut db, &Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005214 assert_storage_increased(
5215 &mut db,
5216 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005217 MetricsStorage::KEY_ENTRY,
5218 MetricsStorage::KEY_ENTRY_ID_INDEX,
5219 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005220 ],
5221 &mut working_stats,
5222 );
5223
5224 let mut blob_metadata = BlobMetaData::new();
5225 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5226 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5227 assert_storage_increased(
5228 &mut db,
5229 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005230 MetricsStorage::BLOB_ENTRY,
5231 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5232 MetricsStorage::BLOB_METADATA,
5233 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005234 ],
5235 &mut working_stats,
5236 );
5237
5238 let params = make_test_params(None);
5239 db.insert_keyparameter(&key_id, &params)?;
5240 assert_storage_increased(
5241 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005242 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005243 &mut working_stats,
5244 );
5245
5246 let mut metadata = KeyMetaData::new();
5247 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5248 db.insert_key_metadata(&key_id, &metadata)?;
5249 assert_storage_increased(
5250 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005251 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005252 &mut working_stats,
5253 );
5254
5255 let mut sum = 0;
5256 for stat in working_stats.values() {
5257 sum += stat.size;
5258 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005259 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005260 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5261
5262 Ok(())
5263 }
5264
5265 #[test]
5266 fn test_verify_auth_table_size_reporting() -> Result<()> {
5267 let mut db = new_test_db()?;
5268 let mut working_stats = get_storage_stats_map(&mut db);
5269 db.insert_auth_token(&HardwareAuthToken {
5270 challenge: 123,
5271 userId: 456,
5272 authenticatorId: 789,
5273 authenticatorType: kmhw_authenticator_type::ANY,
5274 timestamp: Timestamp { milliSeconds: 10 },
5275 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005276 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005277 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005278 Ok(())
5279 }
5280
5281 #[test]
5282 fn test_verify_grant_table_size_reporting() -> Result<()> {
5283 const OWNER: i64 = 1;
5284 let mut db = new_test_db()?;
5285 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5286
5287 let mut working_stats = get_storage_stats_map(&mut db);
5288 db.grant(
5289 &KeyDescriptor {
5290 domain: Domain::APP,
5291 nspace: 0,
5292 alias: Some(TEST_ALIAS.to_string()),
5293 blob: None,
5294 },
5295 OWNER as u32,
5296 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005297 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005298 |_, _| Ok(()),
5299 )?;
5300
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005301 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005302
5303 Ok(())
5304 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005305
5306 #[test]
5307 fn find_auth_token_entry_returns_latest() -> Result<()> {
5308 let mut db = new_test_db()?;
5309 db.insert_auth_token(&HardwareAuthToken {
5310 challenge: 123,
5311 userId: 456,
5312 authenticatorId: 789,
5313 authenticatorType: kmhw_authenticator_type::ANY,
5314 timestamp: Timestamp { milliSeconds: 10 },
5315 mac: b"mac0".to_vec(),
5316 });
5317 std::thread::sleep(std::time::Duration::from_millis(1));
5318 db.insert_auth_token(&HardwareAuthToken {
5319 challenge: 123,
5320 userId: 457,
5321 authenticatorId: 789,
5322 authenticatorType: kmhw_authenticator_type::ANY,
5323 timestamp: Timestamp { milliSeconds: 12 },
5324 mac: b"mac1".to_vec(),
5325 });
5326 std::thread::sleep(std::time::Duration::from_millis(1));
5327 db.insert_auth_token(&HardwareAuthToken {
5328 challenge: 123,
5329 userId: 458,
5330 authenticatorId: 789,
5331 authenticatorType: kmhw_authenticator_type::ANY,
5332 timestamp: Timestamp { milliSeconds: 3 },
5333 mac: b"mac2".to_vec(),
5334 });
5335 // All three entries are in the database
5336 assert_eq!(db.perboot.auth_tokens_len(), 3);
5337 // It selected the most recent timestamp
Eric Biggersb5613da2024-03-13 19:31:42 +00005338 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().auth_token.mac, b"mac2".to_vec());
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005339 Ok(())
5340 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005341
5342 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005343 fn test_load_key_descriptor() -> Result<()> {
5344 let mut db = new_test_db()?;
5345 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5346
5347 let key = db.load_key_descriptor(key_id)?.unwrap();
5348
5349 assert_eq!(key.domain, Domain::APP);
5350 assert_eq!(key.nspace, 1);
5351 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5352
5353 // No such id
5354 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5355 Ok(())
5356 }
Eran Messeri4dc27b52024-01-09 12:43:31 +00005357
5358 #[test]
5359 fn test_get_list_app_uids_for_sid() -> Result<()> {
5360 let uid: i32 = 1;
5361 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5362 let first_sid = 667;
5363 let second_sid = 669;
5364 let first_app_id: i64 = 123 + uid_offset;
5365 let second_app_id: i64 = 456 + uid_offset;
5366 let third_app_id: i64 = 789 + uid_offset;
5367 let unrelated_app_id: i64 = 1011 + uid_offset;
5368 let mut db = new_test_db()?;
5369 make_test_key_entry_with_sids(
5370 &mut db,
5371 Domain::APP,
5372 first_app_id,
5373 TEST_ALIAS,
5374 None,
5375 &[first_sid],
5376 )
5377 .context("test_get_list_app_uids_for_sid")?;
5378 make_test_key_entry_with_sids(
5379 &mut db,
5380 Domain::APP,
5381 second_app_id,
5382 "alias2",
5383 None,
5384 &[first_sid],
5385 )
5386 .context("test_get_list_app_uids_for_sid")?;
5387 make_test_key_entry_with_sids(
5388 &mut db,
5389 Domain::APP,
5390 second_app_id,
5391 TEST_ALIAS,
5392 None,
5393 &[second_sid],
5394 )
5395 .context("test_get_list_app_uids_for_sid")?;
5396 make_test_key_entry_with_sids(
5397 &mut db,
5398 Domain::APP,
5399 third_app_id,
5400 "alias3",
5401 None,
5402 &[second_sid],
5403 )
5404 .context("test_get_list_app_uids_for_sid")?;
5405 make_test_key_entry_with_sids(
5406 &mut db,
5407 Domain::APP,
5408 unrelated_app_id,
5409 TEST_ALIAS,
5410 None,
5411 &[],
5412 )
5413 .context("test_get_list_app_uids_for_sid")?;
5414
5415 let mut first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5416 first_sid_apps.sort();
5417 assert_eq!(first_sid_apps, vec![first_app_id, second_app_id]);
5418 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5419 second_sid_apps.sort();
5420 assert_eq!(second_sid_apps, vec![second_app_id, third_app_id]);
5421 Ok(())
5422 }
5423
5424 #[test]
5425 fn test_get_list_app_uids_with_multiple_sids() -> Result<()> {
5426 let uid: i32 = 1;
5427 let uid_offset: i64 = (uid as i64) * (AID_USER_OFFSET as i64);
5428 let first_sid = 667;
5429 let second_sid = 669;
5430 let third_sid = 772;
5431 let first_app_id: i64 = 123 + uid_offset;
5432 let second_app_id: i64 = 456 + uid_offset;
5433 let mut db = new_test_db()?;
5434 make_test_key_entry_with_sids(
5435 &mut db,
5436 Domain::APP,
5437 first_app_id,
5438 TEST_ALIAS,
5439 None,
5440 &[first_sid, second_sid],
5441 )
5442 .context("test_get_list_app_uids_for_sid")?;
5443 make_test_key_entry_with_sids(
5444 &mut db,
5445 Domain::APP,
5446 second_app_id,
5447 "alias2",
5448 None,
5449 &[second_sid, third_sid],
5450 )
5451 .context("test_get_list_app_uids_for_sid")?;
5452
5453 let first_sid_apps = db.get_app_uids_affected_by_sid(uid, first_sid)?;
5454 assert_eq!(first_sid_apps, vec![first_app_id]);
5455
5456 let mut second_sid_apps = db.get_app_uids_affected_by_sid(uid, second_sid)?;
5457 second_sid_apps.sort();
5458 assert_eq!(second_sid_apps, vec![first_app_id, second_app_id]);
5459
5460 let third_sid_apps = db.get_app_uids_affected_by_sid(uid, third_sid)?;
5461 assert_eq!(third_sid_apps, vec![second_app_id]);
5462 Ok(())
5463 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005464}